Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions kinguard/docvision/read.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
28 changes: 14 additions & 14 deletions kinguard/payments/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
84 changes: 81 additions & 3 deletions kinguard/webui/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,7 @@ <h1>KinGuard</h1>
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,
Expand Down Expand Up @@ -2349,6 +2350,7 @@ <h5>This session</h5>
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;
Expand Down Expand Up @@ -2818,9 +2820,14 @@ <h5>This session</h5>
${h.explainErr && h.explainScope===scope?`<p class="mute" style="margin-top:10px;color:var(--red-ink)">${esc(h.explainErr)}</p>`:""}
${active?`<div class="hyb-out">
<div style="white-space:pre-wrap">${esc(h.explainOut)}</div>
<p class="mute" style="margin-top:8px;font-size:12px">
Generated from the recorded fields shown below. ${sourceBadge(h.explainSource)} Not clinical advice.
</p>
<div class="hyb-bar" style="margin:10px 0 0">
<p class="mute" style="margin:0;font-size:12px">
Generated from the recorded fields shown below. ${sourceBadge(h.explainSource)} Not clinical advice.
</p>
<button type="button" class="btn ghost" style="min-height:34px;padding:5px 12px;font-size:12.5px"
onclick="toggleExplainSpeak('${esc(scope)}')">
${h.ttsSpeaking && h.ttsScope===scope ? "⏹ Stop reading" : "🔊 Listen"}</button>
</div>
</div>`:""}
</div>`;
}
Expand All @@ -2834,6 +2841,7 @@ <h5>This session</h5>
h.explainLang = lang;
h.explainErr = null;
h.explainOut = null;
if(typeof stopExplainSpeak === "function") stopExplainSpeak();
if(!h.ready || !h.model){
h.explainErr = h.reason;
render();
Expand Down Expand Up @@ -2939,6 +2947,76 @@ <h5>This session</h5>
}
}

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();
</script>
Expand Down
1 change: 1 addition & 0 deletions kinguard/wellbeing/escalation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
31 changes: 31 additions & 0 deletions tests/test_payments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading