Update handler.py
Browse files2 unmodified lines3456789108 unmodified lines1920212223242529 unmodified lines5556575859606136 unmodified lines9899100101102103104105106107179 unmodified lines28728828929029129229329429529629729829930030130230330430530630730842 unmodified lines3513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943959 unmodified lines4054064074084094101 unmodified line41241341441541641741841942042158 unmodified lines4804814824834844854864874884898 unmodified lines49849950050150250350471 unmodified lines5765775785795805815825835845855865875885895905915925935945955965975985996006016022 unmodified linesPULSE ECG Handler - Deterministic ECG Analysis Model (app.py uyumlu)- Deterministic (do_sample=False, sabit seed)- Tek görüntü, LLaVA conv_template + <image> token akışı- Model dtype/device ile uyumlu görüntü tensörü- Sağlam URL/base64 işleme, güvenli logging, opsiyonel HF upload"""import os8 unmodified lines# --- Opsiyonel bağımlılıklar ---try:import numpy as np # isteğe bağlı, kullanılabilirexcept Exception:np = None29 unmodified lines# Transformerstry:from transformers import TextIteratorStreamer # kullanılmıyor ama mevcutsa sorun değilTRANSFORMERS_AVAILABLE = Trueexcept Exception:TRANSFORMERS_AVAILABLE = False36 unmodified linesmodel_initialized = False# --- Tutarlılık ayarları ---# Tutarlılık ayarlarıPROMPT_NORMALIZATION = TrueDEFAULT_ECG_PROMPT = "Perform a detailed ECG interpretation of the provided image. Analyze step by step the rhythm, heart rate, cardiac axis, P waves, PR interval, QRS complex morphology and duration, ST segments, T waves, and QT/QTc interval. Highlight any abnormalities, conduction disturbances, or ischemic changes you detect. Conclude with a structured clinical impression of the overall ECG."# ---------- Yardımcılar ----------179 unmodified linesexcept Exception as e:return {"error": f"Failed to clear history: {str(e)}"}# ---------- Cevap üretimi ----------def _build_prompt(chatbot, user_text: str) -> str:# App.py ile aynı: <image> token + kullanıcı metniimage_token = DEFAULT_IMAGE_TOKENinp = image_token + "\n" + user_textchatbot.conversation.append_message(chatbot.conversation.roles[0], inp)chatbot.conversation.append_message(chatbot.conversation.roles[1], None)prompt = chatbot.conversation.get_prompt()return promptdef _stop_criteria_from_conv(chatbot, input_ids):conv = chatbot.conversationstop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2return KeywordsStoppingCriteria([stop_str], chatbot.tokenizer, input_ids)def generate_response(message_text,image_input,max_output_tokens=4096,42 unmodified lines# Model dtype/devicemodel_device = next(chatbot.model.parameters()).devicemodel_dtype = next(chatbot.model.parameters()).dtype# Görüntü tensörü (Tensor/list/tuple + 3D/4D/5D destekli)try:processed = process_images([image], chatbot.image_processor, chatbot.model.config)if isinstance(processed, torch.Tensor):# Olası şekiller: (C,H,W), (B,C,H,W), (B,T,C,H,W)if processed.ndim == 3:# (C,H,W) -> (1,C,H,W)image_tensor = processed.unsqueeze(0)elif processed.ndim == 4:# (B,C,H,W)image_tensor = processedelif processed.ndim == 5:# (B,T,C,H,W) -> (B*T,C,H,W)b, t, c, h, w = processed.shapeimage_tensor = processed.reshape(b * t, c, h, w)else:return {"error": f"Unexpected image tensor shape: {tuple(processed.shape)}"}elif isinstance(processed, (list, tuple)):if len(processed) == 0:return {"error": "Image processing returned empty list"}first = processed[0]if not isinstance(first, torch.Tensor):return {"error": f"Processed image type not tensor: {type(first)}"}# first: (C,H,W) veya (B,C,H,W)image_tensor = first.unsqueeze(0) if first.ndim == 3 else firstelse:return {"error": f"Unsupported processed type: {type(processed)}"}# Cihaz ve dtype eşleimage_tensor = image_tensor.to(device=model_device, dtype=model_dtype)except Exception as e:return {"error": f"Image processing failed: {str(e)}"}# Prompt & tokenizasyonprompt = _build_prompt(chatbot, message_text)input_ids = tokenizer_image_token(9 unmodified linestorch.cuda.manual_seed(42)torch.cuda.manual_seed_all(42)try:with torch.no_grad():outputs = chatbot.model.generate(1 unmodified lineimages=image_tensor,do_sample=False, # deterministikmax_new_tokens=int(max_output_tokens),repetition_penalty=float(repetition_penalty),use_cache=False,pad_token_id=chatbot.tokenizer.eos_token_id,eos_token_id=chatbot.tokenizer.eos_token_id,length_penalty=1.0,early_stopping=False,stopping_criteria=[stopping_criteria],58 unmodified linesor "")# Prompt normalization (ECG + diagnosis içeriyorsa)if PROMPT_NORMALIZATION and "ecg" in message_text.lower():if "concise" in message_text.lower():message_text = "Provide a short, concise clinical summary of the ECG."else:message_text = DEFAULT_ECG_PROMPT8 unmodified lines# Parametrelermax_output_tokens = int(payload.get("max_output_tokens",payload.get("max_new_tokens",payload.get("max_tokens", 2048))))repetition_penalty = float(payload.get("repetition_penalty", 1.0))conv_mode_override = payload.get("conv_mode", None)71 unmodified linesself.model_base = Noneself.num_gpus = int(os.getenv("NUM_GPUS", "1"))self.conv_mode = Noneself.max_new_tokens = int(os.getenv("MAX_NEW_TOKENS", "2048"))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")))args = Args()model_name = get_model_name_from_path(args.model_path)tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit)# Device: accelerate devicemap kullanıyorsa ek .to('cuda') gerekmeztry:_ = next(model.parameters()).deviceexcept Exception:# güvenli taşımaif torch.cuda.is_available():model = model.to(torch.device("cuda"))print("[init] tokenizer/image_processor/context_len ready")return True2 unmodified lines345678910118 unmodified lines2021222324252629 unmodified lines5657585960616236 unmodified lines99100101102103104105106107108109110111112113114115116117118119120121179 unmodified lines30130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133242 unmodified lines3753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104119 unmodified lines4214224234244254264274284294304314324334341 unmodified line43643743843944044144244344444544658 unmodified lines5055065075085095105115125135145155165178 unmodified lines52652752852953053153271 unmodified lines6046056066076086096106116126136146156166176186196206216226236246256266276286296306316326332 unmodified linesPULSE ECG Handler - Deterministic ECG Analysis Model (app.py uyumlu)- Deterministic (do_sample=False, sabit seed)- Tek görüntü, LLaVA conv_template + <image> token akışı- Model dtype/device ile uyumlu görüntü tensörü (3D/4D/5D destekli)- Sağlam URL/base64 işleme, güvenli logging, opsiyonel HF upload- Zorunlu başlık şablonu + min_new_tokens ile tam Step 1–9 çıktısı"""import os8 unmodified lines# --- Opsiyonel bağımlılıklar ---try:import numpy as np # isteğe bağlıexcept Exception:np = None29 unmodified lines# Transformerstry:from transformers import TextIteratorStreamer # mevcutsa sorun değilTRANSFORMERS_AVAILABLE = Trueexcept Exception:TRANSFORMERS_AVAILABLE = False36 unmodified linesmodel_initialized = False# --- Tutarlılık ayarları ---PROMPT_NORMALIZATION = TrueDEFAULT_ECG_PROMPT = ("Perform a detailed ECG interpretation of the provided image. Analyze step by step the rhythm, heart rate, ""cardiac axis, P waves, PR interval, QRS complex morphology and duration, ST segments, T waves, and QT/QTc interval. ""OUTPUT FORMAT (use these exact headings, and include every section even if normal):\n""Step 1: Rhythm Analysis\n""Step 2: Heart Rate Analysis\n""Step 3: Cardiac Axis Analysis\n""Step 4: P Wave Analysis\n""Step 5: PR Interval Analysis\n""Step 6: QRS Complex Analysis\n""Step 7: ST Segment Analysis\n""Step 8: T Wave Analysis\n""Step 9: QT/QTc Interval Analysis\n""Structured Clinical Impression:\n""If a section is normal, write 'Normal' and give a brief justification.")# ---------- Yardımcılar ----------179 unmodified linesexcept Exception as e:return {"error": f"Failed to clear history: {str(e)}"}# ---------- Prompt inşası ----------def _build_prompt(chatbot, user_text: str) -> str:# mm_use_im_start_end konfigürasyonuna göre <image> tokenını sarmalatry:use_wrap = bool(getattr(chatbot.model.config, "mm_use_im_start_end", False))except Exception:use_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}"chatbot.conversation.append_message(chatbot.conversation.roles[0], inp)chatbot.conversation.append_message(chatbot.conversation.roles[1], None)return chatbot.conversation.get_prompt()def _stop_criteria_from_conv(chatbot, input_ids):conv = chatbot.conversationstop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2return KeywordsStoppingCriteria([stop_str], chatbot.tokenizer, input_ids)# ---------- Cevap üretimi ----------def generate_response(message_text,image_input,max_output_tokens=4096,42 unmodified lines# Model dtype/devicemodel_device = next(chatbot.model.parameters()).devicemodel_dtype = next(chatbot.model.parameters()).dtype# Görüntü tensörü (Tensor/list/tuple + 3D/4D/5D destekli)try:processed = 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)else:return {"error": f"Unexpected image tensor shape: {tuple(processed.shape)}"}elif isinstance(processed, (list, tuple)):if len(processed) == 0:return {"error": "Image processing returned empty list"}first = processed[0]if not isinstance(first, torch.Tensor):return {"error": f"Processed image type not tensor: {type(first)}"}image_tensor = first.unsqueeze(0) if first.ndim == 3 else firstelse:return {"error": f"Unsupported processed type: {type(processed)}"}image_tensor = image_tensor.to(device=model_device, dtype=model_dtype)except Exception as e:return {"error": f"Image processing failed: {str(e)}"}# Prompt & tokenizasyonprompt = _build_prompt(chatbot, message_text)input_ids = tokenizer_image_token(9 unmodified linestorch.cuda.manual_seed(42)torch.cuda.manual_seed_all(42)# EOS/PAD güvenli aleos_id = chatbot.tokenizer.eos_token_idif eos_id is None:try:eos_id = chatbot.tokenizer.convert_tokens_to_ids("</s>")except Exception:eos_id = 0 # son çaretry:with torch.no_grad():outputs = chatbot.model.generate(1 unmodified lineimages=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,eos_token_id=eos_id,length_penalty=1.0,early_stopping=False,stopping_criteria=[stopping_criteria],58 unmodified linesor "")# Prompt normalization (ECG içeren tüm isteklerde ayrıntılı şablonu zorla)if PROMPT_NORMALIZATION and "ecg" in message_text.lower():if "concise" in message_text.lower():message_text = ("Provide a short, concise clinical summary of the ECG. ""Still cover rhythm, rate, axis, PR, QRS, ST-T, QT/QTc in brief.")else:message_text = DEFAULT_ECG_PROMPT8 unmodified lines# Parametrelermax_output_tokens = int(payload.get("max_output_tokens",payload.get("max_new_tokens",payload.get("max_tokens", 4096))))repetition_penalty = float(payload.get("repetition_penalty", 1.0))conv_mode_override = payload.get("conv_mode", None)71 unmodified linesself.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")))# args globaline ataglobals()["args"] = Args()model_name = get_model_name_from_path(args.model_path)loaded = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit)globals()["tokenizer"], globals()["model"], globals()["image_processor"], globals()["context_len"] = loaded# Device: accelerate devicemap varsa ek .to('cuda') gerekmeyebilirtry:_ = next(model.parameters()).deviceexcept Exception:if torch.cuda.is_available():model = model.to(torch.device("cuda"))# Deterministik için dropout vb. kapansınmodel.eval()print("[init] tokenizer/image_processor/context_len ready")return True
handler.py+70-39