Spaces:
Sleeping
Sleeping
Auto-form: AI backend via Power Automate + AI Builder (AI_BACKEND env, OpenRouter kept for rollback)
Browse files- ai_clean.py +94 -20
ai_clean.py
CHANGED
|
@@ -4,10 +4,16 @@ ai_clean — turn a TOR กำหนดส่งมอบ (การส่งม
|
|
| 4 |
and split it into selectable งวด.
|
| 5 |
|
| 6 |
- parse_nguad(clause) : deterministic; lists the งวด the user can pick (no AI, never fails).
|
| 7 |
-
- clean_delivery(...) : AI rewrite
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
import os
|
|
@@ -19,7 +25,23 @@ import urllib.error
|
|
| 19 |
|
| 20 |
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
"กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"]
|
| 24 |
|
| 25 |
|
|
@@ -116,6 +138,55 @@ def _call_openrouter(model, user_content, api_key, timeout=45):
|
|
| 116 |
return (data["choices"][0]["message"]["content"] or "").strip()
|
| 117 |
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
def _api_keys(explicit=None):
|
| 120 |
"""Ordered list of OpenRouter API keys → auto-rotate across multiple accounts when
|
| 121 |
one hits its limit. Sources, in order: an explicit arg, then OPENROUTER_API_KEY (which
|
|
@@ -133,15 +204,18 @@ def _api_keys(explicit=None):
|
|
| 133 |
return keys
|
| 134 |
|
| 135 |
|
| 136 |
-
def _complete(user_content, api_keys, accept, retries=2):
|
| 137 |
-
"""
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
| 145 |
for model in MODELS: # keep the SAME model as long as any account serves it
|
| 146 |
for key in api_keys: # rotate accounts on this model
|
| 147 |
for attempt in range(retries):
|
|
@@ -226,8 +300,7 @@ def generate_body(fields, api_key=None, retries=2):
|
|
| 226 |
Falls back to the identical-format deterministic compose_body() on missing key / failure /
|
| 227 |
if the model drifts off-format — so the output is always exactly on-format."""
|
| 228 |
det = compose_body(fields)
|
| 229 |
-
|
| 230 |
-
if not keys:
|
| 231 |
return det, False
|
| 232 |
|
| 233 |
verb = _verb(fields.get("procurement_type"))
|
|
@@ -244,7 +317,9 @@ def generate_body(fields, api_key=None, retries=2):
|
|
| 244 |
f"DURATION={duration}\nSTART={(fields.get('start_date') or '').strip()}"
|
| 245 |
)
|
| 246 |
# accept only if on-format (both anchor phrases present); else fall back to det
|
| 247 |
-
out = _complete(user,
|
|
|
|
|
|
|
| 248 |
return (out, True) if out else (det, False)
|
| 249 |
|
| 250 |
|
|
@@ -258,8 +333,7 @@ def clean_delivery(clause, selected_label=None, api_key=None, retries=2):
|
|
| 258 |
clause = (clause or "").strip()
|
| 259 |
if not clause:
|
| 260 |
return "", False
|
| 261 |
-
|
| 262 |
-
if not keys:
|
| 263 |
return _raw_fallback(clause, selected_label), False
|
| 264 |
|
| 265 |
if selected_label and selected_label.startswith("งวดที่"):
|
|
@@ -275,5 +349,5 @@ def clean_delivery(clause, selected_label=None, api_key=None, retries=2):
|
|
| 275 |
"เรียบเรียงหัวข้อการส่งมอบงานต่อไปนี้เป็นข้อความแจ้งกำหนดส่งมอบที่สะอาด:\n\n" + clause
|
| 276 |
)
|
| 277 |
|
| 278 |
-
out = _complete(instruction,
|
| 279 |
return (out, True) if out else (_raw_fallback(clause, selected_label), False)
|
|
|
|
| 4 |
and split it into selectable งวด.
|
| 5 |
|
| 6 |
- parse_nguad(clause) : deterministic; lists the งวด the user can pick (no AI, never fails).
|
| 7 |
+
- clean_delivery(...) : AI rewrite, then a deterministic fallback so generation never hard-fails.
|
| 8 |
+
- generate_body(...) : AI-generate the 2-paragraph letter body (deterministic fallback).
|
| 9 |
+
|
| 10 |
+
AI backend is selected by the AI_BACKEND env var:
|
| 11 |
+
"powerautomate" (default) → POST the prompt to the AI Builder flow at AIBUILDER_FLOW_URL.
|
| 12 |
+
"openrouter" → legacy OpenRouter path (code kept intact, PAUSED by default);
|
| 13 |
+
key(s) read from OPENROUTER_API_KEY[_2 .. _5].
|
| 14 |
+
"off" / "deterministic" → skip AI entirely; use the deterministic composer.
|
| 15 |
+
Any backend failure/timeout falls back to the deterministic composer, so output is always
|
| 16 |
+
on-format. To roll back to OpenRouter, set AI_BACKEND=openrouter (nothing was deleted).
|
| 17 |
"""
|
| 18 |
|
| 19 |
import os
|
|
|
|
| 25 |
|
| 26 |
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
|
| 27 |
|
| 28 |
+
# --- AI backend selection --------------------------------------------------
|
| 29 |
+
# Default backend is the Power Automate + AI Builder flow. OpenRouter is kept
|
| 30 |
+
# below purely for easy rollback (set AI_BACKEND=openrouter); it is not called
|
| 31 |
+
# under the default backend.
|
| 32 |
+
_DETERMINISTIC_BACKENDS = {"off", "none", "no", "false", "deterministic", ""}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _backend():
|
| 36 |
+
return (os.environ.get("AI_BACKEND") or "powerautomate").strip().lower()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _flow_url():
|
| 40 |
+
"""HTTP(S) POST URL of the AI Builder Power Automate flow (a HF Space secret in prod)."""
|
| 41 |
+
return (os.environ.get("AIBUILDER_FLOW_URL") or "").strip()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
THAI_MONTHS =["", "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน",
|
| 45 |
"กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"]
|
| 46 |
|
| 47 |
|
|
|
|
| 138 |
return (data["choices"][0]["message"]["content"] or "").strip()
|
| 139 |
|
| 140 |
|
| 141 |
+
def _call_powerautomate(url, prompt, timeout=90):
|
| 142 |
+
"""POST the prompt to the AI Builder Power Automate flow and return its text.
|
| 143 |
+
|
| 144 |
+
Request : {"prompt": <full instruction text>}
|
| 145 |
+
Response: either plain text, or JSON with the generated text under one of
|
| 146 |
+
text / result / output / response (the flow's Respond action shape)."""
|
| 147 |
+
body = json.dumps({"prompt": prompt}).encode("utf-8")
|
| 148 |
+
req = urllib.request.Request(
|
| 149 |
+
url, data=body, headers={"Content-Type": "application/json"})
|
| 150 |
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
| 151 |
+
raw = r.read().decode("utf-8", "ignore").strip()
|
| 152 |
+
try:
|
| 153 |
+
data = json.loads(raw)
|
| 154 |
+
except Exception: # plain-text response
|
| 155 |
+
return raw
|
| 156 |
+
if isinstance(data, dict):
|
| 157 |
+
for k in ("text", "result", "output", "response"):
|
| 158 |
+
v = data.get(k)
|
| 159 |
+
if v:
|
| 160 |
+
return str(v).strip()
|
| 161 |
+
return "" # unexpected JSON shape → fall back
|
| 162 |
+
return str(data).strip()
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _complete_powerautomate(system, user_content, accept, retries=2):
|
| 166 |
+
"""Run one completion through the Power Automate / AI Builder flow. The flow takes a
|
| 167 |
+
single instruction, so system + user are merged. Returns the accepted text, or None
|
| 168 |
+
(caller then uses the deterministic composer)."""
|
| 169 |
+
url = _flow_url()
|
| 170 |
+
if not url:
|
| 171 |
+
return None
|
| 172 |
+
prompt = (system + "\n\n" + user_content) if system else user_content
|
| 173 |
+
for attempt in range(retries):
|
| 174 |
+
try:
|
| 175 |
+
out = _call_powerautomate(url, prompt)
|
| 176 |
+
if out and accept(out):
|
| 177 |
+
return out
|
| 178 |
+
return None # responded but off-format → fallback
|
| 179 |
+
except urllib.error.HTTPError as e:
|
| 180 |
+
if e.code in (429, 500, 502, 503) and attempt < retries - 1:
|
| 181 |
+
time.sleep(0.8 * (attempt + 1)); continue
|
| 182 |
+
return None
|
| 183 |
+
except Exception: # noqa: BLE001 — network/timeout/parse
|
| 184 |
+
if attempt < retries - 1:
|
| 185 |
+
time.sleep(0.8 * (attempt + 1)); continue
|
| 186 |
+
return None
|
| 187 |
+
return None
|
| 188 |
+
|
| 189 |
+
|
| 190 |
def _api_keys(explicit=None):
|
| 191 |
"""Ordered list of OpenRouter API keys → auto-rotate across multiple accounts when
|
| 192 |
one hits its limit. Sources, in order: an explicit arg, then OPENROUTER_API_KEY (which
|
|
|
|
| 204 |
return keys
|
| 205 |
|
| 206 |
|
| 207 |
+
def _complete(user_content, api_keys, accept, retries=2, system=_SYSTEM):
|
| 208 |
+
"""Dispatch one completion to the selected AI backend and return the accepted text,
|
| 209 |
+
or None (the caller then uses the deterministic composer). Default backend is the
|
| 210 |
+
Power Automate / AI Builder flow; OpenRouter is only used when AI_BACKEND=openrouter."""
|
| 211 |
+
backend = _backend()
|
| 212 |
+
if backend in _DETERMINISTIC_BACKENDS:
|
| 213 |
+
return None
|
| 214 |
+
if backend == "powerautomate":
|
| 215 |
+
return _complete_powerautomate(system, user_content, accept, retries)
|
| 216 |
+
# --- legacy OpenRouter path (kept intact for rollback; off by default) ---
|
| 217 |
+
if not api_keys:
|
| 218 |
+
return None
|
| 219 |
for model in MODELS: # keep the SAME model as long as any account serves it
|
| 220 |
for key in api_keys: # rotate accounts on this model
|
| 221 |
for attempt in range(retries):
|
|
|
|
| 300 |
Falls back to the identical-format deterministic compose_body() on missing key / failure /
|
| 301 |
if the model drifts off-format — so the output is always exactly on-format."""
|
| 302 |
det = compose_body(fields)
|
| 303 |
+
if _backend() in _DETERMINISTIC_BACKENDS:
|
|
|
|
| 304 |
return det, False
|
| 305 |
|
| 306 |
verb = _verb(fields.get("procurement_type"))
|
|
|
|
| 317 |
f"DURATION={duration}\nSTART={(fields.get('start_date') or '').strip()}"
|
| 318 |
)
|
| 319 |
# accept only if on-format (both anchor phrases present); else fall back to det
|
| 320 |
+
out = _complete(user, _api_keys(api_key),
|
| 321 |
+
lambda o: "ตามที่" in o and "จึงขอแจ้งให้" in o, retries,
|
| 322 |
+
system=_BODY_SYSTEM)
|
| 323 |
return (out, True) if out else (det, False)
|
| 324 |
|
| 325 |
|
|
|
|
| 333 |
clause = (clause or "").strip()
|
| 334 |
if not clause:
|
| 335 |
return "", False
|
| 336 |
+
if _backend() in _DETERMINISTIC_BACKENDS:
|
|
|
|
| 337 |
return _raw_fallback(clause, selected_label), False
|
| 338 |
|
| 339 |
if selected_label and selected_label.startswith("งวดที่"):
|
|
|
|
| 349 |
"เรียบเรียงหัวข้อการส่งมอบงานต่อไปนี้เป็นข้อความแจ้งกำหนดส่งมอบที่สะอาด:\n\n" + clause
|
| 350 |
)
|
| 351 |
|
| 352 |
+
out = _complete(instruction, _api_keys(api_key), lambda o: bool(o), retries)
|
| 353 |
return (out, True) if out else (_raw_fallback(clause, selected_label), False)
|