Update app.py
Browse files14 unmodified lines15161718192038 unmodified lines59606162636438 unmodified lines1031041051061071081091 unmodified line1111121131141151161171181195 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516640 unmodified lines2072082092102112122131 unmodified line2152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462 unmodified lines24925025125225325425525625725812 unmodified lines27127227327427527627711 unmodified lines28929029129229329429529629729829914 unmodified linesEMBED_MODEL_ID = "intfloat/e5-small-v2"MAX_CONCURRENT_JOBS = 7# Below this cosine similarity, treat the pick as unreliable rather than# silently returning a low-confidence guess. e5 cosine scores for genuinely# relevant pairs typically sit higher than raw MiniLM scores did, but this38 unmodified lines}# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Best-video selection via embedding similarity#38 unmodified linesreturn videos[best_idx].get("position"), float(sims[best_idx])def _select_best_videos(scenes_data: dict) -> list:"""scenes_data: parsed JSON in the format:{"scenes": [{"scene": 1, "script": "...", "videos": [1 unmodified line"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", []):scene_num = sc.get("scene")script = sc.get("script", "")videos = sc.get("videos", [])5 unmodified lines"status": "no_candidates","video": None,})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,"script": script,"status": "ok","low_confidence": score < LOW_CONFIDENCE_THRESHOLD,"video": {"position": chosen.get("position"),"id": chosen.get("id"),"tags": chosen.get("tags"),"pageURL": chosen.get("pageURL"),"videoURL": chosen.get("videoURL"),"thumbnailURL": chosen.get("thumbnailURL"),"similarity": round(score, 4),},})return results# ββββββββββββββββββββββββββββββββββββοΏ½οΏ½βββββββββββββββββββββββββββββββββββββ# Gradio UI function# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef gradio_select_best(json_text):if not json_text or not json_text.strip():return "β Please paste the scenes JSON"_job_started()try:try:data = json.loads(json_text)except json.JSONDecodeError as e:return f"β Invalid JSON: {e}"results = _select_best_videos(data)lines = ["| Scene | Script | Best Video ID | Similarity | Tags | Link |","|---|---|---|---|---|---|"]40 unmodified linesreturn _get_capacity_snapshot()def 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 per1 unmodified linecandidate'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": [{"position": 1, "id": 847, "tags": "...", "pageURL": "...","videoURL": "...", "thumbnailURL": "..."}, ...]}]}Python client example:from gradio_client import Clientclient = Client("your-username/your-space")result = client.predict(scenes_json=json.dumps(data), api_name="/api_select_best_videos")Returns:{"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()if snapshot["available_slots"] <= 0:return {"status": "busy","error": (f"Server busy: all {snapshot['max_concurrent_jobs']} "f"selection slots are in use. Please try again shortly."),}if not scenes_json or not scenes_json.strip():return {"status": "error", "error": "Empty scenes JSON provided"}2 unmodified linesexcept json.JSONDecodeError as e:return {"status": "error", "error": f"Invalid JSON: {e}"}_job_started()try:start_time = time.time()results = _select_best_videos(data)return {"status": "ok","results": results,12 unmodified linesscene). 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")`,then `client.predict(scenes_json="...", api_name="/api_select_best_videos")`.11 unmodified lineswith gr.Column():out = gr.Textbox(label="Result (markdown table)", lines=20)btn.click(fn=gradio_select_best, inputs=inp, outputs=out, concurrency_limit=MAX_CONCURRENT_JOBS)gr.api(api_health, api_name="api_health")gr.api(api_status, api_name="api_status")gr.api(api_select_best_videos, api_name="api_select_best_videos", concurrency_limit=MAX_CONCURRENT_JOBS)if __name__ == "__main__":14 unmodified lines1516171819202122232425262738 unmodified lines6667686970717273747576777879808182838485868788899091929338 unmodified lines1321331341351361371381 unmodified line1401411421431441451461471481491501511521531541555 unmodified lines16116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022140 unmodified lines2622632642652662672681 unmodified line2702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033042 unmodified lines30730830931031131231331431531631731831932032132232332432532632732832933033133233333433512 unmodified lines34834935035135235335435535611 unmodified lines36836937037137237337437537637737837938038138238338438538638714 unmodified linesEMBED_MODEL_ID = "intfloat/e5-small-v2"MAX_CONCURRENT_JOBS = 7# Gradio-level concurrency cap. This is kept well above MAX_CONCURRENT_JOBS# so requests are handed to our function immediately instead of sitting in# Gradio's own internal queue β capacity is enforced by our own counter# (_active_jobs) below, which lets us return "server busy" the instant a# request arrives rather than after it's been queued for a while.GRADIO_CONCURRENCY_LIMIT = max(MAX_CONCURRENT_JOBS * 4, 20)# Below this cosine similarity, treat the pick as unreliable rather than# silently returning a low-confidence guess. e5 cosine scores for genuinely# relevant pairs typically sit higher than raw MiniLM scores did, but this38 unmodified lines}def _reserve_slot_or_busy():"""Atomically checks capacity and reserves a slot in one step (so tworequests can't both see a free slot and both get admitted). ReturnsNone if a slot was reserved (caller MUST call _job_finished() whendone, ideally in a finally block), or a capacity snapshot dict if theserver is full and the caller should bail out immediately."""global _active_jobs, _total_jobs_servedwith _active_jobs_lock:if _active_jobs >= MAX_CONCURRENT_JOBS:return {"max_concurrent_jobs": MAX_CONCURRENT_JOBS,"active_jobs": _active_jobs,"available_slots": 0,"total_jobs_served_since_startup": _total_jobs_served,}_active_jobs += 1_total_jobs_served += 1return None# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Best-video selection via embedding similarity#38 unmodified linesreturn videos[best_idx].get("position"), float(sims[best_idx])def _select_best_videos(scenes_data: dict, progress_cb=None) -> list:"""scenes_data: parsed JSON in the format:{"scenes": [{"scene": 1, "script": "...", "videos": [1 unmodified line"videoURL": "...", "thumbnailURL": "..."}, ...]}]}Returns a list of per-scene results with the chosen video's full infoplus the similarity score that drove the choice.progress_cb, if given, is called after every scene asprogress_cb(done, total) so callers (e.g. the Gradio UI) can render areal-time percentage-complete progress bar."""results = []scenes = scenes_data.get("scenes", [])total = len(scenes)for i, sc in enumerate(scenes):scene_num = sc.get("scene")script = sc.get("script", "")videos = sc.get("videos", [])5 unmodified lines"status": "no_candidates","video": None,})else:best_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,"script": script,"status": "ok","low_confidence": score < LOW_CONFIDENCE_THRESHOLD,"video": {"position": chosen.get("position"),"id": chosen.get("id"),"tags": chosen.get("tags"),"pageURL": chosen.get("pageURL"),"videoURL": chosen.get("videoURL"),"thumbnailURL": chosen.get("thumbnailURL"),"similarity": round(score, 4),},})if progress_cb is not None:progress_cb(i + 1, total)return results# ββββββββββββββββββββββββββββββββββββοΏ½οΏ½βββββββββββββββββββββββββββββββββββββ# Gradio UI function# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef gradio_select_best(json_text, progress=gr.Progress()):if not json_text or not json_text.strip():return "β Please paste the scenes JSON"# Reserve a slot up front. If the server is already at capacity this# returns immediately with a busy message β no queueing, no model call.busy_snapshot = _reserve_slot_or_busy()if busy_snapshot is not None:return (f"π« Server busy β all {busy_snapshot['max_concurrent_jobs']} "f"selection slots are in use. Please try again shortly.")try:try:data = json.loads(json_text)except json.JSONDecodeError as e:return f"β Invalid JSON: {e}"scenes_total = len(data.get("scenes", []))progress(0, desc=f"0/{scenes_total} scenes (0%)")def _on_progress(done, total):pct = int(done / total * 100) if total else 100progress(done / total if total else 1.0, desc=f"{done}/{total} scenes ({pct}%)")results = _select_best_videos(data, progress_cb=_on_progress)lines = ["| Scene | Script | Best Video ID | Similarity | Tags | Link |","|---|---|---|---|---|---|"]40 unmodified linesreturn _get_capacity_snapshot()def api_select_best_videos(scenes_json: str, progress=gr.Progress()) -> dict:"""Given a scenes JSON (script + candidate videos with tags per scene, e.g.your Pixabay search results), pick the single best-matching video per1 unmodified linecandidate's tags. No LLM generation involved, so there's no positionbias and it runs fast even across many scenes/candidates.If all MAX_CONCURRENT_JOBS slots are currently in use, this returns{"status": "busy", ...} immediately rather than queueing the request.Real-time progress: this endpoint reports scene-by-scene progressthrough Gradio's queue/job status (the same gr.Progress() mechanismthe UI uses). Poll it from gradio_client instead of just predict():from gradio_client import Clientclient = Client("your-username/your-space")job = client.submit(scenes_json=json.dumps(data), api_name="/api_select_best_videos")while not job.done():print(job.status().progress_data) # live % as scenes completetime.sleep(0.5)result = job.result()Plain client.predict(...) still works too β it just blocks until thefinal result, with no visibility into intermediate progress.Expected input shape:{"scenes": [{"scene": 1, "script": "...", "videos": [{"position": 1, "id": 847, "tags": "...", "pageURL": "...","videoURL": "...", "thumbnailURL": "..."}, ...]}]}Returns:{"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": "..."}"""if not scenes_json or not scenes_json.strip():return {"status": "error", "error": "Empty scenes JSON provided"}2 unmodified linesexcept json.JSONDecodeError as e:return {"status": "error", "error": f"Invalid JSON: {e}"}# Reserve a slot up front so a burst of simultaneous requests can't all# slip past the capacity check before any of them increments it.busy_snapshot = _reserve_slot_or_busy()if busy_snapshot is not None:return {"status": "busy","error": (f"Server busy: all {busy_snapshot['max_concurrent_jobs']} "f"selection slots are in use. Please try again shortly."),}try:start_time = time.time()scenes_total = len(data.get("scenes", []))progress(0, desc=f"0/{scenes_total} scenes (0%)")def _on_progress(done, total):pct = int(done / total * 100) if total else 100progress(done / total if total else 1.0, desc=f"{done}/{total} scenes ({pct}%)")results = _select_best_videos(data, progress_cb=_on_progress)return {"status": "ok","results": results,12 unmodified linesscene). 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**; once allslots are busy, new requests get an instant "server busy" reply insteadof waiting in a queue.**API users:** call via `gradio_client.Client("your-username/your-space")`,then `client.predict(scenes_json="...", api_name="/api_select_best_videos")`.11 unmodified lineswith gr.Column():out = gr.Textbox(label="Result (markdown table)", lines=20)btn.click(fn=gradio_select_best,inputs=inp,outputs=out,concurrency_limit=GRADIO_CONCURRENCY_LIMIT,)gr.api(api_health, api_name="api_health")gr.api(api_status, api_name="api_status")gr.api(api_select_best_videos,api_name="api_select_best_videos",concurrency_limit=GRADIO_CONCURRENCY_LIMIT,)if __name__ == "__main__":
app.py+132-44