ColorfulAI commited on
Commit
4c4edf6
·
verified ·
1 Parent(s): e0b626a

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +115 -0
README.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ datasets:
4
+ - lmms-lab/LLaVA-NeXT-Data
5
+ base_model:
6
+ - meta-llama/Llama-3.1-8B-Instruct
7
+ - openai/clip-vit-large-patch14-336
8
+ - openai/whisper-large-v3
9
+ - ICTNLP/Llama-3.1-8B-Omni
10
+ ---
11
+
12
+
13
+ # OpenOmni-8B-Llama3-Omni
14
+
15
+ OpenOmni-8B-Llama3-Omni is fine-tuned from Llama-3.1-8B-Omni using LLaVA-NeXT by 0.1 epoch.
16
+
17
+ ## Usage
18
+
19
+ *Please refer to [Open-Omni-Nexus](https://github.com/patrick-tssn/Open-Omni-Nexus) to install relvevant packages*
20
+
21
+
22
+ ```python
23
+ import os
24
+ import json
25
+ from PIL import Image
26
+ import numpy as np
27
+ import torchaudio
28
+ import torch
29
+ from decord import VideoReader, cpu
30
+ import whisper
31
+ import soundfile as sf
32
+ # fix seed
33
+ torch.manual_seed(0)
34
+
35
+ from fairseq import utils as fairseq_utils
36
+ from fairseq.models.text_to_speech.vocoder import CodeHiFiGANVocoder
37
+
38
+ from open_omni.model.builder import load_pretrained_model
39
+ from open_omni.mm_utils import tokenizer_image_speech_tokens, process_images, ctc_postprocess
40
+ from open_omni.constants import IMAGE_TOKEN_INDEX, SPEECH_TOKEN_INDEX
41
+
42
+ import warnings
43
+ warnings.filterwarnings("ignore")
44
+
45
+ # config OpenOmni
46
+ model_path = "checkpoints/OpenOmni-8B-Llama3-Omni"
47
+ video_path = "local_demo/assets/water.mp4"
48
+ audio_path = "local_demo/wav/water.mp4.wav"
49
+ max_frames_num = 16 # you can change this to several thousands so long you GPU memory can handle it :)
50
+ gen_kwargs = {"do_sample": True, "temperature": 0.5, "top_p": None, "num_beams": 1, "use_cache": True, "max_new_tokens": 1024}
51
+ tokenizer, model, image_processor, _ = load_pretrained_model(model_path, None, "llava_s2s_llama", device_map="cuda:0") # for qwen -> llava_s2s_qwen
52
+
53
+ # config vocoder
54
+ with open("checkpoints/vocoder/config.json") as f:
55
+ vocoder_cfg = json.load(f)
56
+ vocoder = CodeHiFiGANVocoder("checkpoints/vocoder/g_00500000", vocoder_cfg).cuda()
57
+
58
+ # query input
59
+ query = "Give a detailed caption of the video as if I am blind."
60
+ query = None # comment this to use ChatTTS to convert the query to audio
61
+
62
+ #video input
63
+ prompt = "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<image><|im_end|>\n<|im_start|>user\n<speech>\n<|im_end|>\n<|im_start|>assistant\n"
64
+ input_ids = tokenizer_image_speech_tokens(prompt, tokenizer, IMAGE_TOKEN_INDEX, SPEECH_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(model.device)
65
+ vr = VideoReader(video_path, ctx=cpu(0))
66
+ total_frame_num = len(vr)
67
+ uniform_sampled_frames = np.linspace(0, total_frame_num - 1, max_frames_num, dtype=int)
68
+ frame_idx = uniform_sampled_frames.tolist()
69
+ frames = vr.get_batch(frame_idx).asnumpy()
70
+ video_tensor = image_processor.preprocess(frames, return_tensors="pt")["pixel_values"].to(model.device, dtype=torch.float16)
71
+
72
+ #audio input
73
+ # process speech for input question
74
+ if query is not None:
75
+ import ChatTTS
76
+ chat = ChatTTS.Chat()
77
+ chat.load(source='local', compile=True)
78
+ audio_path = "./local_demo/wav/" + "infer.wav"
79
+ if os.path.exists(audio_path): os.remove(audio_path) # refresh
80
+ if not os.path.exists(audio_path):
81
+ wav = chat.infer(query)
82
+ try:
83
+ torchaudio.save(audio_path, torch.from_numpy(wav).unsqueeze(0), 24000)
84
+ except:
85
+ torchaudio.save(audio_path, torch.from_numpy(wav), 24000)
86
+ print(f"Human: {query}")
87
+
88
+ else:
89
+ print("Human: <audio>")
90
+
91
+ speech = whisper.load_audio(audio_path)
92
+ speech = whisper.pad_or_trim(speech)
93
+ speech = whisper.log_mel_spectrogram(speech, n_mels=128).permute(1, 0).to(device=model.device, dtype=torch.float16)
94
+ speech_length = torch.LongTensor([speech.shape[0]]).to(model.device)
95
+
96
+ with torch.inference_mode():
97
+ output_ids, output_units = model.generate(input_ids, images=[video_tensor], modalities=["video"], speeches=speech.unsqueeze(0), speech_lengths=speech_length, **gen_kwargs)
98
+ outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
99
+ print(f"Agent: {outputs}")
100
+
101
+ output_units = ctc_postprocess(output_units, blank=model.config.unit_vocab_size)
102
+ output_units = [(list(map(int, output_units.strip().split())))]
103
+ print(f"Units: {output_units}")
104
+ x = {"code": torch.LongTensor(output_units[0]).view(1,-1)}
105
+ x = fairseq_utils.move_to_cuda(x)
106
+ wav = vocoder(x, True)
107
+ output_file_path = "local_demo/wav/output.wav"
108
+ sf.write(
109
+ output_file_path,
110
+ wav.detach().cpu().numpy(),
111
+ 16000
112
+ )
113
+ print(f"The generated wav saved to {output_file_path}")
114
+ ```
115
+