Update handler.py
Browse files12334567891011121367 unmodified lines8182838485868788899091929354 unmodified lines1481491501431511521536 unmodified lines1601611621561631641651 unmodified line16716816916417017117216817317417517617717817517918018116 unmodified lines19819920019820120220335 unmodified lines23924024124024124224324424524624624724824925025025125225325425525625525625725825926026126226326426526326626726826957 unmodified lines32732832932733033133233133333433533649 unmodified lines38638738838738939039157 unmodified lines4494504514514524534546 unmodified lines46146246346446446546611 unmodified lines478479480482481# -*- coding: utf-8 -*-"""PULSE ECG Handler — Demo Parity ModePULSE 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 lines except Exception: return False
# ====== Güvenli Stop Kriteri (demo eşleniği) ======class SafeKeywordsStoppingCriteria(StoppingCriteria): """6 unmodified lines self.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 False out = input_ids[0] # assume bsz=11 unmodified line if out.shape[0] < n: return False tail = 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 text 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 lines max_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-parite det_seed: Optional[int] = None, # seed gönderilmezse stokastik (demo gibi)): if not (LLAVA_AVAILABLE and TRANSFORMERS_AVAILABLE):35 unmodified lines
# Cihaz/dtype device = next(chatbot.model.parameters()).device # demo half: .half() kullanacağız dtype = torch.float16 dtype = torch.float16 # demo: half
# Görüntü ön-işleme → tensör try: processed = process_images([pil_img], chatbot.image_processor, chatbot.model.config) # LLaVA genelde list döndürür 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 processed # güvenlik image_tensor = processed[0] if processed.ndim == 4 else processed else: return {"error": "Image processing returned empty"} if image_tensor.ndim == 3: image_tensor = image_tensor.unsqueeze(0) # (1,C,H,W) # demo: half + device image_tensor = image_tensor.to(device=device, dtype=dtype) image_tensor = image_tensor.to(device=device, dtype=dtype) # demo: half + device except 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 from conv # Stop string (conv separator) → güvenli kriter stop_str = chatbot.conversation.sep if chatbot.conversation.sep_style != SeparatorStyle.TWO else chatbot.conversation.sep2 stopping = SafeKeywordsStoppingCriteria(stop_str, chatbot.tokenizer)
57 unmodified lines
return {"status": "success", "response": text, "conversation_id": id(chatbot.conversation)}
# ===================== Public API =====================
def query(payload: dict): """HF Endpoint entry (demo parity).""" """HF Endpoint entry (demo parity + style hint).""" global model_initialized, tokenizer, model, image_processor, context_len, args if 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 lines model_ = model_.to(torch.device("cuda")) model_.eval()
# assign globals globals()["tokenizer"] = tokenizer_ globals()["model"] = model_ globals()["image_processor"] = image_processor_6 unmodified lines print(f"[init] failed: {e}") return False
# ===================== HF EndpointHandler =====================
class EndpointHandler:11 unmodified lines return get_model_info()
if __name__ == "__main__": print("Handler ready (Demo Parity Mode). Use `EndpointHandler` or `query`.") print("Handler ready (Demo Parity + Style Hint). Use `EndpointHandler` or `query`.")handler.py+19-20