Spaces:
Sleeping
Sleeping
app, finetuned_clip.pt, retrieval and requirement files
Browse files- app.py +7 -4
- finetuned_clip.pt +3 -0
- hf_retrieval.py +140 -0
- requirements.txt +8 -0
app.py
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
import gradio as gr
|
2 |
-
from
|
3 |
import requests
|
4 |
|
5 |
def ask_llama_about_chunks(question):
|
@@ -25,10 +25,13 @@ CONTEXT:
|
|
25 |
ANSWER:"""
|
26 |
|
27 |
response = requests.post(
|
28 |
-
"
|
29 |
-
|
|
|
30 |
)
|
31 |
-
|
|
|
|
|
32 |
|
33 |
try:
|
34 |
best_chunk_index = int(answer) - 1
|
|
|
1 |
import gradio as gr
|
2 |
+
from hf_retrieval import *
|
3 |
import requests
|
4 |
|
5 |
def ask_llama_about_chunks(question):
|
|
|
25 |
ANSWER:"""
|
26 |
|
27 |
response = requests.post(
|
28 |
+
"https://api-inference.huggingface.co/models/meta-llama/Llama-3-8b-chat-hf",
|
29 |
+
headers={"Authorization": f"Bearer {os.environ['HF_API_TOKEN']}"},
|
30 |
+
json={"inputs": prompt}
|
31 |
)
|
32 |
+
|
33 |
+
data = response.json()
|
34 |
+
answer = data.get("generated_text", "").strip()
|
35 |
|
36 |
try:
|
37 |
best_chunk_index = int(answer) - 1
|
finetuned_clip.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a4919bea11821485be97e47096777e8a596c64b895eb2c97ee6d0876889ca39a
|
3 |
+
size 605227124
|
hf_retrieval.py
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import open_clip
|
2 |
+
import torch
|
3 |
+
import tempfile
|
4 |
+
import subprocess
|
5 |
+
import os
|
6 |
+
from datetime import datetime
|
7 |
+
from collections import defaultdict
|
8 |
+
from datasets import load_dataset
|
9 |
+
from qdrant_client import QdrantClient
|
10 |
+
|
11 |
+
tokenizer = open_clip.get_tokenizer("ViT-B-32")
|
12 |
+
|
13 |
+
model, _, preprocess = open_clip.create_model_and_transforms("ViT-B-32", pretrained=None)
|
14 |
+
checkpoint_path = "finetuned_clip.pt"
|
15 |
+
model.load_state_dict(torch.load(checkpoint_path, map_location="cpu"))
|
16 |
+
model.eval()
|
17 |
+
|
18 |
+
qdrant = QdrantClient(url=os.environ["QDRANT_CLOUD_URL"],
|
19 |
+
api_key=["QDRANT_API_KEY"])
|
20 |
+
collection_name = "video_chunks"
|
21 |
+
|
22 |
+
|
23 |
+
def timestamp_to_seconds(ts):
|
24 |
+
h, m, s = ts.split(":")
|
25 |
+
return int(h) * 3600 + int(m) * 60 + float(s)
|
26 |
+
|
27 |
+
|
28 |
+
def seconds_to_timestamp(seconds):
|
29 |
+
h = int(seconds // 3600)
|
30 |
+
m = int((seconds % 3600) // 60)
|
31 |
+
s = seconds % 60
|
32 |
+
return f"{h:02}:{m:02}:{s:06.3f}"
|
33 |
+
|
34 |
+
|
35 |
+
def smart_merge_subtitles(a, b):
|
36 |
+
if b in a:
|
37 |
+
return a
|
38 |
+
if a in b:
|
39 |
+
return b
|
40 |
+
|
41 |
+
for i in range(min(len(a), len(b)), 0, -1):
|
42 |
+
if a.endswith(b[:i]):
|
43 |
+
return a + b[i:]
|
44 |
+
if b.endswith(a[:i]):
|
45 |
+
return b + a[i:]
|
46 |
+
return a + " " + b
|
47 |
+
|
48 |
+
|
49 |
+
def merge_chunks(chunks):
|
50 |
+
grouped = defaultdict(list)
|
51 |
+
|
52 |
+
for chunk in chunks:
|
53 |
+
payload = chunk.payload
|
54 |
+
grouped[payload["video_id"]].append({
|
55 |
+
"start": timestamp_to_seconds(payload["start_time"]),
|
56 |
+
"end": timestamp_to_seconds(payload["end_time"]),
|
57 |
+
"subtitle": payload["subtitle"].strip(),
|
58 |
+
"merged": False
|
59 |
+
})
|
60 |
+
|
61 |
+
merged_chunks = []
|
62 |
+
|
63 |
+
for video_id, video_chunks in grouped.items():
|
64 |
+
for i, chunk in enumerate(video_chunks):
|
65 |
+
if chunk["merged"]:
|
66 |
+
continue
|
67 |
+
|
68 |
+
merged_chunk = chunk.copy()
|
69 |
+
chunk["merged"] = True
|
70 |
+
|
71 |
+
for j, other in enumerate(video_chunks):
|
72 |
+
if i == j or other["merged"]:
|
73 |
+
continue
|
74 |
+
|
75 |
+
if not (merged_chunk["end"] < other["start"] or other["end"] < merged_chunk["start"]):
|
76 |
+
merged_chunk["start"] = min(merged_chunk["start"], other["start"])
|
77 |
+
merged_chunk["end"] = max(merged_chunk["end"], other["end"])
|
78 |
+
merged_chunk["subtitle"] = smart_merge_subtitles(merged_chunk["subtitle"], other["subtitle"])
|
79 |
+
other["merged"] = True
|
80 |
+
|
81 |
+
merged_chunks.append({
|
82 |
+
"video_id": video_id,
|
83 |
+
"start_time": seconds_to_timestamp(merged_chunk["start"]),
|
84 |
+
"end_time": seconds_to_timestamp(merged_chunk["end"]),
|
85 |
+
"subtitle": merged_chunk["subtitle"]
|
86 |
+
})
|
87 |
+
|
88 |
+
return merged_chunks
|
89 |
+
|
90 |
+
|
91 |
+
def get_video_segment(video_id, start_time, end_time):
|
92 |
+
dataset = load_dataset("aegean-ai/ai-lectures-spring-24", split="train", streaming=True)
|
93 |
+
for sample in dataset:
|
94 |
+
if sample["__key__"] == video_id:
|
95 |
+
break
|
96 |
+
|
97 |
+
tmp_dir = tempfile.gettempdir()
|
98 |
+
timestamp = datetime.now().strftime("%Y%m%d%H%M%S%f")
|
99 |
+
|
100 |
+
full_path = os.path.join(tmp_dir, f"full_{timestamp}.mp4")
|
101 |
+
trimmed_path = os.path.join(tmp_dir, f"clip_{timestamp}.mp4")
|
102 |
+
|
103 |
+
with open(full_path, "wb") as f:
|
104 |
+
f.write(sample["mp4"])
|
105 |
+
|
106 |
+
cmd = [
|
107 |
+
"ffmpeg", "-ss", start_time, "-to", end_time,
|
108 |
+
"-i", full_path,
|
109 |
+
"-c:v", "copy", "-c:a", "copy", "-y",
|
110 |
+
trimmed_path
|
111 |
+
]
|
112 |
+
|
113 |
+
result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
114 |
+
os.remove(full_path)
|
115 |
+
|
116 |
+
if result.returncode != 0:
|
117 |
+
print("FFmpeg failed")
|
118 |
+
return None
|
119 |
+
|
120 |
+
return trimmed_path
|
121 |
+
|
122 |
+
|
123 |
+
def retrieval(question):
|
124 |
+
text_tokens = tokenizer([question])
|
125 |
+
|
126 |
+
with torch.no_grad():
|
127 |
+
query_vec = model.encode_text(text_tokens).squeeze(0).cpu().numpy()
|
128 |
+
|
129 |
+
search_result = qdrant.search(
|
130 |
+
collection_name=collection_name,
|
131 |
+
query_vector=query_vec.tolist(),
|
132 |
+
limit=40
|
133 |
+
)
|
134 |
+
|
135 |
+
filtered_results = [
|
136 |
+
res for res in search_result
|
137 |
+
if len(res.payload.get("subtitle", "")) >= 35
|
138 |
+
]
|
139 |
+
|
140 |
+
return filtered_results[:10]
|
requirements.txt
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
torch
|
3 |
+
open_clip_torch
|
4 |
+
qdrant-client
|
5 |
+
requests
|
6 |
+
scikit-learn
|
7 |
+
datasets
|
8 |
+
ffmpeg-python
|