File size: 17,760 Bytes
dbc3c35 89e1dc4 dbc3c35 5dadf47 dbc3c35 5dadf47 dbc3c35 5dadf47 dbc3c35 5dadf47 dbc3c35 89e1dc4 dbc3c35 5dadf47 dbc3c35 5dadf47 dbc3c35 5dadf47 dbc3c35 6eb98ab dbc3c35 6eb98ab 5dadf47 6eb98ab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 | import json
import re
from uuid import uuid4
from app.core.config import Settings
from app.models.schemas import ChannelProfile, ClipCandidate, SubtitleCue, TranscriptSegment
class QwenHighlightDetector:
def __init__(self, settings: Settings) -> None:
self.settings = settings
self._llm = None
def detect(
self, transcript: list[TranscriptSegment], profile: ChannelProfile
) -> list[ClipCandidate]:
if self.settings.demo_mode:
return self._heuristic_detect(transcript, profile)
try:
return self._qwen_detect(transcript, profile)
except Exception:
return self._heuristic_detect(transcript, profile)
def _qwen_detect(
self, transcript: list[TranscriptSegment], profile: ChannelProfile
) -> list[ClipCandidate]:
try:
from vllm import LLM, SamplingParams
except Exception as exc:
raise RuntimeError("vLLM with ROCm backend is required for Qwen inference") from exc
if self._llm is None:
self._llm = LLM(
model=self.settings.qwen_text_model_id,
dtype=self.settings.preferred_torch_dtype,
trust_remote_code=True,
)
transcript_text = "\n".join(
f"[{segment.start_seconds:.1f}-{segment.end_seconds:.1f}] {segment.text}"
for segment in transcript
)
niche = _effective_niche(profile)
channel_description = profile.channel_description or "No extra channel description provided."
clip_count = min(profile.clip_count, self.settings.max_clips)
prompt = f"""
You are selecting short-form clips for a creator.
Profile:
- niche: {niche}
- creator description: {channel_description}
- style: {profile.clip_style}
- target length seconds: {profile.clip_length_seconds}
- target number of clips: {clip_count}
- language: {profile.primary_language}
- platform: {profile.target_platform.value}
Return strict JSON only. Shape:
[
{{
"start_seconds": 12.0,
"end_seconds": 72.0,
"title": "short title",
"reason": "why this will engage viewers",
"score": 91,
"subtitle_text": "clean subtitle text"
}}
]
Transcript:
{transcript_text}
""".strip()
sampling = SamplingParams(temperature=0.2, max_tokens=1200)
outputs = self._llm.generate([prompt], sampling)
text = outputs[0].outputs[0].text
payload = self._parse_json_array(text)
clips = [
ClipCandidate(
id=uuid4().hex,
start_seconds=float(item["start_seconds"]),
end_seconds=float(item["end_seconds"]),
title=str(item.get("title") or "Highlight"),
reason=str(item.get("reason") or "High engagement potential"),
score=float(item.get("score") or 75),
subtitle_text=str(item.get("subtitle_text") or ""),
metadata={"model": self.settings.qwen_text_model_id},
)
for item in payload[:clip_count]
]
return clips or self._heuristic_detect(transcript, profile)
def _parse_json_array(self, text: str) -> list[dict]:
match = re.search(r"\[[\s\S]*\]", text)
if not match:
raise ValueError("No JSON array in Qwen response")
payload = json.loads(match.group(0))
if not isinstance(payload, list):
raise ValueError("Qwen response is not a list")
return payload
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# AI subtitle actions (Polish, Translate)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def polish_subtitles(
self, cues: list[SubtitleCue], style: str | None = None
) -> list[SubtitleCue]:
"""Rewrite cue text to be punchier and more readable on short-form video.
Demo mode returns deterministic polished text so the UX is testable
without GPU. Production mode calls Qwen2.5.
"""
if self.settings.demo_mode:
return self._heuristic_polish(cues, style)
try:
return self._qwen_polish(cues, style)
except Exception:
return self._heuristic_polish(cues, style)
def translate_subtitles(
self, cues: list[SubtitleCue], target_language: str
) -> list[SubtitleCue]:
"""Translate cue text to target_language while preserving timing."""
if self.settings.demo_mode:
return self._heuristic_translate(cues, target_language)
try:
return self._qwen_translate(cues, target_language)
except Exception:
return self._heuristic_translate(cues, target_language)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Demo / fallback implementations
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _heuristic_polish(
self, cues: list[SubtitleCue], style: str | None
) -> list[SubtitleCue]:
"""Apply simple text transformations that look like an AI polish."""
polished: list[SubtitleCue] = []
for cue in cues:
text = (cue.text or "").strip()
if not text:
polished.append(cue.model_copy())
continue
# Shorten redundant phrasing (heuristic)
text = re.sub(r"\s+", " ", text)
text = re.sub(r"^(so|well|like|um|uh|you know|i mean)[,\s]+", "", text, flags=re.IGNORECASE)
text = text.rstrip(" ,.;:")
# Add light emphasis based on style
if style and style.lower() == "dramatic" and not text.endswith("!"):
text = text + "!"
polished.append(
SubtitleCue(
start_seconds=cue.start_seconds,
end_seconds=cue.end_seconds,
text=text,
)
)
return polished
def _heuristic_translate(
self, cues: list[SubtitleCue], target_language: str
) -> list[SubtitleCue]:
"""Demo translation: append a marker so the UX shows the action ran."""
marker = f"[{target_language[:2].upper()}]"
translated: list[SubtitleCue] = []
for cue in cues:
text = (cue.text or "").strip()
translated.append(
SubtitleCue(
start_seconds=cue.start_seconds,
end_seconds=cue.end_seconds,
text=f"{marker} {text}" if text else "",
)
)
return translated
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Production Qwen calls (used when DEMO_MODE=false on AMD GPU)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _ensure_llm(self):
try:
from vllm import LLM
except Exception as exc:
raise RuntimeError("vLLM with ROCm backend is required for Qwen") from exc
if self._llm is None:
self._llm = LLM(
model=self.settings.qwen_text_model_id,
dtype=self.settings.preferred_torch_dtype,
trust_remote_code=True,
)
return self._llm
def _qwen_polish(
self, cues: list[SubtitleCue], style: str | None
) -> list[SubtitleCue]:
from vllm import SamplingParams
llm = self._ensure_llm()
joined = "\n".join(f"{i + 1}. {cue.text}" for i, cue in enumerate(cues))
prompt = f"""
Rewrite each subtitle line to be punchier and easier to read on short-form vertical video.
Keep the same number of lines and the same approximate length per line.
Style preference: {style or 'natural'}.
Return one rewritten line per row, prefixed with the original index. No commentary.
Input:
{joined}
""".strip()
outputs = llm.generate([prompt], SamplingParams(temperature=0.3, max_tokens=800))
raw = outputs[0].outputs[0].text
rewritten = self._parse_indexed_lines(raw, expected=len(cues))
return [
SubtitleCue(
start_seconds=cue.start_seconds,
end_seconds=cue.end_seconds,
text=rewritten[i] if i < len(rewritten) else cue.text,
)
for i, cue in enumerate(cues)
]
def _qwen_translate(
self, cues: list[SubtitleCue], target_language: str
) -> list[SubtitleCue]:
from vllm import SamplingParams
llm = self._ensure_llm()
joined = "\n".join(f"{i + 1}. {cue.text}" for i, cue in enumerate(cues))
prompt = f"""
Translate each subtitle line into {target_language}. Preserve line count and order.
Return one translated line per row, prefixed with the original index. No commentary.
Input:
{joined}
""".strip()
outputs = llm.generate([prompt], SamplingParams(temperature=0.2, max_tokens=1000))
raw = outputs[0].outputs[0].text
translated = self._parse_indexed_lines(raw, expected=len(cues))
return [
SubtitleCue(
start_seconds=cue.start_seconds,
end_seconds=cue.end_seconds,
text=translated[i] if i < len(translated) else cue.text,
)
for i, cue in enumerate(cues)
]
def _parse_indexed_lines(self, raw: str, expected: int) -> list[str]:
lines = []
for line in raw.splitlines():
stripped = line.strip()
if not stripped:
continue
match = re.match(r"^\s*\d+[.)\s-]+\s*(.*)$", stripped)
lines.append(match.group(1).strip() if match else stripped)
if len(lines) >= expected:
break
return lines
def _heuristic_detect(
self, transcript: list[TranscriptSegment], profile: ChannelProfile
) -> list[ClipCandidate]:
style_terms = {
"funny": ["react", "punchy", "mistake", "surprising"],
"informative": ["important", "practical", "takeaway", "explanation"],
"dramatic": ["problem", "surprising", "before-and-after", "stop scrolling"],
"educational": ["question", "answer", "context", "takeaway"],
}
preferred_terms = style_terms.get(profile.clip_style.lower(), [])
niche = _effective_niche(profile)
profile_terms = [
term
for term in f"{niche} {profile.channel_description}".lower().split()[:30]
if len(term) > 2
]
scored: list[tuple[float, TranscriptSegment]] = []
for segment in transcript:
text = segment.text.lower()
score = 45.0
score += 12 if "?" in segment.text else 0
score += 8 if any(term in text for term in preferred_terms) else 0
score += 8 if any(term in text for term in ["mistake", "surprising", "stop scrolling"]) else 0
score += 6 if any(term in text for term in ["takeaway", "answer", "reacts"]) else 0
score += 5 if any(term in text for term in profile_terms) else 0
score += min(len(segment.text) / 12, 10)
scored.append((min(score, 100), segment))
scored.sort(key=lambda item: item[0], reverse=True)
clips: list[ClipCandidate] = []
clip_count = min(profile.clip_count, self.settings.max_clips)
for score, segment in scored[:clip_count]:
start = max(0.0, segment.start_seconds - 5.0)
end = start + float(profile.clip_length_seconds)
clips.append(
ClipCandidate(
id=uuid4().hex,
start_seconds=start,
end_seconds=end,
title=self._title_for(segment.text),
reason=self._reason_for(profile, niche),
score=round(score, 1),
subtitle_text=segment.text,
metadata={"model": "heuristic-fallback"},
)
)
return sorted(clips, key=lambda clip: clip.start_seconds)
def _title_for(self, text: str) -> str:
clean = re.sub(r"\s+", " ", text).strip(" \t\r\n.,!?;:()[]{}\"'")
words = clean.split()
if len(words) > 1:
title = " ".join(words[:7])
else:
title = clean[:48]
return title[:72].rstrip() or "Highlight"
def _reason_for(self, profile: ChannelProfile, niche: str) -> str:
language = profile.primary_language.lower()
style = _localized_profile_word(profile.clip_style, language, "style")
niche_label = _localized_profile_word(niche, language, "niche")
if "thai" in language:
return f"เธเธฃเธเธเธฑเธเธชเนเธเธฅเน {style} เธชเธณเธซเธฃเธฑเธเธเธนเนเธเธกเธเนเธญเธเนเธเธง {niche_label}"
if "japanese" in language:
return f"{niche_label} ใฎ่ฆ่ด่
ใซๅใ {style} ในใฟใคใซใฎๅ่ฃใงใใ"
if "chinese" in language:
return f"็ฌฆๅ {niche_label} ๅไผๆๅพ
็ {style} ้ฃๆ ผใ"
if "korean" in language:
return f"{niche_label} ์์ฒญ์์๊ฒ ๋ง๋ {style} ์คํ์ผ์ ํ๋ณด์
๋๋ค."
return f"Matches the {profile.clip_style} style for a {niche} audience."
def _effective_niche(profile: ChannelProfile) -> str:
if profile.niche.lower() == "other" and profile.niche_custom:
return profile.niche_custom
return profile.niche
def _localized_profile_word(value: str, language: str, group: str) -> str:
key = value.lower().replace(" ", "_")
localized = {
"thai": {
"niche": {
"education": "เธเธฒเธฃเธจเธถเธเธฉเธฒ",
"gaming": "เนเธเธก",
"podcast": "เธเธญเธเนเธเธชเธเน",
"commentary": "เนเธฅเนเธฒ/เธงเธดเนเธเธฃเธฒเธฐเธซเน",
"cars": "เธฃเธเธขเธเธเน",
"beauty": "เธเธดเธงเธเธตเน",
"fitness": "เธเธดเธเนเธเธช",
"finance": "เธเธฒเธฃเนเธเธดเธ",
"tech": "เนเธเธเนเธเนเธฅเธขเธต",
"lifestyle": "เนเธฅเธเนเธชเนเธเธฅเน",
"music": "เธเธเธเธฃเธต",
},
"style": {
"informative": "เนเธซเนเธเนเธญเธกเธนเธฅ",
"funny": "เธเธฅเธ",
"dramatic": "เธเธฃเธฒเธกเนเธฒ",
"educational": "เธชเธญเธเนเธเนเธฒเนเธเธเนเธฒเธข",
"commentary": "เธงเธดเนเธเธฃเธฒเธฐเธซเน",
},
},
"japanese": {
"niche": {
"education": "ๆ่ฒ",
"gaming": "ใฒใผใ ",
"podcast": "ใใใใญใฃในใ",
"commentary": "่งฃ่ชฌ",
"cars": "่ป",
"beauty": "็พๅฎน",
"fitness": "ใใฃใใใใน",
"finance": "้่",
"tech": "ใใใฏ",
"lifestyle": "ใฉใคใในใฟใคใซ",
"music": "้ณๆฅฝ",
},
"style": {
"informative": "ๆ
ๅ ฑๆงใฎ้ซใ",
"funny": "ใฆใผใขใขใฎใใ",
"dramatic": "ใใฉใใใใฏใช",
"educational": "ๅญฆใณใใใ",
"commentary": "่งฃ่ชฌๅใฎ",
},
},
"chinese": {
"niche": {
"education": "ๆ่ฒ",
"gaming": "ๆธธๆ",
"podcast": "ๆญๅฎข",
"commentary": "่งฃ่ฏด",
"cars": "ๆฑฝ่ฝฆ",
"beauty": "็พๅฆ",
"fitness": "ๅฅ่บซ",
"finance": "้่",
"tech": "็งๆ",
"lifestyle": "็ๆดปๆนๅผ",
"music": "้ณไน",
},
"style": {
"informative": "ไฟกๆฏ้้ซ",
"funny": "ๆ่ถฃ",
"dramatic": "ๆๅงๅ",
"educational": "ๆๅญฆๅ",
"commentary": "่ฏ่ฎบๅ",
},
},
"korean": {
"niche": {
"education": "๊ต์ก",
"gaming": "๊ฒ์",
"podcast": "ํ์บ์คํธ",
"commentary": "ํด์ค",
"cars": "์๋์ฐจ",
"beauty": "๋ทฐํฐ",
"fitness": "ํผํธ๋์ค",
"finance": "๊ธ์ต",
"tech": "ํ
ํฌ",
"lifestyle": "๋ผ์ดํ์คํ์ผ",
"music": "์์
",
},
"style": {
"informative": "์ ๋ณดํ",
"funny": "์ฌ๋ฏธ์๋",
"dramatic": "๊ทน์ ์ธ",
"educational": "๊ต์กํ",
"commentary": "ํด์คํ",
},
},
}
for language_key, groups in localized.items():
if language_key in language:
return groups.get(group, {}).get(key, value)
return value
|