diff --git a/kinguard/docvision/read.py b/kinguard/docvision/read.py index 3608e80..9bdd43a 100644 --- a/kinguard/docvision/read.py +++ b/kinguard/docvision/read.py @@ -158,6 +158,7 @@ def _call_model(image: bytes, mime_type: str) -> str: response = client.models.generate_content( model=settings().model, contents=[types.Part.from_bytes(data=image, mime_type=mime_type), _PROMPT], + config={"http_options": {"timeout": 25_000}}, ) return (response.text or "").strip() diff --git a/kinguard/payments/providers.py b/kinguard/payments/providers.py index b260813..51c7d73 100644 --- a/kinguard/payments/providers.py +++ b/kinguard/payments/providers.py @@ -60,11 +60,10 @@ def _auth_header() -> str: return "Basic " + base64.b64encode(pair.encode()).decode() -def _post(path: str, payload: dict) -> tuple[int, dict]: +def _post_json(url: str, payload: dict, headers: dict[str, str]) -> tuple[int, dict]: + """POST JSON to a Razorpay API endpoint, turning HTTP or network failures into errors.""" request = urllib.request.Request( - f"{API}{path}", data=json.dumps(payload).encode(), - headers={"Content-Type": "application/json", - "Authorization": _auth_header()}, + url, data=json.dumps(payload).encode(), headers=headers, ) try: with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response: @@ -74,6 +73,16 @@ def _post(path: str, payload: dict) -> tuple[int, dict]: return error.code, json.load(error) except Exception: # noqa: BLE001 - a non-JSON error body is still an error return error.code, {"error": {"description": error.reason}} + except (urllib.error.URLError, OSError, TimeoutError) as error: + return 0, {"error": {"description": f"network error: {type(error).__name__}: {error}"}} + + +def _post(path: str, payload: dict) -> tuple[int, dict]: + return _post_json( + f"{API}{path}", + payload, + {"Content-Type": "application/json", "Authorization": _auth_header()}, + ) def create_order(*, payment_id: str, amount_inr: int, payee_label: str, @@ -208,16 +217,7 @@ def _x_post(path: str, payload: dict, idempotency_key: str = "") -> tuple[int, d # request cannot pay a hospital twice. headers["X-Payout-Idempotency"] = idempotency_key - request = urllib.request.Request( - f"{XAPI}{path}", data=json.dumps(payload).encode(), headers=headers) - try: - with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response: - return response.status, json.load(response) - except urllib.error.HTTPError as error: - try: - return error.code, json.load(error) - except Exception: # noqa: BLE001 - a non-JSON error body is still an error - return error.code, {"error": {"description": error.reason}} + return _post_json(f"{XAPI}{path}", payload, headers) def _narration(bill_id: str) -> str: diff --git a/kinguard/webui/index.html b/kinguard/webui/index.html index 891dcbf..940ca44 100644 --- a/kinguard/webui/index.html +++ b/kinguard/webui/index.html @@ -430,6 +430,7 @@

KinGuard

