Update app.py
Browse files1234567891011121314151617181920212223242530 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131142 unmodified lines11711811912012112212310 unmodified lines1341351361371381391406 unmodified lines14714814915015115214 unmodified lines16716816917017117217317417517617717817918018110 unmodified lines19219319419519619719819920020120220310 unmodified lines2142152162172182192202212228 unmodified lines2312322332342352362372 unmodified lines24024124224324424524620 unmodified lines267268269270271272273274275276277278279# app.pyimport osimport reimport jsonimport timeimport threadingimport gradio as grimport torchfrom transformers import pipelineMODEL_ID = "google/gemma-3-270m-it"HF_TOKEN = os.environ.get("HF_TOKEN")MAX_CONCURRENT_JOBS = 7print("Loading Gemma 3 270M IT...")pipe = pipeline("text-generation",model=MODEL_ID,dtype=torch.bfloat16,device_map="auto",token=HF_TOKEN,)print("β Ready")# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ30 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Fast best-video selection## The model outputs ONLY the position number (1-10) of the best-matching# candidate β no descriptive text. That's a 1-2 token generation instead of# ~150, so this runs many times faster per scene and stays cheap even# across a full script's worth of scenes.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββSELECT_FEW_SHOT = """You match a script line to the best stock video candidate using its tags. Reply with ONLY the number of the best matching candidate. No words, no punctuation, just the number.Script: "The stock market crashed today, wiping out billions."Candidates:1. stock market, crash, finance, chart, money, ticker2. cat, pet, animal, cute, fur3. forest, nature, trees, calmBest: 1Script: "A child learns to ride a bicycle for the first time."Candidates:1. binary code, computer, data, digital2. child, bicycle, learning, park, family, outdoor, happy3. ocean, waves, beach, sunsetBest: 2"""def _format_candidates(videos: list) -> str:lines = []for v in videos:pos = v.get("position")tags = v.get("tags", "")lines.append(f"{pos}. {tags}")return "\n".join(lines)def _select_best_position(script: str, videos: list) -> int:"""Ask the model for just the best candidate's position number. Fast: ~2 output tokens."""if not videos:return Nonecandidates_block = _format_candidates(videos)prompt = (f'{SELECT_FEW_SHOT}\nScript: "{script}"\nCandidates:\n{candidates_block}\nBest:')messages = [{"role": "user", "content": prompt}]out = pipe(messages, max_new_tokens=4, do_sample=False)result = out[0]["generated_text"][-1]["content"].strip()match = re.search(r"\d+", result)if not match:return videos[0].get("position") # fallback: first candidatechosen = int(match.group())valid_positions = {v.get("position") for v in videos}if chosen not in valid_positions:return videos[0].get("position") # fallback if model hallucinated a bad numberreturn chosendef _select_best_videos(scenes_data: dict) -> list:2 unmodified lines{"scenes": [{"scene": 1, "script": "...", "videos": [{"position": 1, "id": 847, "tags": "...", "pageURL": "...","videoURL": "...", "thumbnailURL": "..."}, ...]}]}Returns a list of per-scene results with the chosen video's full info."""results = []for sc in scenes_data.get("scenes", []):10 unmodified lines})continuebest_pos = _select_best_position(script, videos)chosen = next((v for v in videos if v.get("position") == best_pos), videos[0])results.append({"scene": scene_num,6 unmodified lines"pageURL": chosen.get("pageURL"),"videoURL": chosen.get("videoURL"),"thumbnailURL": chosen.get("thumbnailURL"),},})return results14 unmodified linesresults = _select_best_videos(data)lines = ["| Scene | Script | Best Video ID | Tags | Link |","|---|---|---|---|---|"]for r in results:if r["status"] == "no_candidates":lines.append(f"| {r['scene']} | {r['script']} | β | *no candidates* | β |")else:v = r["video"]lines.append(f"| {r['scene']} | {r['script']} | {v['id']} | {v['tags']} | {v['pageURL']} |")return "\n".join(lines)except Exception as e:10 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef api_health() -> dict:"""Health check. Returns service status."""return {"status": "ok", "model": MODEL_ID, "device": "cpu"}def api_status() -> dict:"""Check server capacity β how many extraction "channels"/slots areavailable right now.Returns:10 unmodified linesdef api_select_best_videos(scenes_json: str) -> dict:"""Given a scenes JSON (script + candidate videos with tags per scene, e.g.your Pixabay search results), have the model pick the single best-matchingvideo per scene. Fast: the model only outputs a candidate number (1-10),not any descriptive text, so this is cheap enough to run scene-by-scene.Expected input shape:{"scenes": [{"scene": 1, "script": "...", "videos": [8 unmodified linesReturns:{"status": "ok", "results": [{"scene": 1, "script": "...", "status": "ok","video": {"position":1,"id":847,"tags":"...","pageURL":"...","videoURL":"...","thumbnailURL":"..."}}], "took_seconds": 0.42}or {"status": "busy"/"error", "error": "..."}"""snapshot = _get_capacity_snapshot()2 unmodified lines"status": "busy","error": (f"Server busy: all {snapshot['max_concurrent_jobs']} "f"extraction slots are in use. Please try again shortly."),}20 unmodified lines_job_finished()with gr.Blocks(title="Gemma 3 270M β Best Video Selector") as demo:gr.Markdown(f"""# π― Fast Best-Video SelectorPaste your scenes JSON (script + Pixabay candidate videos with tags perscene). The model picks the best-matching candidate per scene byoutputting only a position number β no descriptive text β so it runsfast even across many scenes.Handles up to **{MAX_CONCURRENT_JOBS} simultaneous requests**.**API users:** call via `gradio_client.Client("your-username/your-space")`,1234567891011121314151630 unmodified lines47484950515253545556575859606162636465666768697071722 unmodified lines757677787980818210 unmodified lines939495969798996 unmodified lines10610710810911011111214 unmodified lines12712812913013113213313413513613713813914014110 unmodified lines15215315415515615715815916016116216310 unmodified lines1741751761771781791801811821838 unmodified lines1921931941951961971982 unmodified lines20120220320420520620720 unmodified lines228229230231232233234235236237238239240# app.pyimport osimport jsonimport timeimport threadingimport gradio as grfrom sentence_transformers import SentenceTransformer, utilEMBED_MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"MAX_CONCURRENT_JOBS = 7print("Loading embedding model...")embedder = SentenceTransformer(EMBED_MODEL_ID)print("β Ready")# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ30 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Best-video selection via embedding similarity## Instead of asking an LLM to pick a position number (which showed a strong# bias toward always picking position 1, regardless of actual relevance),# we embed the script line and every candidate's tag string, then pick the# candidate with the highest cosine similarity. No generation involved, so# there's no position bias and it's faster than even a 2-token LLM call β# just one forward pass per script+candidate pair, batched.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _select_best_position(script: str, videos: list) -> int:if not videos:return Nonetag_strings = [v.get("tags", "") for v in videos]script_emb = embedder.encode(script, convert_to_tensor=True)tag_embs = embedder.encode(tag_strings, convert_to_tensor=True)sims = util.cos_sim(script_emb, tag_embs)[0] # shape: (num_candidates,)best_idx = int(sims.argmax())return videos[best_idx].get("position"), float(sims[best_idx])def _select_best_videos(scenes_data: dict) -> list:2 unmodified lines{"scenes": [{"scene": 1, "script": "...", "videos": [{"position": 1, "id": 847, "tags": "...", "pageURL": "...","videoURL": "...", "thumbnailURL": "..."}, ...]}]}Returns a list of per-scene results with the chosen video's full infoplus the similarity score that drove the choice."""results = []for sc in scenes_data.get("scenes", []):10 unmodified lines})continuebest_pos, score = _select_best_position(script, videos)chosen = next((v for v in videos if v.get("position") == best_pos), videos[0])results.append({"scene": scene_num,6 unmodified lines"pageURL": chosen.get("pageURL"),"videoURL": chosen.get("videoURL"),"thumbnailURL": chosen.get("thumbnailURL"),"similarity": round(score, 4),},})return results14 unmodified linesresults = _select_best_videos(data)lines = ["| Scene | Script | Best Video ID | Similarity | Tags | Link |","|---|---|---|---|---|---|"]for r in results:if r["status"] == "no_candidates":lines.append(f"| {r['scene']} | {r['script']} | β | β | *no candidates* | β |")else:v = r["video"]lines.append(f"| {r['scene']} | {r['script']} | {v['id']} | {v['similarity']} | {v['tags']} | {v['pageURL']} |")return "\n".join(lines)except Exception as e:10 unmodified lines# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef api_health() -> dict:"""Health check. Returns service status."""return {"status": "ok", "model": EMBED_MODEL_ID, "device": "cpu"}def api_status() -> dict:"""Check server capacity β how many selection "channels"/slots areavailable right now.Returns:10 unmodified linesdef api_select_best_videos(scenes_json: str) -> dict:"""Given a scenes JSON (script + candidate videos with tags per scene, e.g.your Pixabay search results), pick the single best-matching video perscene using embedding cosine similarity between the script line and eachcandidate's tags. No LLM generation involved, so there's no positionbias and it runs fast even across many scenes/candidates.Expected input shape:{"scenes": [{"scene": 1, "script": "...", "videos": [8 unmodified linesReturns:{"status": "ok", "results": [{"scene": 1, "script": "...", "status": "ok","video": {"position":1,"id":847,"tags":"...","pageURL":"...","videoURL":"...","thumbnailURL":"...","similarity":0.63}}], "took_seconds": 0.12}or {"status": "busy"/"error", "error": "..."}"""snapshot = _get_capacity_snapshot()2 unmodified lines"status": "busy","error": (f"Server busy: all {snapshot['max_concurrent_jobs']} "f"selection slots are in use. Please try again shortly."),}20 unmodified lines_job_finished()with gr.Blocks(title="Best Video Selector β Embedding Similarity") as demo:gr.Markdown(f"""# π― Best-Video Selector (Embedding Similarity)Paste your scenes JSON (script + Pixabay candidate videos with tags perscene). Each candidate is ranked by cosine similarity between the scriptline and its tags β no LLM generation, so there's no position bias andit's fast even across many scenes.Handles up to **{MAX_CONCURRENT_JOBS} simultaneous requests**.**API users:** call via `gradio_client.Client("your-username/your-space")`,
app.py+40-79