j-js commited on
Commit
8a8fb5a
·
verified ·
1 Parent(s): 664a146

Create Utils.py

Browse files
Files changed (1) hide show
  1. Utils.py +84 -0
Utils.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import json
5
+ import re
6
+ from typing import Any
7
+
8
+ from models import ChatRequest
9
+
10
+
11
+ def clamp01(x: Any, default: float = 0.5) -> float:
12
+ try:
13
+ v = float(x)
14
+ return max(0.0, min(1.0, v))
15
+ except Exception:
16
+ return default
17
+
18
+
19
+ def normalize_spaces(text: str) -> str:
20
+ return re.sub(r"\s+", " ", text).strip()
21
+
22
+
23
+ def clean_math_text(text: str) -> str:
24
+ t = text
25
+ t = t.replace("×", "*").replace("÷", "/").replace("–", "-").replace("—", "-")
26
+ t = t.replace("−", "-").replace("^", "**")
27
+ return t
28
+
29
+
30
+ def extract_text_from_any_payload(payload: Any) -> str:
31
+ if payload is None:
32
+ return ""
33
+
34
+ if isinstance(payload, str):
35
+ s = payload.strip()
36
+
37
+ if (s.startswith("{") and s.endswith("}")) or (s.startswith("[") and s.endswith("]")):
38
+ try:
39
+ decoded = json.loads(s)
40
+ return extract_text_from_any_payload(decoded)
41
+ except Exception:
42
+ pass
43
+
44
+ try:
45
+ decoded = ast.literal_eval(s)
46
+ if isinstance(decoded, (dict, list)):
47
+ return extract_text_from_any_payload(decoded)
48
+ except Exception:
49
+ pass
50
+
51
+ return s
52
+
53
+ if isinstance(payload, dict):
54
+ for key in [
55
+ "message", "prompt", "query", "text", "user_message",
56
+ "input", "data", "payload", "body", "content"
57
+ ]:
58
+ if key in payload:
59
+ extracted = extract_text_from_any_payload(payload[key])
60
+ if extracted:
61
+ return extracted
62
+
63
+ strings = []
64
+ for v in payload.values():
65
+ if isinstance(v, (str, dict, list)):
66
+ maybe = extract_text_from_any_payload(v)
67
+ if maybe:
68
+ strings.append(maybe)
69
+ return "\n".join(strings).strip()
70
+
71
+ if isinstance(payload, list):
72
+ parts = [extract_text_from_any_payload(x) for x in payload]
73
+ return "\n".join([p for p in parts if p]).strip()
74
+
75
+ return str(payload).strip()
76
+
77
+
78
+ def get_user_text(req: ChatRequest, raw_body: Any = None) -> str:
79
+ for field in ["message", "prompt", "query", "text", "user_message"]:
80
+ value = getattr(req, field, None)
81
+ if isinstance(value, str) and value.strip():
82
+ return value.strip()
83
+
84
+ return extract_text_from_any_payload(raw_body).strip()