Spaces:
Sleeping
Sleeping
Auto-form: remove the OpenRouter backend entirely (org policy) — AI Builder flow is the only AI backend
Browse files- ai_clean.py +13 -90
- streamlit_app.py +1 -1
ai_clean.py
CHANGED
|
@@ -9,11 +9,9 @@ and split it into selectable งวด.
|
|
| 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.
|
| 17 |
"""
|
| 18 |
|
| 19 |
import os
|
|
@@ -23,12 +21,8 @@ import time
|
|
| 23 |
import urllib.request
|
| 24 |
import urllib.error
|
| 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.
|
| 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 |
|
|
@@ -51,13 +45,6 @@ def thai_date(d):
|
|
| 51 |
return ""
|
| 52 |
return f"{d.day} {THAI_MONTHS[d.month]} {d.year + 543}"
|
| 53 |
|
| 54 |
-
# Primary = the user's choice; the rest are free fallbacks for when the primary 429s.
|
| 55 |
-
MODELS = [
|
| 56 |
-
"google/gemma-4-31b-it:free",
|
| 57 |
-
"meta-llama/llama-3.3-70b-instruct:free",
|
| 58 |
-
"openai/gpt-oss-120b:free",
|
| 59 |
-
]
|
| 60 |
-
|
| 61 |
_SYSTEM = (
|
| 62 |
"คุณเป็นผู้ช่วยร่างหนังสือราชการจัดซื้อจัดจ้างของ บริษัท ปตท. จำกัด (มหาชน) "
|
| 63 |
"หน้าที่ของคุณคือเรียบเรียงหัวข้อ \"การส่งมอบงาน/กำหนดส่งมอบ\" จาก TOR "
|
|
@@ -116,28 +103,6 @@ def _raw_fallback(clause, selected_label=None):
|
|
| 116 |
return " ".join(lines).strip()
|
| 117 |
|
| 118 |
|
| 119 |
-
def _call_openrouter(model, user_content, api_key, timeout=45):
|
| 120 |
-
body = json.dumps({
|
| 121 |
-
"model": model,
|
| 122 |
-
"messages": [
|
| 123 |
-
{"role": "system", "content": _SYSTEM},
|
| 124 |
-
{"role": "user", "content": user_content},
|
| 125 |
-
],
|
| 126 |
-
"temperature": 0.2,
|
| 127 |
-
}).encode("utf-8")
|
| 128 |
-
req = urllib.request.Request(
|
| 129 |
-
OPENROUTER_URL, data=body,
|
| 130 |
-
headers={
|
| 131 |
-
"Authorization": "Bearer " + api_key,
|
| 132 |
-
"Content-Type": "application/json",
|
| 133 |
-
"HTTP-Referer": "https://procurement-tools-auto-form.hf.space",
|
| 134 |
-
"X-Title": "PTT Auto Form",
|
| 135 |
-
})
|
| 136 |
-
with urllib.request.urlopen(req, timeout=timeout) as r:
|
| 137 |
-
data = json.load(r)
|
| 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 |
|
|
@@ -187,54 +152,13 @@ def _complete_powerautomate(system, user_content, accept, retries=2):
|
|
| 187 |
return None
|
| 188 |
|
| 189 |
|
| 190 |
-
def
|
| 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
|
| 193 |
-
may itself hold several keys separated by comma / whitespace / newline), then
|
| 194 |
-
OPENROUTER_API_KEY_2 … _5. Blanks and duplicates are dropped, order preserved."""
|
| 195 |
-
raw = [explicit or "", os.environ.get("OPENROUTER_API_KEY", "")]
|
| 196 |
-
raw += [os.environ.get(f"OPENROUTER_API_KEY_{i}", "") for i in range(2, 6)]
|
| 197 |
-
keys, seen = [], set()
|
| 198 |
-
for chunk in raw:
|
| 199 |
-
for k in re.split(r"[\s,]+", chunk or ""):
|
| 200 |
-
k = k.strip()
|
| 201 |
-
if k and k not in seen:
|
| 202 |
-
seen.add(k)
|
| 203 |
-
keys.append(k)
|
| 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).
|
| 210 |
-
Power Automate / AI Builder flow
|
| 211 |
-
|
| 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 |
-
|
| 220 |
-
for key in api_keys: # rotate accounts on this model
|
| 221 |
-
for attempt in range(retries):
|
| 222 |
-
try:
|
| 223 |
-
out = _call_openrouter(model, user_content, key)
|
| 224 |
-
if out and accept(out):
|
| 225 |
-
return out
|
| 226 |
-
break # responded but off-format → next account
|
| 227 |
-
except urllib.error.HTTPError as e:
|
| 228 |
-
if e.code == 429:
|
| 229 |
-
break # rate-limited → switch account NOW, same model
|
| 230 |
-
if e.code in (500, 502, 503) and attempt < retries - 1:
|
| 231 |
-
time.sleep(0.8 * (attempt + 1)); continue
|
| 232 |
-
break # other HTTP error → next account
|
| 233 |
-
except Exception: # noqa: BLE001 — network/timeout/parse
|
| 234 |
-
if attempt < retries - 1:
|
| 235 |
-
time.sleep(0.8 * (attempt + 1)); continue
|
| 236 |
-
break
|
| 237 |
-
return None
|
| 238 |
|
| 239 |
|
| 240 |
# ---------------------------------------------------------------------------
|
|
@@ -295,9 +219,9 @@ _BODY_SYSTEM = (
|
|
| 295 |
)
|
| 296 |
|
| 297 |
|
| 298 |
-
def generate_body(fields,
|
| 299 |
"""AI-generate the 2-paragraph เนื้อความ in the exact format. Returns (text, used_ai).
|
| 300 |
-
Falls back to the identical-format deterministic compose_body() on
|
| 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:
|
|
@@ -317,17 +241,16 @@ def generate_body(fields, api_key=None, retries=2):
|
|
| 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,
|
| 321 |
-
lambda o: "ตามที่" in o and "จึงขอแจ้งให้" in o, retries,
|
| 322 |
system=_BODY_SYSTEM)
|
| 323 |
return (out, True) if out else (det, False)
|
| 324 |
|
| 325 |
|
| 326 |
-
def clean_delivery(clause, selected_label=None,
|
| 327 |
"""Rewrite a delivery clause (optionally for a single selected งวด) into clean
|
| 328 |
letter Thai. Returns (text, used_ai): used_ai=False means the raw fallback was used.
|
| 329 |
|
| 330 |
-
Never raises — on
|
| 331 |
fallback so document generation always proceeds.
|
| 332 |
"""
|
| 333 |
clause = (clause or "").strip()
|
|
@@ -349,5 +272,5 @@ def clean_delivery(clause, selected_label=None, api_key=None, retries=2):
|
|
| 349 |
"เรียบเรียงหัวข้อการส่งมอบงานต่อไปนี้เป็นข้อความแจ้งกำหนดส่งมอบที่สะอาด:\n\n" + clause
|
| 350 |
)
|
| 351 |
|
| 352 |
-
out = _complete(instruction,
|
| 353 |
return (out, True) if out else (_raw_fallback(clause, selected_label), False)
|
|
|
|
| 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 |
"off" / "deterministic" → skip AI entirely; use the deterministic composer.
|
| 13 |
Any backend failure/timeout falls back to the deterministic composer, so output is always
|
| 14 |
+
on-format.
|
| 15 |
"""
|
| 16 |
|
| 17 |
import os
|
|
|
|
| 21 |
import urllib.request
|
| 22 |
import urllib.error
|
| 23 |
|
|
|
|
|
|
|
| 24 |
# --- AI backend selection --------------------------------------------------
|
| 25 |
+
# Default backend is the Power Automate + AI Builder flow.
|
|
|
|
|
|
|
| 26 |
_DETERMINISTIC_BACKENDS = {"off", "none", "no", "false", "deterministic", ""}
|
| 27 |
|
| 28 |
|
|
|
|
| 45 |
return ""
|
| 46 |
return f"{d.day} {THAI_MONTHS[d.month]} {d.year + 543}"
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
_SYSTEM = (
|
| 49 |
"คุณเป็นผู้ช่วยร่างหนังสือราชการจัดซื้อจัดจ้างของ บริษัท ปตท. จำกัด (มหาชน) "
|
| 50 |
"หน้าที่ของคุณคือเรียบเรียงหัวข้อ \"การส่งมอบงาน/กำหนดส่งมอบ\" จาก TOR "
|
|
|
|
| 103 |
return " ".join(lines).strip()
|
| 104 |
|
| 105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
def _call_powerautomate(url, prompt, timeout=90):
|
| 107 |
"""POST the prompt to the AI Builder Power Automate flow and return its text.
|
| 108 |
|
|
|
|
| 152 |
return None
|
| 153 |
|
| 154 |
|
| 155 |
+
def _complete(user_content, accept, retries=2, system=_SYSTEM):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
"""Dispatch one completion to the selected AI backend and return the accepted text,
|
| 157 |
+
or None (the caller then uses the deterministic composer). The only AI backend is
|
| 158 |
+
the Power Automate / AI Builder flow."""
|
| 159 |
+
if _backend() in _DETERMINISTIC_BACKENDS:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
return None
|
| 161 |
+
return _complete_powerautomate(system, user_content, accept, retries)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
|
| 164 |
# ---------------------------------------------------------------------------
|
|
|
|
| 219 |
)
|
| 220 |
|
| 221 |
|
| 222 |
+
def generate_body(fields, retries=2):
|
| 223 |
"""AI-generate the 2-paragraph เนื้อความ in the exact format. Returns (text, used_ai).
|
| 224 |
+
Falls back to the identical-format deterministic compose_body() on failure /
|
| 225 |
if the model drifts off-format — so the output is always exactly on-format."""
|
| 226 |
det = compose_body(fields)
|
| 227 |
if _backend() in _DETERMINISTIC_BACKENDS:
|
|
|
|
| 241 |
f"DURATION={duration}\nSTART={(fields.get('start_date') or '').strip()}"
|
| 242 |
)
|
| 243 |
# accept only if on-format (both anchor phrases present); else fall back to det
|
| 244 |
+
out = _complete(user, lambda o: "ตามที่" in o and "จึงขอแจ้งให้" in o, retries,
|
|
|
|
| 245 |
system=_BODY_SYSTEM)
|
| 246 |
return (out, True) if out else (det, False)
|
| 247 |
|
| 248 |
|
| 249 |
+
def clean_delivery(clause, selected_label=None, retries=2):
|
| 250 |
"""Rewrite a delivery clause (optionally for a single selected งวด) into clean
|
| 251 |
letter Thai. Returns (text, used_ai): used_ai=False means the raw fallback was used.
|
| 252 |
|
| 253 |
+
Never raises — on repeated failure it returns the deterministic
|
| 254 |
fallback so document generation always proceeds.
|
| 255 |
"""
|
| 256 |
clause = (clause or "").strip()
|
|
|
|
| 272 |
"เรียบเรียงหัวข้อการส่งมอบงานต่อไปนี้เป็นข้อความแจ้งกำหนดส่งมอบที่สะอาด:\n\n" + clause
|
| 273 |
)
|
| 274 |
|
| 275 |
+
out = _complete(instruction, lambda o: bool(o), retries)
|
| 276 |
return (out, True) if out else (_raw_fallback(clause, selected_label), False)
|
streamlit_app.py
CHANGED
|
@@ -24,7 +24,7 @@ from openpyxl.utils.datetime import from_excel
|
|
| 24 |
DATE_COLUMNS = {"poCreateDate"}
|
| 25 |
|
| 26 |
# AI "creating" animation shown while the document is being written (pure CSS, runs in the
|
| 27 |
-
# browser while Python blocks on the
|
| 28 |
AI_CREATE_ANIM_HTML = """
|
| 29 |
<div class="ai-create-wrap">
|
| 30 |
<div class="ai-create-card">
|
|
|
|
| 24 |
DATE_COLUMNS = {"poCreateDate"}
|
| 25 |
|
| 26 |
# AI "creating" animation shown while the document is being written (pure CSS, runs in the
|
| 27 |
+
# browser while Python blocks on the AI Builder call + docx render). Ember theme.
|
| 28 |
AI_CREATE_ANIM_HTML = """
|
| 29 |
<div class="ai-create-wrap">
|
| 30 |
<div class="ai-create-card">
|