Update handler.py
Browse files12345678910111267 unmodified lines80818283848554 unmodified lines1401411421431441451466 unmodified lines1531541551561571581591 unmodified line16116216316416516616716816917017117217317417517617717816 unmodified lines19519619719819920020135 unmodified lines23723823924024124224324424524624724824925025125225325425525625725825926026126226326426526657 unmodified lines32432532632732832933033133233333449 unmodified lines38438538638738838939057 unmodified lines4484494504514524534546 unmodified lines46146246346446546646711 unmodified lines479480481482# -*- coding: utf-8 -*-"""PULSE ECG Handler — Demo Parity Mode- 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"""import os67 unmodified linesargs = Nonemodel_initialized = False# ===================== Utilities =====================54 unmodified linesexcept Exception:return False# ====== Güvenli Stop Kriteri (demo eşleniği) ======class SafeKeywordsStoppingCriteria(StoppingCriteria):"""6 unmodified linesself.kw_ids = tok # shape: (n,)def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:# input_ids: (bsz, seq_len)if input_ids is None or input_ids.shape[0] == 0:return Falseout = input_ids[0] # assume bsz=11 unmodified lineif out.shape[0] < n:return Falsetail = out[-n:]# cihaz hizasıkw = self.kw_ids.to(tail.device)return torch.equal(tail, kw)# ===================== Core Generation =====================def _build_prompt_and_ids(chatbot, user_text: str, device: torch.device):# demo gibi: <image> + text (IM_START/END gerekiyorsa sar)use_wrap = _wrap_image_token_if_needed(chatbot.model.config)if use_wrap:# <im_start><image><im_end>\n + user textinp = f"{DEFAULT_IM_START_TOKEN}{DEFAULT_IMAGE_TOKEN}{DEFAULT_IM_END_TOKEN}\n{user_text}"else:inp = f"{DEFAULT_IMAGE_TOKEN}\n{user_text}"16 unmodified linesmax_new_tokens: Optional[int] = None,conv_mode_override: Optional[str] = None,repetition_penalty: Optional[float] = None, # demo'da yok; verilirse 1.0 yaparız# NOT: no_repeat_ngram_size / min_new_tokens / custom_stop KULLANMIYORUZ → demo-paritedet_seed: Optional[int] = None, # seed gönderilmezse stokastik (demo gibi)):if not (LLAVA_AVAILABLE and TRANSFORMERS_AVAILABLE):35 unmodified lines# Cihaz/dtypedevice = next(chatbot.model.parameters()).device# demo half: .half() kullanacağızdtype = torch.float16# Görüntü ön-işleme → tensörtry:processed = process_images([pil_img], chatbot.image_processor, chatbot.model.config)# LLaVA genelde list döndürürif isinstance(processed, (list, tuple)) and len(processed) > 0:image_tensor = processed[0]elif isinstance(processed, torch.Tensor):image_tensor = processed[0] if processed.ndim == 4 else processed # güvenlikelse:return {"error": "Image processing returned empty"}if image_tensor.ndim == 3:image_tensor = image_tensor.unsqueeze(0) # (1,C,H,W)# demo: half + deviceimage_tensor = image_tensor.to(device=device, dtype=dtype)except Exception as e:return {"error": f"Image processing failed: {e}"}# Prompt & input ids_, input_ids = _build_prompt_and_ids(chatbot, message_text, device)# Stop string from convstop_str = chatbot.conversation.sep if chatbot.conversation.sep_style != SeparatorStyle.TWO else chatbot.conversation.sep2stopping = SafeKeywordsStoppingCriteria(stop_str, chatbot.tokenizer)57 unmodified linesreturn {"status": "success", "response": text, "conversation_id": id(chatbot.conversation)}# ===================== Public API =====================def query(payload: dict):"""HF Endpoint entry (demo parity)."""global model_initialized, tokenizer, model, image_processor, context_len, argsif not model_initialized:if not initialize_model():49 unmodified lines"device": str(next(model.parameters()).device) if model else "Unknown",}# ===================== Init & Session =====================class _Args:57 unmodified linesmodel_ = model_.to(torch.device("cuda"))model_.eval()# assign globalsglobals()["tokenizer"] = tokenizer_globals()["model"] = model_globals()["image_processor"] = image_processor_6 unmodified linesprint(f"[init] failed: {e}")return False# ===================== HF EndpointHandler =====================class EndpointHandler:11 unmodified linesreturn get_model_info()if __name__ == "__main__":print("Handler ready (Demo Parity Mode). Use `EndpointHandler` or `query`.")1234567891011121367 unmodified lines8182838485868788899091929354 unmodified lines1481491501511521536 unmodified lines1601611621631641651 unmodified line16716816917017117217317417517617717817918018116 unmodified lines19819920020120220335 unmodified lines23924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826957 unmodified lines32732832933033133233333433533649 unmodified lines38638738838939039157 unmodified lines4494504514524534546 unmodified lines46146246346446546611 unmodified lines478479480481# -*- coding: utf-8 -*-"""PULSE ECG Handler — Demo Parity + Style Hint- 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) yaklaşmak için"""import os67 unmodified linesargs = Nonemodel_initialized = False# ====== Demo üslubuna yönlendiren stil ipucu ======STYLE_HINT = ("Write a concise diagnostic narrative as in a cardiology read: ""use 2–3 short paragraphs describing rhythm, rate, axis, chamber enlargement, conduction, QRS, ST–T, QT; ""then finish with a single final line starting exactly with 'Structured clinical impression:'. ""Do not include recommendations, prognosis, follow-up, or risk counseling. No emojis or bullet points.")# ===================== Utilities =====================54 unmodified linesexcept Exception:return False# ====== Güvenli Stop Kriteri (demo eşleniği) ======class SafeKeywordsStoppingCriteria(StoppingCriteria):"""6 unmodified linesself.kw_ids = tok # shape: (n,)def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:if input_ids is None or input_ids.shape[0] == 0:return Falseout = input_ids[0] # assume bsz=11 unmodified lineif out.shape[0] < n:return Falsetail = out[-n:]kw = self.kw_ids.to(tail.device)return torch.equal(tail, kw)# ===================== Core Generation =====================def _build_prompt_and_ids(chatbot, user_text: str, device: torch.device):# demo gibi: <image> + text (IM_START/END gerekiyorsa sar)use_wrap = _wrap_image_token_if_needed(chatbot.model.config)if 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}"16 unmodified linesmax_new_tokens: Optional[int] = None,conv_mode_override: Optional[str] = None,repetition_penalty: Optional[float] = None, # demo'da yok; verilirse 1.0 yaparızdet_seed: Optional[int] = None, # seed gönderilmezse stokastik (demo gibi)):if not (LLAVA_AVAILABLE and TRANSFORMERS_AVAILABLE):35 unmodified lines# Cihaz/dtypedevice = next(chatbot.model.parameters()).devicedtype = torch.float16 # demo: half# Görüntü ön-işleme → tensörtry:processed = process_images([pil_img], chatbot.image_processor, chatbot.model.config)if isinstance(processed, (list, tuple)) and len(processed) > 0:image_tensor = processed[0]elif isinstance(processed, torch.Tensor):image_tensor = processed[0] if processed.ndim == 4 else processedelse:return {"error": "Image processing returned empty"}if image_tensor.ndim == 3:image_tensor = image_tensor.unsqueeze(0) # (1,C,H,W)image_tensor = image_tensor.to(device=device, dtype=dtype) # demo: half + deviceexcept Exception as e:return {"error": f"Image processing failed: {e}"}# --------- STIL İPUCU EKLEME ---------message_text = (message_text or "").strip() + "\n\n" + STYLE_HINT# -------------------------------------# Prompt & input ids_, input_ids = _build_prompt_and_ids(chatbot, message_text, device)# Stop string (conv separator) → güvenli kriterstop_str = chatbot.conversation.sep if chatbot.conversation.sep_style != SeparatorStyle.TWO else chatbot.conversation.sep2stopping = SafeKeywordsStoppingCriteria(stop_str, chatbot.tokenizer)57 unmodified linesreturn {"status": "success", "response": text, "conversation_id": id(chatbot.conversation)}# ===================== Public API =====================def query(payload: dict):"""HF Endpoint entry (demo parity + style hint)."""global model_initialized, tokenizer, model, image_processor, context_len, argsif not model_initialized:if not initialize_model():49 unmodified lines"device": str(next(model.parameters()).device) if model else "Unknown",}# ===================== Init & Session =====================class _Args:57 unmodified linesmodel_ = model_.to(torch.device("cuda"))model_.eval()globals()["tokenizer"] = tokenizer_globals()["model"] = model_globals()["image_processor"] = image_processor_6 unmodified linesprint(f"[init] failed: {e}")return False# ===================== HF EndpointHandler =====================class EndpointHandler:11 unmodified linesreturn get_model_info()if __name__ == "__main__":print("Handler ready (Demo Parity + Style Hint). Use `EndpointHandler` or `query`.")
handler.py+19-20