intakeText:"", intakeBusy:false, intakeNorm:null, intakeErr:null, intakeSubmitted:null, explainBusy:false, explainOut:null, explainErr:null, explainScope:null, explainLang:"en", explainSource:null, + ttsSpeaking:false, ttsScope:null, uploadBusy:false, uploadMsg:null, uploadOk:false, uploadPrecheck:null, }, _loadedCaseId:null, @@ -2349,6 +2350,7 @@
This session
S.hybrid.intakeErr = null; S.hybrid.intakeSubmitted = null; S.hybrid.explainRequestId = (S.hybrid.explainRequestId || 0) + 1; + if(typeof stopExplainSpeak === "function") stopExplainSpeak(); if(clearParent) S.parentId = null; S.trail = null; S.brief = null; S.record = null; S.verify = null; S.wellbeing = null; S.careCircle = null; S.recovery = null; @@ -2818,9 +2820,14 @@
This session
${h.explainErr && h.explainScope===scope?`

${esc(h.explainErr)}

`:""} ${active?`
${esc(h.explainOut)}
-

- Generated from the recorded fields shown below. ${sourceBadge(h.explainSource)} Not clinical advice. -

+
+

+ Generated from the recorded fields shown below. ${sourceBadge(h.explainSource)} Not clinical advice. +

+ +
`:""} `; } @@ -2834,6 +2841,7 @@
This session
h.explainLang = lang; h.explainErr = null; h.explainOut = null; + if(typeof stopExplainSpeak === "function") stopExplainSpeak(); if(!h.ready || !h.model){ h.explainErr = h.reason; render(); @@ -2939,6 +2947,76 @@
This session
} } +const SPEECH_LANG_MAP = { en:"en-IN", ta:"ta-IN", hi:"hi-IN" }; +let _activeUtterance = null; + +function stopExplainSpeak(){ + _activeUtterance = null; + try{ + if(typeof window !== "undefined" && window.speechSynthesis && + (window.speechSynthesis.speaking || window.speechSynthesis.pending)) + window.speechSynthesis.cancel(); + }catch{ /* ignore */ } + S.hybrid.ttsSpeaking = false; + S.hybrid.ttsScope = null; +} + +function toggleExplainSpeak(scope){ + const h = S.hybrid; + if(typeof window === "undefined" || !("speechSynthesis" in window) || typeof SpeechSynthesisUtterance === "undefined"){ + h.explainErr = "Read-aloud (speechSynthesis) is not supported in this browser."; + render(); + return; + } + if(h.ttsSpeaking && h.ttsScope === scope){ + stopExplainSpeak(); + render(); + return; + } + if(h.explainScope !== scope || !h.explainOut) return; + const ctx = requestContext(); + const cleanText = String(h.explainOut).replace(/[*_`#]/g, "").replace(/\s+/g, " ").trim(); + if(!cleanText) return; + + stopExplainSpeak(); + const targetLang = SPEECH_LANG_MAP[h.explainLang] || "en-IN"; + const prefix = (h.explainLang || "en").toLowerCase(); + const utter = new SpeechSynthesisUtterance(cleanText); + utter.lang = targetLang; + try{ + const voices = window.speechSynthesis.getVoices?.() || []; + const match = voices.find(v => (v.lang || "").toLowerCase() === targetLang.toLowerCase()) + || voices.find(v => (v.lang || "").toLowerCase().startsWith(prefix)); + if(match) utter.voice = match; + }catch{ /* default voice */ } + + _activeUtterance = utter; + h.ttsSpeaking = true; + h.ttsScope = scope; + utter.onend = () => { + if(_activeUtterance !== utter) return; + _activeUtterance = null; + if(!contextIsCurrent(ctx)) return; + h.ttsSpeaking = false; + h.ttsScope = null; + render(); + }; + utter.onerror = event => { + if(_activeUtterance !== utter) return; + _activeUtterance = null; + if(!contextIsCurrent(ctx)) return; + h.ttsSpeaking = false; + h.ttsScope = null; + const err = event?.error || ""; + if(err && err !== "canceled" && err !== "interrupted") + h.explainErr = `Read-aloud could not play (${err}).`; + render(); + }; + try{ window.speechSynthesis.resume?.(); }catch{ /* ignore */ } + window.speechSynthesis.speak(utter); + render(); +} + initHybridAI(); render(); diff --git a/kinguard/wellbeing/escalation.py b/kinguard/wellbeing/escalation.py index d3d14c0..cd1e8f7 100644 --- a/kinguard/wellbeing/escalation.py +++ b/kinguard/wellbeing/escalation.py @@ -157,6 +157,7 @@ def read(text: str) -> Reading: response = client.models.generate_content( model=settings().model, contents=_PROMPT.format(text=text), + config={"http_options": {"timeout": 15_000}}, ) raw = (response.text or "").strip() # Models like to wrap JSON in a fence whatever the instruction says. diff --git a/tests/test_payments.py b/tests/test_payments.py index 00229f5..b523eca 100644 --- a/tests/test_payments.py +++ b/tests/test_payments.py @@ -2289,6 +2289,37 @@ def _with_a_contact(parent_id): consent_purposes=["billing_updates", "status_updates", "outbound_notify"]) +def test_provider_network_error_returns_clean_failure(monkeypatch): + """A transient TLS/network drop must return ProviderResult(ok=False), not raise.""" + import urllib.error + + from kinguard.payments import providers + + monkeypatch.setenv("RAZORPAY_KEY_ID", "rzp_test_unit") + monkeypatch.setenv("RAZORPAY_KEY_SECRET", "secret") + monkeypatch.setenv("RAZORPAYX_KEY_ID", "rzp_test_xunit") + monkeypatch.setenv("RAZORPAYX_KEY_SECRET", "xsecret") + monkeypatch.setenv("RAZORPAYX_ACCOUNT_NUMBER", "1234567890") + + def reset_tls(*_args, **_kwargs): + raise urllib.error.URLError(ConnectionResetError(54, "Connection reset by peer")) + + monkeypatch.setattr("urllib.request.urlopen", reset_tls) + + order = providers.create_order( + payment_id="pay-net-1", amount_inr=100, payee_label="Hospital", bill_id="bill-1", + ) + assert not order.ok + assert "network error" in order.detail + + payout = providers.create_payout( + payment_id="pay-net-2", amount_inr=100, payee_vpa="hospital@upi", + payee_label="Hospital", bill_id="bill-1", + ) + assert not payout.ok + assert "network error" in payout.detail + + def _stub_payment(parent_id, case_id): from datetime import UTC, datetime