Update handler.py
Browse files123456789101112131415161718192045 unmodified lines6667686970717223 unmodified lines969798991001011022 unmodified lines10510610710810911013 unmodified lines1241251261271281291301311321334 unmodified lines13813914014114214314417 unmodified lines16216316416516616716816910 unmodified lines18018118218318418518619 unmodified lines20620720820921021121228 unmodified lines24124224324424524624726 unmodified lines2742752762772782795 unmodified lines2852862872882892902912922932942952962972982993003019 unmodified lines3113123133143153163173183193203213223233243253263273282 unmodified lines3313323333343353363373388 unmodified lines34734834935035135235335411 unmodified lines36636736836937037137237337 unmodified lines4114124134144154169 unmodified lines42642742842943043118 unmodified lines4504514524534544557 unmodified lines46346446546646746852 unmodified lines5215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605611 unmodified line5635645655665675685699 unmodified lines5795805815825835845855865877 unmodified lines5955965975985996006015 unmodified lines60760860961061161261311 unmodified lines62562662762862963046 unmodified lines677678679680681# -*- coding: utf-8 -*-"""PULSE ECG Handler — Demo Parity + Style Hint + Robust Fallbacks + Debug + Dynamic Vision Size- Demo app.py ile aynı üretim ayarları:do_sample=True, temperature=0.05, top_p=1.0, max_new_tokens=4096- Stopping: konuşma ayırıcıda (conv.sep/sep2) güvenli token-eşleşmeli kriter- Görsel tensörü: .half() ve model cihazında- Streamer: TextIteratorStreamer (demo gibi), thread ile generate- Seed/deterministic KAPALI (göndermezseniz); demo gibi stokastik- STYLE_HINT: demo üslubuna (narratif + sonda tek satır structured impression)- Post-process: yalnızca whitespace/biçim temizliği- Ekler:* DEBUG yardımcıları (ENV: DEBUG=1)* Dynamic vision size: vision tower -> processor + preprocess/fallback* image_processor fallback (AutoProcessor → CLIPImageProcessor)* process_images fallback (torchvision + CLIP norm)* FastAPI wrapper: /health, /info, /query, /debug"""import os45 unmodified linesTRANSFORMERS_AVAILABLE = Falsewarn(f"transformers not available: {e}")# ====== HF Hub logging (opsiyonel) ======try:from huggingface_hub import HfApi, loginHF_HUB_AVAILABLE = True23 unmodified linesargs = Nonemodel_initialized = False# ====== Style Hint (demo benzeri üslup) ======STYLE_HINT = ("Write one concise narrative paragraph that covers rhythm, heart rate, cardiac axis, ""P waves and PR interval, QRS morphology and duration, ST segments, T waves, and QT/QTc. "2 unmodified lines"followed by a succinct, comma-separated summary of the key diagnoses.")# ===================== Utilities =====================def _safe_upload(path: str):if api and repo_name and path and os.path.isfile(path):13 unmodified linesdef load_image_any(image_input: Union[str, dict]) -> Image.Image:"""Desteklenen:- URL (http/https)- yerel dosya yolu- base64 (opsiyonel data URL prefix ile)- {"image": <base64|dataurl>}"""if isinstance(image_input, str):4 unmodified linesreturn Image.open(BytesIO(r.content)).convert("RGB")if os.path.exists(s):return Image.open(s).convert("RGB")# base64 (dataurl olabilir)if s.startswith("data:image"):s = s.split(",", 1)[1]raw = base64.b64decode(s)17 unmodified lines# ====== Vision helpers (dynamic size) ======def get_vision_expected_size(m, default: int = 336) -> int:"""Modelin vision tower'ının beklediği input boyutunu döndürür (örn. 336).LLaVA/CLIP konfiglerinde genelde `image_size` bulunur."""try:vt = m.get_vision_tower()10 unmodified linesreturn defaultdef force_processor_size(proc, size: int):"""Processor'ın resize/crop alanlarını güvenle hedef boyuta zorlar."""try:# sizeif hasattr(proc, "size"):19 unmodified linesexcept Exception as e:warn(f"[processor] force size failed: {e}")# ====== Güvenli Stop Kriteri (conv separator) ======class SafeKeywordsStoppingCriteria(StoppingCriteria):def __init__(self, keyword: str, tokenizer):self.tokenizer = tokenizer28 unmodified linesdef __init__(self):self.chatbot = Noneself.args = Noneself.model_path = Nonedef init_if_needed(self, args, model_path, tokenizer, model, image_processor, context_len):if self.chatbot is None:self.args = args26 unmodified linesconv_mode_override: Optional[str] = None,repetition_penalty: Optional[float] = None,det_seed: Optional[int] = None,):if not (LLAVA_AVAILABLE and TRANSFORMERS_AVAILABLE):return {"error": "Required libraries not available (llava/transformers)"}5 unmodified linesif max_new_tokens is None: max_new_tokens = 4096if repetition_penalty is None: repetition_penalty = 1.0dbg(f"[gen] temperature={temperature} top_p={top_p} max_new_tokens={max_new_tokens} rep={repetition_penalty} seed={det_seed}")chatbot = chat_manager.get_chatbot(args, args.model_path, tokenizer, model, image_processor, context_len)if conv_mode_override and conv_mode_override in conv_templates:chatbot.conversation = conv_templates[conv_mode_override].copy()try:pil_img = load_image_any(image_input)except Exception as e:return {"error": f"Failed to load image: {e}"}img_hash, img_path = "NA", Nonetry:buf = BytesIO(); pil_img.save(buf, format="JPEG"); raw = buf.getvalue()9 unmodified linesdevice = next(chatbot.model.parameters()).devicedtype = torch.float16# === Görüntü ön-işleme → tensör (dinamik boy) ===expected_size = get_vision_expected_size(chatbot.model, default=336)dbg(f"[pre] dynamic expected_size={expected_size} | processor={type(chatbot.image_processor)}")# 3.1) Processor.preprocess varsa kullan (en stabil yol)image_tensor = Nonetry:if hasattr(chatbot.image_processor, "preprocess"):px = chatbot.image_processor.preprocess(pil_img, return_tensors="pt")image_tensor = px.get("pixel_values", px)if not isinstance(image_tensor, torch.Tensor):# Bazı processor'lar nested dict döndürebilirimage_tensor = image_tensor["pixel_values"]if image_tensor.ndim == 3:image_tensor = image_tensor.unsqueeze(0)2 unmodified lineselse:raise AttributeError("processor has no preprocess")except Exception as e_pre:warn(f"[pre] processor.preprocess not used: {e_pre} → process_images denenecek…")# 3.2) LLaVA'nın process_images yolutry:processed = process_images([pil_img], chatbot.image_processor, chatbot.model.config)if isinstance(processed, (list, tuple)) and len(processed) > 0:8 unmodified linesimage_tensor = image_tensor.to(device=device, dtype=dtype)dbg(f"[pre] process_images ok → {tuple(image_tensor.shape)}")except Exception as e_proc:warn(f"[pre] process_images failed: {e_proc} → manual CLIP fallback (dinamik size) kullanılacak.")# 3.3) Manuel CLIP fallback (dinamik expected_size)from torchvision import transformsfrom torchvision.transforms import InterpolationModepreprocess = transforms.Compose([11 unmodified linesif image_tensor is None:return {"error": "Image processing failed (no tensor produced)"}msg = (message_text or "").strip()msg = f"{msg}\n\n{STYLE_HINT}"dbg(f"[prompt] conv_sep_style={chatbot.conversation.sep_style} sep_len={len(chatbot.conversation.sep)}")_, input_ids = _build_prompt_and_ids(chatbot, msg, device)37 unmodified linesexcept Exception as e:return {"error": f"Generation failed: {e}"}try:row = {"time": datetime.datetime.now().isoformat(),9 unmodified linesexcept Exception as e:warn(f"[log] failed: {e}")return {"status": "success", "response": text, "conversation_id": id(chatbot.conversation)}# ===================== Public API =====================18 unmodified linesconv_mode_override = payload.get("conv_mode", None)det_seed = payload.get("det_seed", None)if det_seed is not None:try: det_seed = int(det_seed)except Exception: det_seed = None7 unmodified linesconv_mode_override=conv_mode_override,repetition_penalty=repetition_penalty,det_seed=det_seed,)except Exception as e:return {"error": f"Query failed: {e}"}52 unmodified linesmodel_.eval()dbg(f"[init] device={next(model_.parameters()).device}, cuda_available={torch.cuda.is_available()}")# --- vision tower beklenen image_size'ı al ---expected_size = get_vision_expected_size(model_, default=336)dbg(f"[init] vision expected image_size={expected_size}")# --- image_processor fallback zinciri (model path > AutoProcessor > CLIP 224/336) ---try:if image_processor_ is None:dbg("[init] image_processor None → AutoProcessor(model_path) deneniyor…")try:from transformers import AutoProcessorimage_processor_ = AutoProcessor.from_pretrained(args.model_path)dbg("[init] image_processor: AutoProcessor.from_pretrained(model_path) yüklendi.")except Exception as _e1:dbg(f"[init] AutoProcessor(model_path) failed: {_e1}")try:from transformers import AutoProcessorclip_id = "openai/clip-vit-large-patch14-336" if expected_size >= 336 else "openai/clip-vit-large-patch14"image_processor_ = AutoProcessor.from_pretrained(clip_id)dbg(f"[init] AutoProcessor({clip_id}) yüklendi.")except Exception as _e2:from transformers import CLIPImageProcessorclip_id = "openai/clip-vit-large-patch14-336" if expected_size >= 336 else "openai/clip-vit-large-patch14"image_processor_ = CLIPImageProcessor.from_pretrained(clip_id)warn(f"[init] CLIPImageProcessor({clip_id}) fallback kullanılıyor.")except Exception as _e:warn(f"[init] image_processor fallback chain failed: {_e}")# --- processor'ın boyutlarını vision tower'a uydur ---try:if image_processor_ is not None:force_processor_size(image_processor_, expected_size)except Exception as e_ip:warn(f"[init] processor size set error: {e_ip}")# --- image_processor introspection ---try:ip = image_processor_if ip is not None:1 unmodified linesize_sz = getattr(getattr(ip, "size", None), "shortest_edge", None) or getattr(ip, "size", None)dbg(f"[init] image_processor crop_size={crop_sz} size={size_sz} class={ip.__class__.__name__}")else:warn("[init] image_processor yine None (fallback da başarısız).")except Exception as e_ip2:warn(f"[init] image_processor inspect error: {e_ip2}")9 unmodified lineswarn(f"[init] failed: {e}")return False# ===================== HF EndpointHandler =====================class EndpointHandler:"""Hugging Face Endpoint uyumlu sınıf"""def __init__(self, model_dir):self.model_dir = model_dirprint(f"EndpointHandler initialized with model_dir: {model_dir}")7 unmodified linesreturn get_model_info()if __name__ == "__main__":print("Handler ready (Demo Parity + Style Hint + whitespace post-process + dynamic size + fallbacks + debug). Use `EndpointHandler` or `query`.")# ===================== Minimal FastAPI Wrapper =====================try:5 unmodified lineswarn(f"fastapi/pydantic not available: {e}")if FASTAPI_AVAILABLE:app = FastAPI(title="PULSE ECG Handler API", version="1.0.0")class QueryIn(BaseModel):message: str | None = None11 unmodified linesrepetition_penalty: float | None = Noneconv_mode: str | None = Nonedet_seed: int | None = None@app.on_event("startup")async def _startup():46 unmodified lines@app.post("/query")async def _query(payload: QueryIn):return query({k: v for k, v in payload.dict().items() if v is not None})else:app = None # uvicorn handler:app çalıştırıldığında import error verir12345678910111213141516171819202145 unmodified lines6768697071727323 unmodified lines9798991001011021032 unmodified lines10610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513 unmodified lines1491501511521531541551561571584 unmodified lines16316416516616716816917 unmodified lines18718818919019119219310 unmodified lines20420520620720820921019 unmodified lines23023123223323423523628 unmodified lines26526626726826927027126 unmodified lines2982993003013023033045 unmodified lines3103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623639 unmodified lines3733743753763773783793803813823833843853863873882 unmodified lines3913923933943953963978 unmodified lines40640740840941041141211 unmodified lines42442542642742842943043143243343443543637 unmodified lines4744754764774784794809 unmodified lines49049149249349449549649749849950050150250350450550650750818 unmodified lines5275285295305315325335347 unmodified lines54254354454554654754852 unmodified lines6016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406411 unmodified line6436446456466476486499 unmodified lines6596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037 unmodified lines7117127137147157167175 unmodified lines72372472572672772872911 unmodified lines74174274374474574674746 unmodified lines794795796797798799800801802803804805806807808809810# -*- coding: utf-8 -*-"""PULSE ECG Handler — Demo Parity + Style Hint + Robust Fallbacks + Debug + Dynamic Vision Size + JSON/Report (EN)- Generation settings aligned with demo app.py:do_sample=True, temperature=0.05, top_p=1.0, max_new_tokens=4096- Stopping: safe keyword match on conversation separator (conv.sep/sep2)- Image tensor: .half() on model device- Streamer: TextIteratorStreamer with background thread (demo-like)- Stochastic by default (seed/deterministic OFF unless provided)- STYLE_HINT: narrative + single-line 'Structured clinical impression:' ending- Post-process: whitespace cleanup only- Extras:* DEBUG helpers (ENV: DEBUG=1)* Dynamic vision size (vision tower -> processor + preprocess/fallback)* image_processor fallback (AutoProcessor → CLIPImageProcessor)* process_images fallback (torchvision + CLIP norm)* FastAPI wrapper: /health, /info, /query, /debug, /analyze/json, /analyze/report-en* JSON schema (EN) and report renderer (table text + narrative)"""import os45 unmodified linesTRANSFORMERS_AVAILABLE = Falsewarn(f"transformers not available: {e}")# ====== HF Hub logging (optional) ======try:from huggingface_hub import HfApi, loginHF_HUB_AVAILABLE = True23 unmodified linesargs = Nonemodel_initialized = False# ====== Style Hint (demo-like narrative) ======STYLE_HINT = ("Write one concise narrative paragraph that covers rhythm, heart rate, cardiac axis, ""P waves and PR interval, QRS morphology and duration, ST segments, T waves, and QT/QTc. "2 unmodified lines"followed by a succinct, comma-separated summary of the key diagnoses.")# ====== JSON Schema (EN) for strict machine-readable output ======JSON_SCHEMA_HINT_EN = """Return ONLY a valid JSON object that matches EXACTLY this schema:{"heart_rate_bpm": int, // e.g., 128"rhythm": "string", // e.g., "Sinus tachycardia""qrs_axis": "string", // e.g., "Normal (+16°)""p_waves": "string", // e.g., "Normal""pr_interval_ms": int, // e.g., 160"qrs_duration_ms": int, // e.g., 84"t_waves": "string", // e.g., "Negative in DIII, aVF, V1–V4""qtc_ms": int, // e.g., 467"qtc_comment": "string", // e.g., "Mildly prolonged""additional_comments": "string" // e.g., "S1Q3T3 pattern and anterior T-wave inversions present."}Rules:- Output MUST be valid JSON with no extra text before or after.- Units: use numbers for bpm and ms (integers only).- If unknown, use null (ints may be null).- Use standard cardiology terminology in English."""# ===================== Utilities =====================def _safe_upload(path: str):if api and repo_name and path and os.path.isfile(path):13 unmodified linesdef load_image_any(image_input: Union[str, dict]) -> Image.Image:"""Supported:- URL (http/https)- local file path- base64 (optionally with data URL prefix)- {"image": <base64|dataurl>}"""if isinstance(image_input, str):4 unmodified linesreturn Image.open(BytesIO(r.content)).convert("RGB")if os.path.exists(s):return Image.open(s).convert("RGB")# base64 (maybe dataurl)if s.startswith("data:image"):s = s.split(",", 1)[1]raw = base64.b64decode(s)17 unmodified lines# ====== Vision helpers (dynamic size) ======def get_vision_expected_size(m, default: int = 336) -> int:"""Returns expected image size for the model's vision tower (e.g., 336)."""try:vt = m.get_vision_tower()10 unmodified linesreturn defaultdef force_processor_size(proc, size: int):"""Force processor resize/crop to target size safely."""try:# sizeif hasattr(proc, "size"):19 unmodified linesexcept Exception as e:warn(f"[processor] force size failed: {e}")# ====== Safe Stop Criteria (conv separator) ======class SafeKeywordsStoppingCriteria(StoppingCriteria):def __init__(self, keyword: str, tokenizer):self.tokenizer = tokenizer28 unmodified linesdef __init__(self):self.chatbot = Noneself.args = Noneself.model_path = Nonedef init_if_needed(self, args, model_path, tokenizer, model, image_processor, context_len):if self.chatbot is None:self.args = args26 unmodified linesconv_mode_override: Optional[str] = None,repetition_penalty: Optional[float] = None,det_seed: Optional[int] = None,output_mode: Optional[str] = "narrative", # "narrative" | "json" | "report_en"):if not (LLAVA_AVAILABLE and TRANSFORMERS_AVAILABLE):return {"error": "Required libraries not available (llava/transformers)"}5 unmodified linesif max_new_tokens is None: max_new_tokens = 4096if repetition_penalty is None: repetition_penalty = 1.0dbg(f"[gen] temperature={temperature} top_p={top_p} max_new_tokens={max_new_tokens} rep={repetition_penalty} seed={det_seed} mode={output_mode}")# For "report_en", compose by calling json + narrative branchesif output_mode == "report_en":first = generate_response(message_text=message_text,image_input=image_input,temperature=temperature, top_p=top_p,max_new_tokens=max_new_tokens,conv_mode_override=conv_mode_override,repetition_penalty=repetition_penalty,det_seed=det_seed,output_mode="json",)if not isinstance(first, dict) or "response" not in first or not isinstance(first["response"], dict):return firstdata = first["response"]second = generate_response(message_text=message_text,image_input=image_input,temperature=temperature, top_p=top_p,max_new_tokens=min(int(max_new_tokens), 512),conv_mode_override=conv_mode_override,repetition_penalty=repetition_penalty,det_seed=det_seed,output_mode="narrative",)narrative = second.get("response") if isinstance(second, dict) else Nonetable_txt = render_ecg_table_en(data)return {"status": "success","report": {"table_text": table_txt, "json": data, "narrative": narrative},"conversation_id": id(chatbot) # not conversation; narrative branch already logged}chatbot = chat_manager.get_chatbot(args, args.model_path, tokenizer, model, image_processor, context_len)if conv_mode_override and conv_mode_override in conv_templates:chatbot.conversation = conv_templates[conv_mode_override].copy()# Load image (PIL)try:pil_img = load_image_any(image_input)except Exception as e:return {"error": f"Failed to load image: {e}"}# Save image log (optional)img_hash, img_path = "NA", Nonetry:buf = BytesIO(); pil_img.save(buf, format="JPEG"); raw = buf.getvalue()9 unmodified linesdevice = next(chatbot.model.parameters()).devicedtype = torch.float16# === Image preprocessing → tensor (dynamic size) ===expected_size = get_vision_expected_size(chatbot.model, default=336)dbg(f"[pre] dynamic expected_size={expected_size} | processor={type(chatbot.image_processor)}")image_tensor = Nonetry:if hasattr(chatbot.image_processor, "preprocess"):px = chatbot.image_processor.preprocess(pil_img, return_tensors="pt")image_tensor = px.get("pixel_values", px)if not isinstance(image_tensor, torch.Tensor):image_tensor = image_tensor["pixel_values"]if image_tensor.ndim == 3:image_tensor = image_tensor.unsqueeze(0)2 unmodified lineselse:raise AttributeError("processor has no preprocess")except Exception as e_pre:warn(f"[pre] processor.preprocess not used: {e_pre} → process_images fallback…")try:processed = process_images([pil_img], chatbot.image_processor, chatbot.model.config)if isinstance(processed, (list, tuple)) and len(processed) > 0:8 unmodified linesimage_tensor = image_tensor.to(device=device, dtype=dtype)dbg(f"[pre] process_images ok → {tuple(image_tensor.shape)}")except Exception as e_proc:warn(f"[pre] process_images failed: {e_proc} → manual CLIP fallback (dynamic size).")from torchvision import transformsfrom torchvision.transforms import InterpolationModepreprocess = transforms.Compose([11 unmodified linesif image_tensor is None:return {"error": "Image processing failed (no tensor produced)"}# ===== Build message according to output_mode =====base_msg = (message_text or "").strip()if output_mode == "json":msg = f"{base_msg}\n\n{JSON_SCHEMA_HINT_EN}"else: # "narrative"msg = f"{base_msg}\n\n{STYLE_HINT}"dbg(f"[prompt] conv_sep_style={chatbot.conversation.sep_style} sep_len={len(chatbot.conversation.sep)}")_, input_ids = _build_prompt_and_ids(chatbot, msg, device)37 unmodified linesexcept Exception as e:return {"error": f"Generation failed: {e}"}# Loggingtry:row = {"time": datetime.datetime.now().isoformat(),9 unmodified linesexcept Exception as e:warn(f"[log] failed: {e}")# If JSON mode, parse and return as objectif output_mode == "json":try:start = text.find("{"); end = text.rfind("}")if start != -1 and end != -1 and end > start:obj = json.loads(text[start:end+1])else:return {"error": "JSON block not found", "raw": text}except Exception as e:return {"error": f"JSON parse failed: {e}", "raw": text}return {"status": "success", "response": obj, "conversation_id": id(chatbot.conversation)}# Default narrativereturn {"status": "success", "response": text, "conversation_id": id(chatbot.conversation)}# ===================== Public API =====================18 unmodified linesconv_mode_override = payload.get("conv_mode", None)det_seed = payload.get("det_seed", None)output_mode = payload.get("output_mode", "narrative") # "narrative" | "json" | "report_en"if det_seed is not None:try: det_seed = int(det_seed)except Exception: det_seed = None7 unmodified linesconv_mode_override=conv_mode_override,repetition_penalty=repetition_penalty,det_seed=det_seed,output_mode=output_mode,)except Exception as e:return {"error": f"Query failed: {e}"}52 unmodified linesmodel_.eval()dbg(f"[init] device={next(model_.parameters()).device}, cuda_available={torch.cuda.is_available()}")# Vision tower expected image sizeexpected_size = get_vision_expected_size(model_, default=336)dbg(f"[init] vision expected image_size={expected_size}")# image_processor fallback chaintry:if image_processor_ is None:dbg("[init] image_processor None → AutoProcessor(model_path)…")try:from transformers import AutoProcessorimage_processor_ = AutoProcessor.from_pretrained(args.model_path)dbg("[init] image_processor: AutoProcessor.from_pretrained(model_path) loaded.")except Exception as _e1:dbg(f"[init] AutoProcessor(model_path) failed: {_e1}")try:from transformers import AutoProcessorclip_id = "openai/clip-vit-large-patch14-336" if expected_size >= 336 else "openai/clip-vit-large-patch14"image_processor_ = AutoProcessor.from_pretrained(clip_id)dbg(f"[init] AutoProcessor({clip_id}) loaded.")except Exception as _e2:from transformers import CLIPImageProcessorclip_id = "openai/clip-vit-large-patch14-336" if expected_size >= 336 else "openai/clip-vit-large-patch14"image_processor_ = CLIPImageProcessor.from_pretrained(clip_id)warn(f"[init] CLIPImageProcessor({clip_id}) fallback in use.")except Exception as _e:warn(f"[init] image_processor fallback chain failed: {_e}")# Force processor sizes to match towertry:if image_processor_ is not None:force_processor_size(image_processor_, expected_size)except Exception as e_ip:warn(f"[init] processor size set error: {e_ip}")# Processor introspectiontry:ip = image_processor_if ip is not None:1 unmodified linesize_sz = getattr(getattr(ip, "size", None), "shortest_edge", None) or getattr(ip, "size", None)dbg(f"[init] image_processor crop_size={crop_sz} size={size_sz} class={ip.__class__.__name__}")else:warn("[init] image_processor still None (fallback failed).")except Exception as e_ip2:warn(f"[init] image_processor inspect error: {e_ip2}")9 unmodified lineswarn(f"[init] failed: {e}")return False# ===================== Report rendering (EN) =====================def render_ecg_table_en(d: Dict[str, Any]) -> str:def g(k, default="—"):v = d.get(k, None)if v is None: return defaultreturn str(v)hr = g("heart_rate_bpm")rhythm = g("rhythm")axis = g("qrs_axis")p = g("p_waves")pr = g("pr_interval_ms")qrs_dur = g("qrs_duration_ms")t = g("t_waves")qtc = g("qtc_ms")qtc_c = g("qtc_comment")extra = g("additional_comments")lines = ["ECG ANALYSIS","────────────",f"Heart rate : {hr} beats/min",f"Rhythm : {rhythm}",f"QRS axis : {axis}",f"P waves : {p}",f"PR interval : {pr} ms",f"QRS duration : {qrs_dur} ms",f"T waves : {t}",f"QTc : {qtc_c} ({qtc} ms)","","Additional comments","──────────────────",f"{extra}"]return "\n".join(lines)# ===================== HF EndpointHandler =====================class EndpointHandler:"""Hugging Face Endpoint-compatible wrapper."""def __init__(self, model_dir):self.model_dir = model_dirprint(f"EndpointHandler initialized with model_dir: {model_dir}")7 unmodified linesreturn get_model_info()if __name__ == "__main__":print("Handler ready (Demo Parity + Style Hint + whitespace post-process + dynamic size + fallbacks + debug + JSON/Report-EN). Use `EndpointHandler` or `query`.")# ===================== Minimal FastAPI Wrapper =====================try:5 unmodified lineswarn(f"fastapi/pydantic not available: {e}")if FASTAPI_AVAILABLE:app = FastAPI(title="PULSE ECG Handler API", version="1.1.0")class QueryIn(BaseModel):message: str | None = None11 unmodified linesrepetition_penalty: float | None = Noneconv_mode: str | None = Nonedet_seed: int | None = Noneoutput_mode: str | None = None # "narrative" | "json" | "report_en"@app.on_event("startup")async def _startup():46 unmodified lines@app.post("/query")async def _query(payload: QueryIn):return query({k: v for k, v in payload.dict().items() if v is not None})@app.post("/analyze/json")async def analyze_json(payload: QueryIn):data = {k: v for k, v in payload.dict().items() if v is not None}data["output_mode"] = "json"return query(data)@app.post("/analyze/report-en")async def analyze_report_en(payload: QueryIn):data = {k: v for k, v in payload.dict().items() if v is not None}data["output_mode"] = "report_en"return query(data)else:app = None # Running "uvicorn handler:app" will raise import error if FastAPI missing
handler.py+175-46