wchen22 commited on
Commit
bdbc6a5
·
verified ·
1 Parent(s): bf9948e

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +73 -5
app.py CHANGED
@@ -6,16 +6,19 @@ import math
6
  import os
7
  import re
8
  import time
 
9
  from functools import lru_cache
10
  from pathlib import Path
11
  from typing import Any
12
 
13
- from fastapi import FastAPI, HTTPException
14
 
15
  CLASSIFIER_MODEL = "microsoft/deberta-v3-small"
16
  CLASSIFIER_ARTIFACT_DIR = os.environ.get("TOUCHDOWN_CLASSIFIER_ARTIFACT_DIR")
17
  API_SCHEMA_VERSION = "0.1.0"
18
  RULES_VERSION = "hf-space-rules-v0.1.0"
 
 
19
  LOW_SIGNAL_PATTERNS = [
20
  re.compile(pattern, re.IGNORECASE)
21
  for pattern in [
@@ -31,6 +34,15 @@ LOW_SIGNAL_PATTERNS = [
31
  app = FastAPI(title="Touchdown Compression Classifier", version="0.1.0")
32
 
33
 
 
 
 
 
 
 
 
 
 
34
  @lru_cache(maxsize=1)
35
  def _get_tokenizer():
36
  from transformers import AutoTokenizer
@@ -309,6 +321,20 @@ def _receipt_id(payload: dict[str, Any]) -> str:
309
  return "tdcr_" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:24]
310
 
311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
  def _tool_schema_variants(schema: Any) -> list[str]:
313
  if isinstance(schema, str):
314
  return [schema] if schema else []
@@ -349,7 +375,9 @@ def _tool_schema_missing_groups(
349
  ) -> list[list[str]]:
350
  missing = []
351
  for group in groups:
352
- if _schema_occurrences(input_text, group) > 0 and _schema_occurrences(output, group) == 0:
 
 
353
  missing.append(group)
354
  return missing
355
 
@@ -394,7 +422,13 @@ def _protected_spans(
394
  spans.extend(code_spans)
395
  spans.extend(json_spans)
396
  spans.extend(system_spans)
397
- return _merge(spans), code_spans, json_spans, system_spans, _merge(tool_schema_spans)
 
 
 
 
 
 
398
 
399
 
400
  def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
@@ -404,6 +438,12 @@ def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
404
  settings = payload.get("compression_settings") or {}
405
  if not isinstance(settings, dict):
406
  raise HTTPException(status_code=400, detail="compression_settings must be an object")
 
 
 
 
 
 
407
  protected_values = payload.get("protected_spans") or []
408
  if not isinstance(protected_values, list) or not all(
409
  isinstance(value, str) for value in protected_values
@@ -505,6 +545,9 @@ def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
505
  ]
506
  classifier_blocked = sum(classifier_blocked_by_reason.values())
507
  receipt = {
 
 
 
508
  "protected_spans_checked": len(protected_values),
509
  "protected_spans_missing": len(missing),
510
  "code_blocks_detected": len(code_spans),
@@ -577,6 +620,8 @@ def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
577
  "output_tokens": after,
578
  "tokens_saved": saved,
579
  "compression_percentage": round(100.0 * saved / before, 1),
 
 
580
  "receipt": receipt,
581
  }
582
 
@@ -592,6 +637,8 @@ def _merge_batch_item_payload(
592
  "compression_settings": payload.get("compression_settings"),
593
  "protected_spans": payload.get("protected_spans"),
594
  "tool_schemas": payload.get("tool_schemas", payload.get("tools")),
 
 
595
  }
596
  if not isinstance(item, dict):
597
  raise ValueError(f"inputs[{index}] must be a string or an object")
@@ -621,6 +668,11 @@ def _merge_batch_item_payload(
621
  "tool_schemas",
622
  item.get("tools", payload.get("tool_schemas", payload.get("tools"))),
623
  ),
 
 
 
 
 
624
  }
625
 
626
 
@@ -632,6 +684,12 @@ def _handle_batch(payload: dict[str, Any]) -> dict[str, Any]:
632
  raise HTTPException(status_code=400, detail="inputs must be a list")
633
  if not inputs:
634
  raise HTTPException(status_code=400, detail="inputs list is empty")
 
 
 
 
 
 
635
 
636
  results: list[dict[str, Any]] = []
637
  totals = {
@@ -678,7 +736,7 @@ def _handle_batch(payload: dict[str, Any]) -> dict[str, Any]:
678
  for result in results
679
  if result.get("status") == "ok" and result.get("receipt", {}).get("receipt_id")
680
  ]
681
- return {
682
  "schema_version": API_SCHEMA_VERSION,
683
  "status": "ok" if failed == 0 else "partial_error",
684
  "endpoint": "/v1/compress",
@@ -691,6 +749,11 @@ def _handle_batch(payload: dict[str, Any]) -> dict[str, Any]:
691
  "receipt_ids": receipt_ids,
692
  "results": results,
693
  }
 
 
 
 
 
694
 
695
 
696
  def _tokens(text: str) -> list[dict[str, Any]]:
@@ -765,7 +828,12 @@ def classify(payload: dict[str, Any]) -> dict[str, Any]:
765
 
766
 
767
  @app.post("/v1/compress")
768
- def compress(payload: dict[str, Any]) -> dict[str, Any]:
 
 
 
 
 
769
  if "inputs" in payload:
770
  return _handle_batch(payload)
771
  return _compress_text(payload)
 
6
  import os
7
  import re
8
  import time
9
+ import uuid
10
  from functools import lru_cache
11
  from pathlib import Path
12
  from typing import Any
13
 
14
+ from fastapi import FastAPI, HTTPException, Request
15
 
16
  CLASSIFIER_MODEL = "microsoft/deberta-v3-small"
17
  CLASSIFIER_ARTIFACT_DIR = os.environ.get("TOUCHDOWN_CLASSIFIER_ARTIFACT_DIR")
18
  API_SCHEMA_VERSION = "0.1.0"
19
  RULES_VERSION = "hf-space-rules-v0.1.0"
20
+ REQUEST_ID_HEADER = "X-Request-ID"
21
+ IDEMPOTENCY_KEY_HEADER = "Idempotency-Key"
22
  LOW_SIGNAL_PATTERNS = [
23
  re.compile(pattern, re.IGNORECASE)
24
  for pattern in [
 
34
  app = FastAPI(title="Touchdown Compression Classifier", version="0.1.0")
35
 
36
 
37
+ @app.middleware("http")
38
+ async def request_id_middleware(request: Request, call_next):
39
+ request_id = request.headers.get(REQUEST_ID_HEADER) or f"tdreq_{uuid.uuid4().hex}"
40
+ request.state.request_id = request_id
41
+ response = await call_next(request)
42
+ response.headers[REQUEST_ID_HEADER] = request_id
43
+ return response
44
+
45
+
46
  @lru_cache(maxsize=1)
47
  def _get_tokenizer():
48
  from transformers import AutoTokenizer
 
321
  return "tdcr_" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:24]
322
 
323
 
324
+ def _correlation_payload(
325
+ payload: dict[str, Any],
326
+ *,
327
+ request_id: str | None = None,
328
+ idempotency_key: str | None = None,
329
+ ) -> dict[str, Any]:
330
+ out = dict(payload)
331
+ if request_id and "request_id" not in out:
332
+ out["request_id"] = request_id
333
+ if idempotency_key and "idempotency_key" not in out:
334
+ out["idempotency_key"] = idempotency_key
335
+ return out
336
+
337
+
338
  def _tool_schema_variants(schema: Any) -> list[str]:
339
  if isinstance(schema, str):
340
  return [schema] if schema else []
 
375
  ) -> list[list[str]]:
376
  missing = []
377
  for group in groups:
378
+ input_occurrences = _schema_occurrences(input_text, group)
379
+ output_occurrences = _schema_occurrences(output, group)
380
+ if input_occurrences > 0 and output_occurrences == 0:
381
  missing.append(group)
382
  return missing
383
 
 
422
  spans.extend(code_spans)
423
  spans.extend(json_spans)
424
  spans.extend(system_spans)
425
+ return (
426
+ _merge(spans),
427
+ code_spans,
428
+ json_spans,
429
+ system_spans,
430
+ _merge(tool_schema_spans),
431
+ )
432
 
433
 
434
  def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
 
438
  settings = payload.get("compression_settings") or {}
439
  if not isinstance(settings, dict):
440
  raise HTTPException(status_code=400, detail="compression_settings must be an object")
441
+ request_id = payload.get("request_id")
442
+ if request_id is not None and not isinstance(request_id, str):
443
+ raise HTTPException(status_code=400, detail="request_id must be a string")
444
+ idempotency_key = payload.get("idempotency_key")
445
+ if idempotency_key is not None and not isinstance(idempotency_key, str):
446
+ raise HTTPException(status_code=400, detail="idempotency_key must be a string")
447
  protected_values = payload.get("protected_spans") or []
448
  if not isinstance(protected_values, list) or not all(
449
  isinstance(value, str) for value in protected_values
 
545
  ]
546
  classifier_blocked = sum(classifier_blocked_by_reason.values())
547
  receipt = {
548
+ "request_id": request_id,
549
+ "idempotency_key": idempotency_key,
550
+ "idempotency_mode": "correlation_only_no_response_replay",
551
  "protected_spans_checked": len(protected_values),
552
  "protected_spans_missing": len(missing),
553
  "code_blocks_detected": len(code_spans),
 
620
  "output_tokens": after,
621
  "tokens_saved": saved,
622
  "compression_percentage": round(100.0 * saved / before, 1),
623
+ "request_id": request_id,
624
+ "idempotency_key": idempotency_key,
625
  "receipt": receipt,
626
  }
627
 
 
637
  "compression_settings": payload.get("compression_settings"),
638
  "protected_spans": payload.get("protected_spans"),
639
  "tool_schemas": payload.get("tool_schemas", payload.get("tools")),
640
+ "request_id": payload.get("request_id"),
641
+ "idempotency_key": payload.get("idempotency_key"),
642
  }
643
  if not isinstance(item, dict):
644
  raise ValueError(f"inputs[{index}] must be a string or an object")
 
668
  "tool_schemas",
669
  item.get("tools", payload.get("tool_schemas", payload.get("tools"))),
670
  ),
