SECTION_ORDER added
Browse files8 unmodified lines91011121314131 unmodified lines1461471481491501511521531541551561 unmodified line15815916016116216316469 unmodified lines23423523623723823971 unmodified lines31131231331431531631717 unmodified lines33533633733833934034134234334434534634734834935035129 unmodified lines38138238338438538638738838939039144 unmodified lines4364374384394404414426 unmodified lines449450451452453454154 unmodified lines6096106116126136146158 unmodified lines"""import osimport datetimeimport torchimport hashlib131 unmodified linesdef vote_last_response(state, vote_type, model_selector):try:with open(get_conv_vote_filename(), "a") as fout:data = {"type": vote_type,"model": model_selector,"state": state,}fout.write(json.dumps(data) + "\n")_safe_upload(get_conv_vote_filename())except Exception as e:1 unmodified line# Yalın uzantı listeleri (sorunlu formatlar çıkarıldı)IMAGE_EXTS = {"jpg", "jpeg", "png", "bmp", "gif", "tiff", "webp", "jfif"}# HEIC/HEIF: pillow-heif yoksa desteklemeyelimtry:import pillow_heif # noqa: F401IMAGE_EXTS.update({"heic", "heif"})69 unmodified linesreturn process_base64_image(image_input["image"])raise ValueError("Unsupported image input format")# ---------- Oturum / Konuşma ----------class InferenceDemo(object):71 unmodified linesuse_wrap = Falseif use_wrap:# <im_start><image></im_end>\n + metininp = f"{DEFAULT_IM_START_TOKEN}{DEFAULT_IMAGE_TOKEN}{DEFAULT_IM_END_TOKEN}\n{user_text}"else:inp = f"{DEFAULT_IMAGE_TOKEN}\n{user_text}"17 unmodified linesif not LLAVA_AVAILABLE:return {"error": "LLaVA modules not available"}# Zorunlu girişlerif not message_text or not image_input:return {"error": "Both message text and image are required"}# Chatbot alchatbot = chat_manager.get_chatbot(args, args.model_path if args else "PULSE-ECG/PULSE-7B",tokenizer, model, image_processor, context_len)# İsteğe bağlı conv overrideif conv_mode_override and conv_mode_override in conv_templates:chatbot.conversation = conv_templates[conv_mode_override].copy()else:29 unmodified linesprocessed = process_images([image], chatbot.image_processor, chatbot.model.config)if isinstance(processed, torch.Tensor):# (C,H,W) / (B,C,H,W) / (B,T,C,H,W)if processed.ndim == 3:image_tensor = processed.unsqueeze(0) # (1,C,H,W)elif processed.ndim == 4:image_tensor = processed # (B,C,H,W)elif processed.ndim == 5:b, t, c, h, w = processed.shapeimage_tensor = processed.reshape(b * t, c, h, w) # (B*T,C,H,W)44 unmodified linesimages=image_tensor,do_sample=False, # deterministikmax_new_tokens=int(max_output_tokens),min_new_tokens=600, # en az bu kadar üret (step başlıkları garanti)repetition_penalty=float(repetition_penalty),use_cache=False,pad_token_id=eos_id,6 unmodified linesgen = outputs[0][input_ids.shape[1]:]response = chatbot.tokenizer.decode(gen, skip_special_tokens=True)# Konuşmaya yerleştirif chatbot.conversation.messages and isinstance(chatbot.conversation.messages[-1], list):chatbot.conversation.messages[-1][-1] = response154 unmodified linesself.load_8bit = bool(int(os.getenv("LOAD_8BIT", "0")))self.load_4bit = bool(int(os.getenv("LOAD_4BIT", "0")))self.debug = bool(int(os.getenv("DEBUG", "0")))# args globaline ataglobals()["args"] = Args()model_name = get_model_name_from_path(args.model_path)8 unmodified lines9101112131415131 unmodified lines1471481491501511521531 unmodified line15515615715815916016169 unmodified lines23123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230371 unmodified lines37537637737837938017 unmodified lines39839940040140240340440540640740840941041129 unmodified lines44144244344444544644744844945044 unmodified lines4954964974984995005016 unmodified lines508509510511512513514515516154 unmodified lines6716726736746756766778 unmodified lines"""import osimport reimport datetimeimport torchimport hashlib131 unmodified linesdef vote_last_response(state, vote_type, model_selector):try:with open(get_conv_vote_filename(), "a") as fout:data = {"type": vote_type, "model": model_selector, "state": state}fout.write(json.dumps(data) + "\n")_safe_upload(get_conv_vote_filename())except Exception as e:1 unmodified line# Yalın uzantı listeleri (sorunlu formatlar çıkarıldı)IMAGE_EXTS = {"jpg", "jpeg", "png", "bmp", "gif", "tiff", "webp", "jfif"}# HEIC/HEIF: pillow-heif yoksa desteklemetry:import pillow_heif # noqa: F401IMAGE_EXTS.update({"heic", "heif"})69 unmodified linesreturn process_base64_image(image_input["image"])raise ValueError("Unsupported image input format")# ---------- Şablon dayatma (post-format) ----------SECTION_ORDER = ["Step 1: Rhythm Analysis","Step 2: Heart Rate Analysis","Step 3: Cardiac Axis Analysis","Step 4: P Wave Analysis","Step 5: PR Interval Analysis","Step 6: QRS Complex Analysis","Step 7: ST Segment Analysis","Step 8: T Wave Analysis","Step 9: QT/QTc Interval Analysis","Structured Clinical Impression:",]_SECTION_RE = re.compile(r"(Step\s*1:\s*Rhythm Analysis|"r"Step\s*2:\s*Heart Rate Analysis|"r"Step\s*3:\s*Cardiac Axis Analysis|"r"Step\s*4:\s*P Wave Analysis|"r"Step\s*5:\s*PR Interval Analysis|"r"Step\s*6:\s*QRS Complex Analysis|"r"Step\s*7:\s*ST Segment Analysis|"r"Step\s*8:\s*T Wave Analysis|"r"Step\s*9:\s*QT/QTc Interval Analysis|"r"Structured Clinical Impression:)",flags=re.IGNORECASE)def _enforce_section_template(text: str) -> str:"""Model çıktısını yakalayıp Step 1–9 + Structured başlıklarını sırayla ve eksiksizdöndürecek şekilde biçimler. Eksik bölümler 'Normal...' notuyla doldurulur."""pieces = _SECTION_RE.split(text)found = {}prefix = Noneif pieces:if not _SECTION_RE.match(pieces[0] or ""):prefix = (pieces[0] or "").strip()i = 1while i + 1 < len(pieces):heading = pieces[i].strip()content = pieces[i + 1].strip()for canonical in SECTION_ORDER:if heading.lower().startswith(canonical.lower().rstrip(":")):found[canonical] = contentbreaki += 2filled = []for sec in SECTION_ORDER:val = (found.get(sec, "") or "").strip()if not val:if sec.startswith("Step"):val = "Normal. No definite abnormality detected in this section based on the provided ECG image."else:val = "Overall impression: No acute life-threatening abnormality identified. Correlate clinically."filled.append(f"{sec}\n{val}")if prefix:filled[0] = filled[0] + f"\n\n(Additional notes captured before Step 1): {prefix}"return "\n\n".join(filled)# ---------- Oturum / Konuşma ----------class InferenceDemo(object):71 unmodified linesuse_wrap = Falseif use_wrap:inp = f"{DEFAULT_IM_START_TOKEN}{DEFAULT_IMAGE_TOKEN}{DEFAULT_IM_END_TOKEN}\n{user_text}"else:inp = f"{DEFAULT_IMAGE_TOKEN}\n{user_text}"17 unmodified linesif not LLAVA_AVAILABLE:return {"error": "LLaVA modules not available"}if not message_text or not image_input:return {"error": "Both message text and image are required"}chatbot = chat_manager.get_chatbot(args, args.model_path if args else "PULSE-ECG/PULSE-7B",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()else:29 unmodified linesprocessed = process_images([image], chatbot.image_processor, chatbot.model.config)if isinstance(processed, torch.Tensor):if processed.ndim == 3:image_tensor = processed.unsqueeze(0) # (1,C,H,W)elif processed.ndim == 4:image_tensor = processed # (B,C,H,W)elif processed.ndim == 5:b, t, c, h, w = processed.shapeimage_tensor = processed.reshape(b * t, c, h, w) # (B*T,C,H,W)44 unmodified linesimages=image_tensor,do_sample=False, # deterministikmax_new_tokens=int(max_output_tokens),min_new_tokens=800, # en az bu kadar üret (step başlıkları garanti)repetition_penalty=float(repetition_penalty),use_cache=False,pad_token_id=eos_id,6 unmodified linesgen = outputs[0][input_ids.shape[1]:]response = chatbot.tokenizer.decode(gen, skip_special_tokens=True)# ŞABLON ZORLAMA: Step1–9 + Structuredresponse = _enforce_section_template(response)# Konuşmaya yerleştirif chatbot.conversation.messages and isinstance(chatbot.conversation.messages[-1], list):chatbot.conversation.messages[-1][-1] = response154 unmodified linesself.load_8bit = bool(int(os.getenv("LOAD_8BIT", "0")))self.load_4bit = bool(int(os.getenv("LOAD_4BIT", "0")))self.debug = bool(int(os.getenv("DEBUG", "0")))globals()["args"] = Args()model_name = get_model_name_from_path(args.model_path)
handler.py+76-14