Spaces:
Paused

Consulawtech Claude Opus 5.5 (1M context) commited on
Commit
1325c64
Β·
1 Parent(s): 2c36551

Cut serving costs: Claude returns only corrected lines; short idle windows with keep-alive

Browse files

- Clean-up prompt now returns only changed/hallucinated segments (unchanged
ones keep their text). Measured on the council meeting: output tokens
298 -> 38 per audio minute, cost per minute -69%.
- While any job runs the server pings its own public URL every 4 min, so
hosts that sleep on no traffic don't stop a job when clients stop polling.
That allows short idle windows: HF Space sleep 1 h -> 10 min, Modal
scaledown 60 min -> 15 min (idle GPU was the largest serving cost).
- Log Claude token usage per clean-up batch.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Files changed (1) hide show
  1. app.py +61 -5
app.py CHANGED
@@ -520,14 +520,19 @@ def _enhance_segments_with_claude(segments: list, language: str) -> list:
520
  "ha": "Hausa-English code-switching",
521
  }.get(language, language or "en")
522
 
 
 
 
523
  system = (
524
- "You are a transcription corrector. Given numbered segments, return them "
525
- "in the same numbered format with ASR errors fixed. "
526
- "Replace the text with HALLUCINATED (exactly) for any segment that was not "
527
- "actually spoken β€” common Whisper hallucinations: 'Thank you for watching', "
528
  "'See you in the next video', 'Don't forget to subscribe', etc. "
529
  "Never translate. Never add new sentences. Preserve code-switching exactly. "
530
- "Return ALL segment numbers, one per line, format: [N] corrected text"
 
 
531
  )
532
 
533
  def _process(batch: list) -> list:
@@ -553,6 +558,11 @@ def _enhance_segments_with_claude(segments: list, language: str) -> list:
553
  ),
554
  }],
555
  )
 
 
 
 
 
556
  response_text = msg.content[0].text.strip()
557
 
558
  result_map: dict[int, str] = {}
@@ -1087,6 +1097,50 @@ else:
1087
  # runs inside this lock, so concurrent uploads queue instead of colliding.
1088
  _ENGINE_LOCK = threading.Lock()
1089
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1090
 
1091
  def _default_model_key() -> str:
1092
  return engine.config.get("models", {}).get("default") or engine.current_model_key
@@ -1154,6 +1208,7 @@ def _run_transcription_sync(
1154
  **kwargs,
1155
  ):
1156
  """Sync worker running in ThreadPoolExecutor β€” returns immediately so 202 is sent."""
 
1157
  try:
1158
  with _ENGINE_LOCK:
1159
  target_model = model_key or _default_model_key()
@@ -1253,6 +1308,7 @@ def _run_transcription_sync(
1253
  logger.error(f"Background transcription job {jid} failed: {e}")
1254
  _upsert_job(jid, status="error", detail=str(e))
1255
  finally:
 
1256
  _job_progress_cache.pop(jid, None)
1257
 
1258
 
 
520
  "ha": "Hausa-English code-switching",
521
  }.get(language, language or "en")
522
 
523
+ # Only changed segments come back: echoing every unchanged line made
524
+ # output tokens (5x the price of input on Haiku) the largest per-minute
525
+ # cost of a transcription. Segments left out keep their original text.
526
  system = (
527
+ "You are a transcription corrector. Given numbered segments, fix ASR "
528
+ "errors (misheard words, wrong names, broken punctuation). "
529
+ "Mark a segment HALLUCINATED (exactly) if it was not actually spoken β€” "
530
+ "common Whisper hallucinations: 'Thank you for watching', "
531
  "'See you in the next video', 'Don't forget to subscribe', etc. "
532
  "Never translate. Never add new sentences. Preserve code-switching exactly. "
533
+ "Output ONLY the segments you changed or marked, one per line, format: "
534
+ "[N] corrected text (or [N] HALLUCINATED). If nothing needs changing, "
535
+ "output exactly: NONE"
536
  )
537
 
538
  def _process(batch: list) -> list:
 
558
  ),
559
  }],
560
  )
561
+ try:
562
+ logger.info(f"Claude cleanup batch: {len(batch)} segments, "
563
+ f"in={msg.usage.input_tokens} out={msg.usage.output_tokens}")
564
+ except Exception:
565
+ pass
566
  response_text = msg.content[0].text.strip()
567
 
568
  result_map: dict[int, str] = {}
 
1097
  # runs inside this lock, so concurrent uploads queue instead of colliding.
1098
  _ENGINE_LOCK = threading.Lock()
1099
 
1100
+ # ── Keep-alive while jobs run ─────────────────────────────────────────────────
1101
+ # Both hosts sleep/scale down after a period with no *incoming requests*,
1102
+ # regardless of work in progress. That used to force long idle windows
1103
+ # (HF 1 h, Modal 1 h) so a job didn't die when the phone stopped polling,
1104
+ # and the idle GPU became the biggest serving cost. Instead, while any job
1105
+ # is running the server requests its own public URL every few minutes,
1106
+ # which counts as traffic on both hosts, so the idle window can be short.
1107
+ _ACTIVE_JOBS = 0
1108
+ _ACTIVE_LOCK = threading.Lock()
1109
+
1110
+
1111
+ def _self_url() -> str:
1112
+ explicit = os.getenv("SELF_URL", "").rstrip("/")
1113
+ if explicit:
1114
+ return explicit
1115
+ host = os.getenv("SPACE_HOST", "") # set by Hugging Face Spaces
1116
+ return f"https://{host}" if host else ""
1117
+
1118
+
1119
+ def _keepalive_loop() -> None:
1120
+ while True:
1121
+ time.sleep(240)
1122
+ url = _self_url()
1123
+ if _ACTIVE_JOBS > 0 and url and _requests_available:
1124
+ try:
1125
+ _requests.get(f"{url}/health", timeout=15)
1126
+ except Exception as e:
1127
+ logger.warning(f"Keep-alive ping failed: {e}")
1128
+
1129
+
1130
+ threading.Thread(target=_keepalive_loop, name="keepalive", daemon=True).start()
1131
+
1132
+
1133
+ def _job_started() -> None:
1134
+ global _ACTIVE_JOBS
1135
+ with _ACTIVE_LOCK:
1136
+ _ACTIVE_JOBS += 1
1137
+
1138
+
1139
+ def _job_finished() -> None:
1140
+ global _ACTIVE_JOBS
1141
+ with _ACTIVE_LOCK:
1142
+ _ACTIVE_JOBS = max(0, _ACTIVE_JOBS - 1)
1143
+
1144
 
1145
  def _default_model_key() -> str:
1146
  return engine.config.get("models", {}).get("default") or engine.current_model_key
 
1208
  **kwargs,
1209
  ):
1210
  """Sync worker running in ThreadPoolExecutor β€” returns immediately so 202 is sent."""
1211
+ _job_started()
1212
  try:
1213
  with _ENGINE_LOCK:
1214
  target_model = model_key or _default_model_key()
 
1308
  logger.error(f"Background transcription job {jid} failed: {e}")
1309
  _upsert_job(jid, status="error", detail=str(e))
1310
  finally:
1311
+ _job_finished()
1312
  _job_progress_cache.pop(jid, None)
1313
 
1314