671
+ "request_id": item.get("request_id", payload.get("request_id")),
672
+ "idempotency_key": item.get(
673
+ "idempotency_key",
674
+ payload.get("idempotency_key"),
675
+ ),
676
  }
677
 
678
 
 
684
  raise HTTPException(status_code=400, detail="inputs must be a list")
685
  if not inputs:
686
  raise HTTPException(status_code=400, detail="inputs list is empty")
687
+ request_id = payload.get("request_id")
688
+ if request_id is not None and not isinstance(request_id, str):
689
+ raise HTTPException(status_code=400, detail="request_id must be a string")
690
+ idempotency_key = payload.get("idempotency_key")
691
+ if idempotency_key is not None and not isinstance(idempotency_key, str):
692
+ raise HTTPException(status_code=400, detail="idempotency_key must be a string")
693
 
694
  results: list[dict[str, Any]] = []
695
  totals = {
 
736
  for result in results
737
  if result.get("status") == "ok" and result.get("receipt", {}).get("receipt_id")
738
  ]
739
+ body = {
740
  "schema_version": API_SCHEMA_VERSION,
741
  "status": "ok" if failed == 0 else "partial_error",
742
  "endpoint": "/v1/compress",
 
749
  "receipt_ids": receipt_ids,
750
  "results": results,
751
  }
752
+ if request_id is not None:
753
+ body["request_id"] = request_id
754
+ if idempotency_key is not None:
755
+ body["idempotency_key"] = idempotency_key
756
+ return body
757
 
758
 
759
  def _tokens(text: str) -> list[dict[str, Any]]:
 
828
 
829
 
830
  @app.post("/v1/compress")
831
+ def compress(payload: dict[str, Any], request: Request) -> dict[str, Any]:
832
+ payload = _correlation_payload(
833
+ payload,
834
+ request_id=getattr(request.state, "request_id", None),
835
+ idempotency_key=request.headers.get(IDEMPOTENCY_KEY_HEADER),
836
+ )
837
  if "inputs" in payload:
838
  return _handle_batch(payload)
839
  return _compress_text(payload)