Update handler.py
Browse files1234567891011122 unmodified lines151617181920212223242526272829303132333413 unmodified lines4849505152535415 unmodified lines707172737475767778791 unmodified line818283848586878811 unmodified lines1001011021031041052 unmodified lines10810911011111211320 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042057 unmodified lines2132142152162172182192202212222234 unmodified lines2282292302312322332342352362372382392402412422432442454 unmodified lines2502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852865 unmodified lines2922932942952962972982993003013023033043053063076 unmodified lines3143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443454 unmodified lines3503513523533543553565 unmodified lines3623633643653663673681 unmodified line37037137237337437537637737837938038138238338438538638738820 unmodified lines40941041141241341441514 unmodified lines430431432433434435436# -*- coding: utf-8 -*-"""PULSE ECG Handler - Demo-like sampling + no_stop (hard) + min_new_tokens auto- do_sample=True, temperature/top_p payload'dan- max_new_tokens: payload değeri (kırpma yok)- no_stop=True: stopping_criteria KAPALI + eos_token_id=None- no_stop=True ve min_new_tokens boşsa: otomatik min_new_tokens (uzun yanıt garantisi)- Tek görsel; IM_START/END otomatik; 3D/4D/5D tensör uyumlu- Post-format yok (demo davranışı)"""import os2 unmodified linesimport hashlibimport datetimefrom io import BytesIOimport torchfrom PIL import Imageimport requests# --- Opsiyonel ---try:import cv2CV2_AVAILABLE = Trueexcept Exception:CV2_AVAILABLE = Falseprint("Warning: OpenCV (cv2) not available; video is disabled.")# --- LLaVA ---try:from llava.constants import (IMAGE_TOKEN_INDEX,13 unmodified linesLLAVA_AVAILABLE = Trueexcept Exception as e:LLAVA_AVAILABLE = Falseprint(f"Warning: LLaVA modules not available: {e}")# --- HF Hub (opsiyonel logging) ---try:15 unmodified linesrepo_name = ""LOGDIR = "./logs"VOTEDIR = "./votes"os.makedirs(LOGDIR, exist_ok=True)os.makedirs(VOTEDIR, exist_ok=True)tokenizer = Nonemodel = Noneimage_processor = None1 unmodified lineargs = Nonemodel_initialized = Falsedef _safe_upload(path: str):if api and repo_name and os.path.isfile(path):try:api.upload_file(path_or_fileobj=path,11 unmodified linesreturn pdef load_image_any(image_input):if isinstance(image_input, str):s = image_input.strip()if s.startswith(("http://", "https://")):2 unmodified linesreturn Image.open(BytesIO(r.content)).convert("RGB")if os.path.exists(s):return Image.open(s).convert("RGB")if s.startswith("data:image"):s = s.split(",", 1)[1]raw = base64.b64decode(s)20 unmodified linesdef _build_prompt_and_ids(chatbot, user_text: str, device: torch.device):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()input_ids = tokenizer_image_token(prompt, chatbot.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device)return prompt, input_idsdef _stopping(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: str,image_input,*,max_new_tokens: int = 4096,temperature: float = 0.05,top_p: float = 1.0,repetition_penalty: float = 1.0,conv_mode_override: str | None = None,det_seed: int | None = None,no_stop: bool = False,min_new_tokens: int | None = None, # otomatik atanabilir):if not LLAVA_AVAILABLE:return {"error": "LLaVA modules not available"}if not message_text or image_input is None:return {"error": "Both 'message' and 'image' are required"}chatbot = 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()try:pil_img = load_image_any(image_input)except Exception as e:return {"error": f"Failed to load image: {e}"}# logimg_hash, img_path = "NA", Nonetry:buf = BytesIO(); pil_img.save(buf, format="JPEG"); img_bytes = buf.getvalue()img_hash = hashlib.md5(img_bytes).hexdigest()t = datetime.datetime.now()img_path = os.path.join(LOGDIR, "serve_images", f"{t.year:04d}-{t.month:02d}-{t.day:02d}", f"{img_hash}.jpg")os.makedirs(os.path.dirname(img_path), exist_ok=True)if not os.path.isfile(img_path): pil_img.save(img_path)except Exception as e:print(f"[log] saving image failed: {e}")# görüntü tensörüdevice = next(chatbot.model.parameters()).devicedtype = next(chatbot.model.parameters()).dtypetry:processed = process_images([pil_img], chatbot.image_processor, chatbot.model.config)if isinstance(processed, torch.Tensor):if processed.ndim == 3: image_tensor = processed.unsqueeze(0)elif processed.ndim == 4: image_tensor = processedelif processed.ndim == 5:b,t,c,h,w = processed.shapeimage_tensor = processed.reshape(b*t, c, h, w)else:7 unmodified linesexcept Exception as e:return {"error": f"Image processing failed: {e}"}# prompt & ids_, input_ids = _build_prompt_and_ids(chatbot, message_text, device)stopping = None if no_stop else _stopping(chatbot, input_ids)# deterministik sample (opsiyonel)if det_seed is not None:try:det_seed = int(det_seed)4 unmodified linesexcept Exception:pass# EOS/PADeos_id = tokenizer.eos_token_idpad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else (eos_id if eos_id is not None else 0)# no_stop=True ise eos'a göre durmayı tamamen kapatif no_stop:eos_for_gen = Noneelse:eos_for_gen = eos_idgen_kwargs = dict(inputs=input_ids,images=image_tensor,do_sample=True,temperature=float(temperature),top_p=float(top_p),4 unmodified lineseos_token_id=eos_for_gen,length_penalty=1.0,early_stopping=False,stopping_criteria=None if no_stop else [stopping],)# min_new_tokens otomatik (no_stop=True ve kullanıcı vermediyse)if no_stop and (min_new_tokens is None):try:req = int(max_new_tokens)auto_min = max(300, min(req - 64, 1024)) # 300–1024 bandında güvenliif auto_min > 0:gen_kwargs["min_new_tokens"] = auto_minexcept Exception:passelif min_new_tokens is not None:try:mn = int(min_new_tokens)if mn > 0 and mn <= int(max_new_tokens):gen_kwargs["min_new_tokens"] = mnexcept Exception:pass# generatetry:with torch.no_grad():outputs = chatbot.model.generate(**gen_kwargs)gen = outputs[0][input_ids.shape[1]:]text = tokenizer.decode(gen, skip_special_tokens=True)chatbot.conversation.messages[-1][-1] = textexcept Exception as e:return {"error": f"Generation failed: {e}"}# logtry:row = {"time": datetime.datetime.now().isoformat(),5 unmodified lines}with open(_conv_log_path(), "a", encoding="utf-8") as f:f.write(json.dumps(row, ensure_ascii=False) + "\n")_safe_upload(_conv_log_path()); _safe_upload(img_path or "")except Exception as e:print(f"[log] failed: {e}")return {"status": "success", "response": text, "conversation_id": id(chatbot.conversation)}# -------- 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():6 unmodified linesif not message.strip(): return {"error": "Missing 'message' text"}if image is None: return {"error": "Missing 'image'. Use 'image', 'image_url', or 'img'."}max_new_tokens = int(payload.get("max_output_tokens", payload.get("max_new_tokens", payload.get("max_tokens", 4096))))temperature = float(payload.get("temperature", 0.05))top_p = float(payload.get("top_p", 1.0))repetition_penalty = float(payload.get("repetition_penalty", 1.0))conv_mode_override = payload.get("conv_mode", None)det_seed = payload.get("det_seed", None)if det_seed is not None:try: det_seed = int(det_seed)except Exception: det_seed = Noneno_stop = bool(payload.get("no_stop", False))mnt = payload.get("min_new_tokens", None)if mnt is not None:try: mnt = int(mnt)except Exception: mnt = Nonereturn generate_response(message_text=message,image_input=image,max_new_tokens=max_new_tokens,temperature=temperature,top_p=top_p,repetition_penalty=repetition_penalty,conv_mode_override=conv_mode_override,det_seed=det_seed,no_stop=no_stop,min_new_tokens=mnt,)except Exception as e:return {"error": f"Query failed: {e}"}4 unmodified lines"model_initialized": model_initialized,"cuda_available": torch.cuda.is_available(),"llava_available": LLAVA_AVAILABLE,"cv2_available": CV2_AVAILABLE,}def get_model_info():5 unmodified lines"device": str(next(model.parameters()).device) if model else "Unknown",}# -------- init --------class _Args:def __init__(self):1 unmodified lineself.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 modules not available")disable_torch_init()self.tokenizer, self.model, self.image_processor, self.context_len = (tokenizer, model, image_processor, context_len)conv_mode_auto = _guess_conv_mode(model_path)self.conv_mode = args.conv_mode if args.conv_mode else conv_mode_auto20 unmodified linesdef initialize_model():global tokenizer, model, image_processor, context_len, argsif not LLAVA_AVAILABLE:print("LLaVA not available; cannot init.")return Falsetry:args = _Args()14 unmodified linesprint(f"[init] failed: {e}")return Falseclass EndpointHandler:def __init__(self, model_dir):self.model_dir = model_dirprint(f"EndpointHandler initialized with model_dir: {model_dir}")123456789102 unmodified lines131415161718192021222324252613 unmodified lines404142434445464748495051525315 unmodified lines6970717273747576771 unmodified line7980818283848586878811 unmodified lines1001011021031041051061071081091101112 unmodified lines11411511611711811912020 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262277 unmodified lines2352362372382392402412422432442452462472482492504 unmodified lines2552562572582592602612622632642652662672682694 unmodified lines2742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103115 unmodified lines3173183193203213223233243253263273283293303313326 unmodified lines3393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803814 unmodified lines3863873883893903913925 unmodified lines3983994004014024034041 unmodified line40640740840941041141241341441541641741841942042142242342420 unmodified lines44544644744844945045114 unmodified lines466467468469470471472473474475# -*- coding: utf-8 -*-"""PULSE ECG Handler (demo-like streaming)- TextIteratorStreamer + skip_prompt=True (dilimleme yok; Step 1 korunur)- do_sample=True (demo davranışı), temperature/top_p payload'dan- Opsiyonel: no_stop, custom_stop, no_repeat_ngram_size, min_new_tokens- IM_START/END otomatik; 3D/4D/5D görüntü tensörü uyumlu; device/dtype eşleştirme"""import os2 unmodified linesimport hashlibimport datetimefrom io import BytesIOfrom threading import Threadfrom typing import Optional, Listimport torchfrom PIL import Imageimport requests# --- LLaVA / Transformers ---try:from llava.constants import (IMAGE_TOKEN_INDEX,13 unmodified linesLLAVA_AVAILABLE = Trueexcept Exception as e:LLAVA_AVAILABLE = Falseprint(f"[WARN] LLaVA modules not available: {e}")try:from transformers import TextIteratorStreamerTRANSFORMERS_AVAILABLE = Trueexcept Exception as e:TRANSFORMERS_AVAILABLE = Falseprint(f"[WARN] transformers not available: {e}")# --- HF Hub (opsiyonel logging) ---try:15 unmodified linesrepo_name = ""LOGDIR = "./logs"os.makedirs(LOGDIR, exist_ok=True)# --- Global Model State ---tokenizer = Nonemodel = Noneimage_processor = None1 unmodified lineargs = Nonemodel_initialized = False# ----------------- Utilities -----------------def _safe_upload(path: str):if api and repo_name and path and os.path.isfile(path):try:api.upload_file(path_or_fileobj=path,11 unmodified linesreturn pdef load_image_any(image_input):"""Desteklenen:- URL (http/https)- Yerel dosya yolu- base64 (opsiyonel data URL prefix ile)"""if isinstance(image_input, str):s = image_input.strip()if s.startswith(("http://", "https://")):2 unmodified linesreturn Image.open(BytesIO(r.content)).convert("RGB")if os.path.exists(s):return Image.open(s).convert("RGB")# base64if s.startswith("data:image"):s = s.split(",", 1)[1]raw = base64.b64decode(s)20 unmodified linesdef _build_prompt_and_ids(chatbot, user_text: str, device: torch.device):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}"chatbot.conversation.append_message(chatbot.conversation.roles[0], inp)chatbot.conversation.append_message(chatbot.conversation.roles[1], None)prompt = chatbot.conversation.get_prompt()input_ids = tokenizer_image_token(prompt, chatbot.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(device)return prompt, input_idsdef _stopping_keywords(chatbot, input_ids, extra: Optional[List[str]] = None):conv = chatbot.conversationstop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2keys = [stop_str]if extra:keys.extend([k for k in extra if isinstance(k, str) and k.strip()])return KeywordsStoppingCriteria(keys, chatbot.tokenizer, input_ids)# ----------------- Core Generation -----------------def generate_response(message_text: str,image_input,*,max_new_tokens: int = 1800,min_new_tokens: Optional[int] = None,temperature: float = 0.20,top_p: float = 0.95,repetition_penalty: float = 1.20,no_repeat_ngram_size: Optional[int] = 6,conv_mode_override: Optional[str] = None,det_seed: Optional[int] = None,no_stop: bool = False,custom_stop: Optional[List[str]] = None,):if not (LLAVA_AVAILABLE and TRANSFORMERS_AVAILABLE):return {"error": "Required libraries not available (llava/transformers)"}if not message_text or image_input is None:return {"error": "Both 'message' and 'image' are required"}# Chat session (fresh conv each call, demo-like)chatbot = 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()# Load imagetry:pil_img = load_image_any(image_input)except Exception as e:return {"error": f"Failed to load image: {e}"}# Save image to logs (optional)img_hash, img_path = "NA", Nonetry:buf = BytesIO(); pil_img.save(buf, format="JPEG"); raw = buf.getvalue()img_hash = hashlib.md5(raw).hexdigest()t = datetime.datetime.now()img_path = os.path.join(LOGDIR, "serve_images", f"{t.year:04d}-{t.month:02d}-{t.day:02d}", f"{img_hash}.jpg")os.makedirs(os.path.dirname(img_path), exist_ok=True)if not os.path.isfile(img_path):pil_img.save(img_path)except Exception as e:print(f"[log] saving image failed: {e}")# To device/dtypedevice = next(chatbot.model.parameters()).devicedtype = next(chatbot.model.parameters()).dtype# Preprocess image -> tensor (support 3D/4D/5D)try:processed = process_images([pil_img], chatbot.image_processor, chatbot.model.config)if isinstance(processed, torch.Tensor):if processed.ndim == 3: image_tensor = processed.unsqueeze(0)elif processed.ndim == 4: 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:7 unmodified linesexcept Exception as e:return {"error": f"Image processing failed: {e}"}# Prompt & ids_, input_ids = _build_prompt_and_ids(chatbot, message_text, device)# Stopping criteriastopping = None if no_stop else _stopping_keywords(chatbot, input_ids, custom_stop)eos_id = chatbot.tokenizer.eos_token_idpad_id = chatbot.tokenizer.pad_token_id if chatbot.tokenizer.pad_token_id is not None else (eos_id if eos_id is not None else 0)eos_for_gen = None if no_stop else eos_id# Deterministic sampling (optional)if det_seed is not None:try:det_seed = int(det_seed)4 unmodified linesexcept Exception:pass# Streamer (demo-like, avoids manual slicing)streamer = TextIteratorStreamer(chatbot.tokenizer, skip_prompt=True, skip_special_tokens=True)gen_kwargs = dict(inputs=input_ids,images=image_tensor,streamer=streamer,do_sample=True,temperature=float(temperature),top_p=float(top_p),4 unmodified lineseos_token_id=eos_for_gen,length_penalty=1.0,early_stopping=False,stopping_criteria=None if no_stop else ([stopping] if stopping else None),)if no_repeat_ngram_size:try:n = int(no_repeat_ngram_size)if n > 0:gen_kwargs["no_repeat_ngram_size"] = nexcept Exception:passif min_new_tokens is not None:try:mn = int(min_new_tokens)if 1 <= mn <= int(max_new_tokens):gen_kwargs["min_new_tokens"] = mnexcept Exception:pass# Generate in a background thread; collect streamed tokenstry:t = Thread(target=chatbot.model.generate, kwargs=gen_kwargs)t.start()chunks = []for piece in streamer:chunks.append(piece)text = "".join(chunks)chatbot.conversation.messages[-1][-1] = textexcept Exception as e:return {"error": f"Generation failed: {e}"}# Logtry:row = {"time": datetime.datetime.now().isoformat(),5 unmodified lines}with open(_conv_log_path(), "a", encoding="utf-8") as f:f.write(json.dumps(row, ensure_ascii=False) + "\n")_safe_upload(_conv_log_path()); _safe_upload(img_path or "")except Exception as e:print(f"[log] failed: {e}")return {"status": "success", "response": text, "conversation_id": id(chatbot.conversation)}# ----------------- Public API -----------------def query(payload: dict):"""HF Endpoint entry (demo-like streaming)"""global model_initialized, tokenizer, model, image_processor, context_len, argsif not model_initialized:if not initialize_model():6 unmodified linesif not message.strip(): return {"error": "Missing 'message' text"}if image is None: return {"error": "Missing 'image'. Use 'image', 'image_url', or 'img'."}# Demo-like knobsmax_new_tokens = int(payload.get("max_output_tokens", payload.get("max_new_tokens", payload.get("max_tokens", 1800))))min_new_tokens = payload.get("min_new_tokens", None)if min_new_tokens is not None:try: min_new_tokens = int(min_new_tokens)except Exception: min_new_tokens = Nonetemperature = float(payload.get("temperature", 0.20))top_p = float(payload.get("top_p", 0.95))repetition_penalty = float(payload.get("repetition_penalty", 1.20))no_repeat_ngram = payload.get("no_repeat_ngram_size", 6)try:no_repeat_ngram = int(no_repeat_ngram) if no_repeat_ngram is not None else Noneexcept Exception:no_repeat_ngram = Noneconv_mode_override = payload.get("conv_mode", None)det_seed = payload.get("det_seed", None)if det_seed is not None:try: det_seed = int(det_seed)except Exception: det_seed = Noneno_stop = bool(payload.get("no_stop", False))custom_stop = payload.get("custom_stop", None)return generate_response(message_text=message,image_input=image,max_new_tokens=max_new_tokens,min_new_tokens=min_new_tokens,temperature=temperature,top_p=top_p,repetition_penalty=repetition_penalty,no_repeat_ngram_size=no_repeat_ngram,conv_mode_override=conv_mode_override,det_seed=det_seed,no_stop=no_stop,custom_stop=custom_stop,)except Exception as e:return {"error": f"Query failed: {e}"}4 unmodified lines"model_initialized": model_initialized,"cuda_available": torch.cuda.is_available(),"llava_available": LLAVA_AVAILABLE,"transformers_available": TRANSFORMERS_AVAILABLE,}def get_model_info():5 unmodified lines"device": str(next(model.parameters()).device) if model else "Unknown",}# ----------------- Init & Session -----------------class _Args:def __init__(self):1 unmodified lineself.model_base = Noneself.num_gpus = int(os.getenv("NUM_GPUS", "1"))self.conv_mode = Noneself.max_new_tokens = int(os.getenv("MAX_NEW_TOKENS", "1800"))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 modules not available")disable_torch_init()self.tokenizer, self.model, self.image_processor, self.context_len = (tokenizer_, model_, image_processor_, context_len_)conv_mode_auto = _guess_conv_mode(model_path)self.conv_mode = args.conv_mode if args.conv_mode else conv_mode_auto20 unmodified linesdef initialize_model():global tokenizer, model, image_processor, context_len, argsif not LLAVA_AVAILABLE:print("[init] LLaVA not available; cannot init.")return Falsetry:args = _Args()14 unmodified linesprint(f"[init] failed: {e}")return False# ----------------- HF EndpointHandler -----------------class EndpointHandler:"""Hugging Face Endpoint uyumlu sınıf"""def __init__(self, model_dir):self.model_dir = model_dirprint(f"EndpointHandler initialized with model_dir: {model_dir}")
handler.py+120-81