normalize_whitespace added
Browse files7 unmodified lines891011121314151611 unmodified lines282930313233343545 unmodified lines81828384858687888990919241 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715813 unmodified lines17217317417517617717817918018118218318418511 unmodified lines1971981992002012022032046 unmodified lines21121221321421521621721821922022122233 unmodified lines25625725825926026126226326426526626737 unmodified lines30530630730830931019 unmodified lines33033133233333433533656 unmodified lines39339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443542 unmodified lines4784794804817 unmodified lines- 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 osimport jsonimport base64import hashlib11 unmodified linesfrom llava.constants import (IMAGE_TOKEN_INDEX,DEFAULT_IMAGE_TOKEN,DEFAULT_IM_START_TOKEN,DEFAULT_IM_END_TOKEN,)from llava.conversation import conv_templates, SeparatorStylefrom llava.model.builder import load_pretrained_model45 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 =====================41 unmodified linesraise ValueError("Unsupported image input format")def _guess_conv_mode(model_path: str) -> str:name = get_model_name_from_path(model_path).lower()if "llama-2" in name: return "llava_llama_2"if "v1" in name or "pulse" in name: return "llava_v1"if "mpt" in name: return "mpt"if "qwen" in name: return "qwen_1_5"return "llava_v0"def _wrap_image_token_if_needed(model_cfg) -> bool:try:return bool(getattr(model_cfg, "mm_use_im_start_end", False))except Exception:return False# ====== Güvenli Stop Kriteri (demo eşleniği) ======class SafeKeywordsStoppingCriteria(StoppingCriteria):"""LLaVA'nın KeywordsStoppingCriteria'sına karşılık, token bazlıanahtar dizi (separator) eşleşmesi; tensör → bool hatası yok."""def __init__(self, keyword: str, tokenizer):self.tokenizer = tokenizer13 unmodified lines# ===================== 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}"chatbot.conversation.append_message(chatbot.conversation.roles[0], inp)chatbot.conversation.append_message(chatbot.conversation.roles[1], None)prompt = chatbot.conversation.get_prompt()11 unmodified linestop_p: Optional[float] = None,max_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):return {"error": "Required libraries not available (llava/transformers)"}6 unmodified linesif max_new_tokens is None: max_new_tokens = 4096if repetition_penalty is None: repetition_penalty = 1.0 # etkisiz# Chat session: her çağrıda taze templatechatbot = 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()else:chatbot.conversation = conv_templates[chatbot.conv_mode].copy()# Görüntü yükletry:33 unmodified linesexcept 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.sep237 unmodified linesfor piece in streamer:chunks.append(piece)text = "".join(chunks)chatbot.conversation.messages[-1][-1] = textexcept Exception as e:return {"error": f"Generation failed: {e}"}19 unmodified lines# ===================== 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():56 unmodified linesself.model_path = os.getenv("HF_MODEL_ID", "PULSE-ECG/PULSE-7B")self.model_base = Noneself.num_gpus = int(os.getenv("NUM_GPUS", "1"))self.conv_mode = Noneself.max_new_tokens = int(os.getenv("MAX_NEW_TOKENS", "4096"))self.num_frames = 16self.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")))class InferenceDemo:def __init__(self, args, model_path, tokenizer_, model_, image_processor_, context_len_):if not LLAVA_AVAILABLE:raise ImportError("LLaVA not available")disable_torch_init()self.tokenizer, self.model, self.image_processor, self.context_len = (tokenizer_, model_, image_processor_, context_len_)auto = _guess_conv_mode(model_path)self.conv_mode = args.conv_mode if args.conv_mode else autoargs.conv_mode = self.conv_modeself.conversation = conv_templates[self.conv_mode].copy()self.num_frames = args.num_framesclass ChatSessionManager:def __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 = argsself.model_path = model_pathself.chatbot = InferenceDemo(args, model_path, tokenizer, model, image_processor, context_len)def get_chatbot(self, args, model_path, tokenizer, model, image_processor, context_len):self.init_if_needed(args, model_path, tokenizer, model, image_processor, context_len)return self.chatbotchat_manager = ChatSessionManager()def initialize_model():global tokenizer, model, image_processor, context_len, argsif not LLAVA_AVAILABLE:42 unmodified linesreturn get_model_info()if __name__ == "__main__":print("Handler ready (Demo Parity + Style Hint). Use `EndpointHandler` or `query`.")7 unmodified lines8910111213141516171811 unmodified lines30313233343545 unmodified lines8182838485868788899091929341 unmodified lines13513613713813914014114214314414514614714814915015115215315415515615715815916016113 unmodified lines17517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321411 unmodified lines2262272282292302312322336 unmodified lines24024124224324424524624724824933 unmodified lines28328428528628728828929029129237 unmodified lines33033133233333433533619 unmodified lines35635735835936036136256 unmodified lines41942042142242342442542642742842943043142 unmodified lines4744754764777 unmodified lines- 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- Post-process: YALNIZCA whitespace/biçim normalizasyonu (yönetim/öneri cümleleri korunur)"""import osimport reimport jsonimport base64import hashlib11 unmodified linesfrom llava.constants import (IMAGE_TOKEN_INDEX,DEFAULT_IMAGE_TOKEN,)from llava.conversation import conv_templates, SeparatorStylefrom llava.model.builder import load_pretrained_model45 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. ""Use neutral, factual cardiology language. Avoid headings and bullet points. ""Finish with a single final line starting exactly with 'Structured clinical impression:' ""followed by a succinct, comma-separated summary of the key diagnoses.")# ===================== Utilities =====================41 unmodified linesraise ValueError("Unsupported image input format")def _normalize_whitespace(text: str) -> str:"""Gereksiz boşluk/boş satırları toparlar:- Satır başı/sonu boşluklarını siler- Birden çok boşluğu tek boşluğa indirger- 3+ boş satırı 1 boş satıra indirger"""text = text.replace("\r\n", "\n").replace("\r", "\n")lines = [re.sub(r"[ \t]+", " ", ln.strip()) for ln in text.split("\n")]text = "\n".join(lines).strip()text = re.sub(r"\n{3,}", "\n\n", text)return textdef _postprocess_min(text: str) -> str:# Yalnızca whitespace/biçim temizliğireturn _normalize_whitespace(text)# ====== Güvenli Stop Kriteri (conv separator) ======class SafeKeywordsStoppingCriteria(StoppingCriteria):"""conv.sep/sep2 bazlı token eşleşmesi; tensör → bool hatası yok."""def __init__(self, keyword: str, tokenizer):self.tokenizer = tokenizer13 unmodified lines# ===================== Core Generation =====================class InferenceDemo:def __init__(self, args, model_path, tokenizer_, model_, image_processor_, context_len_):if not LLAVA_AVAILABLE:raise ImportError("LLaVA not available")disable_torch_init()self.tokenizer, self.model, self.image_processor, self.context_len = (tokenizer_, model_, image_processor_, context_len_)# Parite için sabit şablonself.conv_mode = "llava_v1"self.conversation = conv_templates[self.conv_mode].copy()self.num_frames = getattr(args, "num_frames", 16)class ChatSessionManager:def __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 = argsself.model_path = model_pathself.chatbot = InferenceDemo(args, model_path, tokenizer, model, image_processor, context_len)def get_chatbot(self, args, model_path, tokenizer, model, image_processor, context_len):self.init_if_needed(args, model_path, tokenizer, model, image_processor, context_len)# Her çağrıda taze template (demo gibi yeni tur)self.chatbot.conversation = conv_templates[self.chatbot.conv_mode].copy()return self.chatbotchat_manager = ChatSessionManager()def _build_prompt_and_ids(chatbot, user_text: str, device: torch.device):# DEMO PARİTE: sarım yok, tek görüntü için tek image tokeninp = f"{DEFAULT_IMAGE_TOKEN}\n{user_text}"chatbot.conversation.append_message(chatbot.conversation.roles[0], inp)chatbot.conversation.append_message(chatbot.conversation.roles[1], None)prompt = chatbot.conversation.get_prompt()11 unmodified linestop_p: Optional[float] = None,max_new_tokens: Optional[int] = None,conv_mode_override: Optional[str] = None,repetition_penalty: Optional[float] = None,det_seed: Optional[int] = None, # None → stokastik (demo gibi)):if not (LLAVA_AVAILABLE and TRANSFORMERS_AVAILABLE):return {"error": "Required libraries not available (llava/transformers)"}6 unmodified linesif max_new_tokens is None: max_new_tokens = 4096if repetition_penalty is None: repetition_penalty = 1.0 # etkisiz# Chat sessionchatbot = 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()# Görüntü yükletry:33 unmodified linesexcept Exception as e:return {"error": f"Image processing failed: {e}"}# STYLE_HINT ekle ve prompt hazırlamsg = (message_text or "").strip()msg = f"{msg}\n\n{STYLE_HINT}"_, input_ids = _build_prompt_and_ids(chatbot, msg, device)# Stop string (conv separator) → güvenli kriterstop_str = chatbot.conversation.sep if chatbot.conversation.sep_style != SeparatorStyle.TWO else chatbot.conversation.sep237 unmodified linesfor piece in streamer:chunks.append(piece)text = "".join(chunks)text = _postprocess_min(text) # yalnızca whitespace/format temizliğichatbot.conversation.messages[-1][-1] = textexcept Exception as e:return {"error": f"Generation failed: {e}"}19 unmodified lines# ===================== Public API =====================def query(payload: dict):"""HF Endpoint entry (demo-like)."""global model_initialized, tokenizer, model, image_processor, context_len, argsif not model_initialized:if not initialize_model():56 unmodified linesself.model_path = os.getenv("HF_MODEL_ID", "PULSE-ECG/PULSE-7B")self.model_base = Noneself.num_gpus = int(os.getenv("NUM_GPUS", "1"))self.conv_mode = "llava_v1" # Parite için sabitself.max_new_tokens = int(os.getenv("MAX_NEW_TOKENS", "4096"))self.num_frames = 16self.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")))def initialize_model():global tokenizer, model, image_processor, context_len, argsif not LLAVA_AVAILABLE:42 unmodified linesreturn get_model_info()if __name__ == "__main__":print("Handler ready (Demo Parity + Style Hint + whitespace post-process). Use `EndpointHandler` or `query`.")
handler.py+69-73