Spaces:
Running
on
Zero
Running
on
Zero
test egogpt
Browse files
app.py
CHANGED
@@ -1,64 +1,469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
"""
|
5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
"""
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
|
|
9 |
|
10 |
-
def respond(
|
11 |
-
message,
|
12 |
-
history: list[tuple[str, str]],
|
13 |
-
system_message,
|
14 |
-
max_tokens,
|
15 |
-
temperature,
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
-
|
|
|
|
|
|
|
27 |
|
28 |
-
|
|
|
29 |
|
30 |
-
|
31 |
-
messages,
|
32 |
-
max_tokens=max_tokens,
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
|
|
42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
-
demo = gr.ChatInterface(
|
47 |
-
respond,
|
48 |
-
additional_inputs=[
|
49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
-
)
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
|
|
|
1 |
+
### ----------------- ###
|
2 |
+
# Standard library imports
|
3 |
+
import os
|
4 |
+
import re
|
5 |
+
import sys
|
6 |
+
import copy
|
7 |
+
import warnings
|
8 |
+
from typing import Optional
|
9 |
+
|
10 |
+
# Third-party imports
|
11 |
+
import numpy as np
|
12 |
+
import torch
|
13 |
+
import torch.distributed as dist
|
14 |
+
import uvicorn
|
15 |
+
import librosa
|
16 |
+
import whisper
|
17 |
+
import requests
|
18 |
+
from fastapi import FastAPI
|
19 |
+
from pydantic import BaseModel
|
20 |
+
from decord import VideoReader, cpu
|
21 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
22 |
+
|
23 |
import gradio as gr
|
24 |
+
import spaces
|
25 |
+
|
26 |
+
# Local imports
|
27 |
+
from egogpt.model.builder import load_pretrained_model
|
28 |
+
from egogpt.mm_utils import get_model_name_from_path, process_images
|
29 |
+
from egogpt.constants import (
|
30 |
+
IMAGE_TOKEN_INDEX,
|
31 |
+
DEFAULT_IMAGE_TOKEN,
|
32 |
+
IGNORE_INDEX,
|
33 |
+
SPEECH_TOKEN_INDEX,
|
34 |
+
DEFAULT_SPEECH_TOKEN
|
35 |
+
)
|
36 |
+
from egogpt.conversation import conv_templates, SeparatorStyle
|
37 |
+
|
38 |
+
|
39 |
+
# pretrained = "/mnt/sfs-common/jkyang/EgoGPT/checkpoints/EgoGPT-llavaov-7b-EgoIT-109k-release"
|
40 |
+
pretrained = "/mnt/sfs-common/jkyang/EgoGPT/checkpoints/EgoGPT-llavaov-7b-EgoIT-EgoLife-Demo"
|
41 |
+
device = "cuda"
|
42 |
+
device_map = "cuda"
|
43 |
|
44 |
+
# Add this initialization code before loading the model
|
45 |
+
def setup(rank, world_size):
|
46 |
+
os.environ['MASTER_ADDR'] = 'localhost'
|
47 |
+
os.environ['MASTER_PORT'] = '12377'
|
48 |
+
|
49 |
+
# initialize the process group
|
50 |
+
dist.init_process_group("gloo", rank=rank, world_size=world_size)
|
51 |
+
|
52 |
+
setup(0,1)
|
53 |
+
tokenizer, model, max_length = load_pretrained_model(pretrained,device_map=device_map)
|
54 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
55 |
+
model.to(device).eval()
|
56 |
+
|
57 |
+
title_markdown = """
|
58 |
+
<div style="display: flex; justify-content: space-between; align-items: center; background: linear-gradient(90deg, rgba(72,219,251,0.1), rgba(29,209,161,0.1)); border-radius: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); padding: 20px; margin-bottom: 20px;">
|
59 |
+
<div style="display: flex; align-items: center;">
|
60 |
+
<a href="https://egolife-ntu.github.io/" style="margin-right: 20px; text-decoration: none; display: flex; align-items: center;">
|
61 |
+
<img src="https://egolife-ntu.github.io/egolife.png" alt="EgoLife" style="max-width: 100px; height: auto; border-radius: 15px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
|
62 |
+
</a>
|
63 |
+
<div>
|
64 |
+
<h1 style="margin: 0; background: linear-gradient(90deg, #48dbfb, #1dd1a1); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 2.5em; font-weight: 700;">EgoLife</h1>
|
65 |
+
<h2 style="margin: 10px 0; color: #2d3436; font-weight: 500;">Towards Egocentric Life Assistant</h2>
|
66 |
+
<div style="display: flex; gap: 15px; margin-top: 10px;">
|
67 |
+
<a href="https://egolife-ntu.github.io/" style="text-decoration: none; color: #48dbfb; font-weight: 500; transition: color 0.3s;">Project Page</a> |
|
68 |
+
<a href="https://github.com/egolife-ntu/EgoGPT" style="text-decoration: none; color: #48dbfb; font-weight: 500; transition: color 0.3s;">Github</a> |
|
69 |
+
<a href="https://huggingface.co/lmms-lab" style="text-decoration: none; color: #48dbfb; font-weight: 500; transition: color 0.3s;">Huggingface</a> |
|
70 |
+
<a href="https://arxiv.org/" style="text-decoration: none; color: #48dbfb; font-weight: 500; transition: color 0.3s;">Paper</a> |
|
71 |
+
<a href="https://x.com/" style="text-decoration: none; color: #48dbfb; font-weight: 500; transition: color 0.3s;">Twitter (X)</a>
|
72 |
+
</div>
|
73 |
+
</div>
|
74 |
+
</div>
|
75 |
+
<div style="text-align: right; margin-left: 20px;">
|
76 |
+
<h1 style="margin: 0; background: linear-gradient(90deg, #48dbfb, #1dd1a1); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 2.5em; font-weight: 700;">EgoGPT</h1>
|
77 |
+
<h2 style="margin: 10px 0; background: linear-gradient(90deg, #48dbfb, #1dd1a1); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 1.8em; font-weight: 600;">An Egocentric Video-Audio-Text Model<br>from EgoLife Project</h2>
|
78 |
+
</div>
|
79 |
+
</div>
|
80 |
"""
|
81 |
+
|
82 |
+
bibtext = """
|
83 |
+
### Citation
|
84 |
+
```
|
85 |
+
@article{yang2025egolife,
|
86 |
+
title={EgoLife\: Towards Egocentric Life Assistant},
|
87 |
+
author={The EgoLife Team},
|
88 |
+
journal={arXiv preprint arXiv:25xxx},
|
89 |
+
year={2025}
|
90 |
+
}
|
91 |
+
```
|
92 |
"""
|
|
|
93 |
|
94 |
+
cur_dir = os.path.dirname(os.path.abspath(__file__))
|
95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
+
def time_to_frame_idx(time_int: int, fps: int) -> int:
|
98 |
+
"""
|
99 |
+
Convert time in HHMMSSFF format (integer or string) to frame index.
|
100 |
+
:param time_int: Time in HHMMSSFF format, e.g., 10483000 (10:48:30.00) or "10483000".
|
101 |
+
:param fps: Frames per second of the video.
|
102 |
+
:return: Frame index corresponding to the given time.
|
103 |
+
"""
|
104 |
+
# Ensure time_int is a string for slicing
|
105 |
+
time_str = str(time_int).zfill(
|
106 |
+
8) # Pad with zeros if necessary to ensure it's 8 digits
|
107 |
|
108 |
+
hours = int(time_str[:2])
|
109 |
+
minutes = int(time_str[2:4])
|
110 |
+
seconds = int(time_str[4:6])
|
111 |
+
frames = int(time_str[6:8])
|
112 |
|
113 |
+
total_seconds = hours * 3600 + minutes * 60 + seconds
|
114 |
+
total_frames = total_seconds * fps + frames # Convert to total frames
|
115 |
|
116 |
+
return total_frames
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
|
118 |
+
def split_text(text, keywords):
|
119 |
+
# 创建一个正则表达式模式,将所有关键词用 | 连接,并使用捕获组
|
120 |
+
pattern = '(' + '|'.join(map(re.escape, keywords)) + ')'
|
121 |
+
# 使用 re.split 保留分隔符
|
122 |
+
parts = re.split(pattern, text)
|
123 |
+
# 去除空字符串
|
124 |
+
parts = [part for part in parts if part]
|
125 |
+
return parts
|
126 |
|
127 |
+
warnings.filterwarnings("ignore")
|
128 |
|
129 |
+
# Create FastAPI instance
|
130 |
+
app = FastAPI()
|
131 |
+
def load_video(
|
132 |
+
video_path: Optional[str] = None,
|
133 |
+
max_frames_num: int = 16,
|
134 |
+
fps: int = 1,
|
135 |
+
video_start_time: Optional[float] = None,
|
136 |
+
start_time: Optional[float] = None,
|
137 |
+
end_time: Optional[float] = None,
|
138 |
+
time_based_processing: bool = False
|
139 |
+
) -> tuple:
|
140 |
+
vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
|
141 |
+
target_sr = 16000
|
142 |
+
|
143 |
+
# Add new time-based processing logic
|
144 |
+
if time_based_processing:
|
145 |
+
# Initialize video reader
|
146 |
+
vr = decord.VideoReader(video_path, ctx=decord.cpu(0), num_threads=1)
|
147 |
+
total_frame_num = len(vr)
|
148 |
+
|
149 |
+
# Get the actual FPS of the video
|
150 |
+
video_fps = vr.get_avg_fps()
|
151 |
+
|
152 |
+
# Convert time to frame index based on the actual video FPS
|
153 |
+
video_start_frame = int(time_to_frame_idx(video_start_time, video_fps))
|
154 |
+
start_frame = int(time_to_frame_idx(start_time, video_fps))
|
155 |
+
end_frame = int(time_to_frame_idx(end_time, video_fps))
|
156 |
+
|
157 |
+
print("start frame", start_frame)
|
158 |
+
print("end frame", end_frame)
|
159 |
+
|
160 |
+
# Ensure the end time does not exceed the total frame number
|
161 |
+
if end_frame - start_frame > total_frame_num:
|
162 |
+
end_frame = total_frame_num + start_frame
|
163 |
+
|
164 |
+
# Adjust start_frame and end_frame based on video start time
|
165 |
+
start_frame -= video_start_frame
|
166 |
+
end_frame -= video_start_frame
|
167 |
+
start_frame = max(0, int(round(start_frame))) # 确保不会小于0
|
168 |
+
end_frame = min(total_frame_num, int(round(end_frame))) # 确保不会超过总帧数
|
169 |
+
start_frame = int(round(start_frame))
|
170 |
+
end_frame = int(round(end_frame))
|
171 |
+
|
172 |
+
# Sample frames based on the provided fps (e.g., 1 frame per second)
|
173 |
+
frame_idx = [i for i in range(start_frame, end_frame) if (i - start_frame) % int(video_fps / fps) == 0]
|
174 |
+
|
175 |
+
# Get the video frames for the sampled indices
|
176 |
+
video = vr.get_batch(frame_idx).asnumpy()
|
177 |
+
target_sr = 16000 # Set target sample rate to 16kHz
|
178 |
+
|
179 |
+
# Load audio from video with resampling
|
180 |
+
y, _ = librosa.load(video_path, sr=target_sr)
|
181 |
+
|
182 |
+
# Convert time to audio samples (using 16kHz sample rate)
|
183 |
+
start_sample = int(start_time * target_sr)
|
184 |
+
end_sample = int(end_time * target_sr)
|
185 |
+
|
186 |
+
# Extract audio segment
|
187 |
+
speech = y[start_sample:end_sample]
|
188 |
+
else:
|
189 |
+
# Original processing logic
|
190 |
+
speech, _ = librosa.load(video_path, sr=target_sr)
|
191 |
+
total_frame_num = len(vr)
|
192 |
+
avg_fps = round(vr.get_avg_fps() / fps)
|
193 |
+
frame_idx = [i for i in range(0, total_frame_num, avg_fps)]
|
194 |
+
|
195 |
+
if max_frames_num > 0:
|
196 |
+
if len(frame_idx) > max_frames_num:
|
197 |
+
uniform_sampled_frames = np.linspace(0, total_frame_num - 1, max_frames_num, dtype=int)
|
198 |
+
frame_idx = uniform_sampled_frames.tolist()
|
199 |
+
|
200 |
+
video = vr.get_batch(frame_idx).asnumpy()
|
201 |
+
|
202 |
+
# Process audio
|
203 |
+
speech = whisper.pad_or_trim(speech.astype(np.float32))
|
204 |
+
speech = whisper.log_mel_spectrogram(speech, n_mels=128).permute(1, 0)
|
205 |
+
speech_lengths = torch.LongTensor([speech.shape[0]])
|
206 |
+
|
207 |
+
return video, speech, speech_lengths
|
208 |
+
|
209 |
+
class PromptRequest(BaseModel):
|
210 |
+
prompt: str
|
211 |
+
video_path: str = None
|
212 |
+
max_frames_num: int = 16
|
213 |
+
fps: int = 1
|
214 |
+
video_start_time: float = None
|
215 |
+
start_time: float = None
|
216 |
+
end_time: float = None
|
217 |
+
time_based_processing: bool = False
|
218 |
+
|
219 |
+
# @spaces.GPU(duration=120)
|
220 |
+
def generate_text(video_path, audio_track, prompt):
|
221 |
+
max_frames_num = 30
|
222 |
+
fps = 1
|
223 |
+
# model.eval()
|
224 |
+
|
225 |
+
# Video + speech branch
|
226 |
+
conv_template = "qwen_1_5" # Make sure you use correct chat template for different models
|
227 |
+
question = f"<image>\n{prompt}"
|
228 |
+
conv = copy.deepcopy(conv_templates[conv_template])
|
229 |
+
conv.append_message(conv.roles[0], question)
|
230 |
+
conv.append_message(conv.roles[1], None)
|
231 |
+
prompt_question = conv.get_prompt()
|
232 |
+
|
233 |
+
video, speech, speech_lengths = load_video(
|
234 |
+
video_path=video_path,
|
235 |
+
max_frames_num=max_frames_num,
|
236 |
+
fps=fps,
|
237 |
+
)
|
238 |
+
speech=torch.stack([speech]).to("cuda").half()
|
239 |
+
processor = model.get_vision_tower().image_processor
|
240 |
+
processed_video = processor.preprocess(video, return_tensors="pt")["pixel_values"]
|
241 |
+
image = [(processed_video, video[0].size, "video")]
|
242 |
+
|
243 |
+
print(prompt_question)
|
244 |
+
parts=split_text(prompt_question,["<image>","<speech>"])
|
245 |
+
input_ids=[]
|
246 |
+
for part in parts:
|
247 |
+
if "<image>"==part:
|
248 |
+
input_ids+=[IMAGE_TOKEN_INDEX]
|
249 |
+
elif "<speech>"==part:
|
250 |
+
input_ids+=[SPEECH_TOKEN_INDEX]
|
251 |
+
else:
|
252 |
+
input_ids+=tokenizer(part).input_ids
|
253 |
+
|
254 |
+
input_ids = torch.tensor(input_ids,dtype=torch.long).unsqueeze(0).to(device)
|
255 |
+
image_tensor = [image[0][0].half()]
|
256 |
+
image_sizes = [image[0][1]]
|
257 |
+
|
258 |
+
generate_kwargs={"eos_token_id":tokenizer.eos_token_id}
|
259 |
+
print(input_ids)
|
260 |
+
cont = model.generate(
|
261 |
+
input_ids,
|
262 |
+
images=image_tensor,
|
263 |
+
image_sizes=image_sizes,
|
264 |
+
speech=speech,
|
265 |
+
speech_lengths=speech_lengths,
|
266 |
+
do_sample=False,
|
267 |
+
temperature=0.5,
|
268 |
+
max_new_tokens=4096,
|
269 |
+
modalities=["video"],
|
270 |
+
**generate_kwargs
|
271 |
+
)
|
272 |
+
|
273 |
+
text_outputs = tokenizer.batch_decode(cont, skip_special_tokens=True)
|
274 |
+
|
275 |
+
return text_outputs[0]
|
276 |
+
|
277 |
+
def extract_audio_from_video(video_path, audio_path=None):
|
278 |
+
if audio_path:
|
279 |
+
try:
|
280 |
+
y, sr = librosa.load(audio_path, sr=8000, mono=True, res_type='kaiser_fast')
|
281 |
+
return (sr, y)
|
282 |
+
except Exception as e:
|
283 |
+
print(f"Error loading audio from {audio_path}: {e}")
|
284 |
+
return None
|
285 |
+
if video_path is None:
|
286 |
+
return None
|
287 |
+
try:
|
288 |
+
y, sr = librosa.load(video_path, sr=8000, mono=True, res_type='kaiser_fast')
|
289 |
+
return (sr, y)
|
290 |
+
except Exception as e:
|
291 |
+
print(f"Error extracting audio from video: {e}")
|
292 |
+
return None
|
293 |
+
|
294 |
+
head = """
|
295 |
+
<style>
|
296 |
+
/* Submit按钮默认和悬停效果 */
|
297 |
+
button.lg.secondary.svelte-5st68j {
|
298 |
+
background-color: #ff9933 !important;
|
299 |
+
transition: background-color 0.3s ease !important;
|
300 |
+
}
|
301 |
+
|
302 |
+
button.lg.secondary.svelte-5st68j:hover {
|
303 |
+
background-color: #ff7777 !important; /* 悬停时颜色加深 */
|
304 |
+
}
|
305 |
+
|
306 |
+
/* 确保按钮文字始终清晰可见 */
|
307 |
+
button.lg.secondary.svelte-5st68j span {
|
308 |
+
color: white !important;
|
309 |
+
}
|
310 |
+
|
311 |
+
/* 隐藏表头中的第二列 */
|
312 |
+
.table-wrap .svelte-p5q82i th:nth-child(2) {
|
313 |
+
display: none;
|
314 |
+
}
|
315 |
+
|
316 |
+
/* 隐藏表格内容中的第二列 */
|
317 |
+
.table-wrap .svelte-p5q82i td:nth-child(2) {
|
318 |
+
display: none;
|
319 |
+
}
|
320 |
+
|
321 |
+
.table-wrap {
|
322 |
+
max-height: 300px;
|
323 |
+
overflow-y: auto;
|
324 |
+
}
|
325 |
+
|
326 |
+
</style>
|
327 |
+
|
328 |
+
<script>
|
329 |
+
function initializeControls() {
|
330 |
+
const video = document.querySelector('[data-testid="Video-player"]');
|
331 |
+
const waveform = document.getElementById('waveform');
|
332 |
+
|
333 |
+
// 如果元素还没准备好,直接返回
|
334 |
+
if (!video || !waveform) {
|
335 |
+
return;
|
336 |
+
}
|
337 |
+
|
338 |
+
// 尝试获取音频元素
|
339 |
+
const audio = waveform.querySelector('div')?.shadowRoot?.querySelector('audio');
|
340 |
+
if (!audio) {
|
341 |
+
return;
|
342 |
+
}
|
343 |
+
|
344 |
+
console.log('Elements found:', { video, audio });
|
345 |
+
|
346 |
+
// 监听视频播放进度
|
347 |
+
video.addEventListener("play", () => {
|
348 |
+
if (audio.paused) {
|
349 |
+
audio.play(); // 如果音频暂停,开始播放
|
350 |
+
}
|
351 |
+
});
|
352 |
+
|
353 |
+
// 监听音频播放进度
|
354 |
+
audio.addEventListener("play", () => {
|
355 |
+
if (video.paused) {
|
356 |
+
video.play(); // 如果视频暂停,开始播放
|
357 |
+
}
|
358 |
+
});
|
359 |
+
|
360 |
+
// 同步视频和音频的播放进度
|
361 |
+
video.addEventListener("timeupdate", () => {
|
362 |
+
if (Math.abs(video.currentTime - audio.currentTime) > 0.1) {
|
363 |
+
audio.currentTime = video.currentTime; // 如果时间差超过0.1秒,同步
|
364 |
+
}
|
365 |
+
});
|
366 |
+
|
367 |
+
audio.addEventListener("timeupdate", () => {
|
368 |
+
if (Math.abs(audio.currentTime - video.currentTime) > 0.1) {
|
369 |
+
video.currentTime = audio.currentTime; // 如果时间差超过0.1秒,同步
|
370 |
+
}
|
371 |
+
});
|
372 |
+
|
373 |
+
// 监听暂停事件,确保视频和音频都暂停
|
374 |
+
video.addEventListener("pause", () => {
|
375 |
+
if (!audio.paused) {
|
376 |
+
audio.pause(); // 如果音频未暂停,暂停音频
|
377 |
+
}
|
378 |
+
});
|
379 |
+
|
380 |
+
audio.addEventListener("pause", () => {
|
381 |
+
if (!video.paused) {
|
382 |
+
video.pause(); // 如果视频未暂停,暂停视频
|
383 |
+
}
|
384 |
+
});
|
385 |
+
}
|
386 |
+
|
387 |
+
// 创建观察器监听DOM变化
|
388 |
+
const observer = new MutationObserver((mutations) => {
|
389 |
+
for (const mutation of mutations) {
|
390 |
+
if (mutation.addedNodes.length) {
|
391 |
+
// 当有新节点添加时,尝试初始化
|
392 |
+
const waveform = document.getElementById('waveform');
|
393 |
+
if (waveform?.querySelector('div')?.shadowRoot?.querySelector('audio')) {
|
394 |
+
console.log('Audio element detected');
|
395 |
+
initializeControls();
|
396 |
+
// 可选:如果不需要继续监听,可以断开观察器
|
397 |
+
// observer.disconnect();
|
398 |
+
}
|
399 |
+
}
|
400 |
+
}
|
401 |
+
});
|
402 |
+
|
403 |
+
// 开始观察
|
404 |
+
observer.observe(document.body, {
|
405 |
+
childList: true,
|
406 |
+
subtree: true
|
407 |
+
});
|
408 |
+
|
409 |
+
// 页面加载完成时也尝试初始化
|
410 |
+
document.addEventListener('DOMContentLoaded', () => {
|
411 |
+
console.log('DOM Content Loaded');
|
412 |
+
initializeControls();
|
413 |
+
});
|
414 |
+
|
415 |
+
</script>
|
416 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
417 |
|
418 |
+
with gr.Blocks(head=head) as demo:
|
419 |
+
gr.Markdown(title_markdown)
|
420 |
+
|
421 |
+
with gr.Row():
|
422 |
+
with gr.Column():
|
423 |
+
video_input = gr.Video(label="Video", autoplay=True, loop=True, format="mp4", width=600, height=400, show_label=False, elem_id='video')
|
424 |
+
# Audio input synchronized with video playback
|
425 |
+
audio_display = gr.Audio(label="Video Audio Track", autoplay=False, show_label=True, visible=True, interactive=False, elem_id="audio")
|
426 |
+
text_input = gr.Textbox(label="Question", placeholder="Enter your message here...")
|
427 |
+
|
428 |
+
with gr.Column(): # Create a separate column for output and examples
|
429 |
+
output_text = gr.Textbox(label="Response", lines=14, max_lines=14)
|
430 |
+
gr.Examples(
|
431 |
+
examples=[
|
432 |
+
[f"{cur_dir}/videos/bike.mp4", f"{cur_dir}/videos/bike.mp3", "Can you tell me what I'm doing in short words. Describe them in a natural style."],
|
433 |
+
[f"{cur_dir}/videos/bike.mp4", f"{cur_dir}/videos/bike.mp3", "Can you tell me what I'm doing in short words. Describe them in a natural style."],
|
434 |
+
[f"{cur_dir}/videos/bike.mp4", f"{cur_dir}/videos/bike.mp3", "Can you tell me what I'm doing in short words. Describe them in a natural style."],
|
435 |
+
[f"{cur_dir}/videos/bike.mp4", f"{cur_dir}/videos/bike.mp3", "Can you tell me what I'm doing in short words. Describe them in a natural style."]
|
436 |
+
],
|
437 |
+
inputs=[video_input, audio_display, text_input],
|
438 |
+
outputs=[output_text]
|
439 |
+
)
|
440 |
+
|
441 |
+
# Add event handler for video changes
|
442 |
+
video_input.change(
|
443 |
+
fn=lambda video_path: extract_audio_from_video(video_path, audio_path=None),
|
444 |
+
inputs=[video_input],
|
445 |
+
outputs=[audio_display]
|
446 |
+
)
|
447 |
+
|
448 |
+
# Add event handler for video clear/delete
|
449 |
+
def clear_outputs(video):
|
450 |
+
if video is None: # Video is cleared/deleted
|
451 |
+
return ""
|
452 |
+
return gr.skip() # Keep existing text if video exists
|
453 |
+
|
454 |
+
video_input.change(
|
455 |
+
fn=clear_outputs,
|
456 |
+
inputs=[video_input],
|
457 |
+
outputs=[output_text]
|
458 |
+
)
|
459 |
+
|
460 |
+
# Add submit button and its event handler
|
461 |
+
submit_btn = gr.Button("Submit")
|
462 |
+
submit_btn.click(
|
463 |
+
fn=generate_text,
|
464 |
+
inputs=[video_input, audio_display, text_input],
|
465 |
+
outputs=[output_text]
|
466 |
+
)
|
467 |
|
468 |
+
# Launch the Gradio app
|
469 |
+
demo.launch(share=True)
|