no stop update
Browse files12345678910117 unmodified lines192021222324251 unmodified line2728293031323322 unmodified lines565758596061626 unmodified lines697071727374757677787980811 unmodified line83848586878889909 unmodified lines1001011021031041051061071081091101111121131141151162 unmodified lines1191201211221231241251261271281291301311321 unmodified line1341351361371381391401411421431441451461472 unmodified lines15015115215315415515615715815916016116216316416516616716815 unmodified lines1841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362373 unmodified lines2412422432442452462472482492502512522532542552562574 unmodified lines2622632642652662672682692702712722732742752761 unmodified line2782792802812822832842852862872882892902912921 unmodified line2942952962972982993003013023033043053063073083093103113125 unmodified lines3183193203213223233243253263273283293303313323333343353363372 unmodified lines34034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537628 unmodified lines40540640740840941041116 unmodified lines42842943043143243343443543643743814 unmodified lines4534544554564574584594 unmodified lines4644654664674684694704714724734744754764771 unmodified line479480481482483484485486487488# -*- coding: utf-8 -*-"""PULSE ECG Handler - Demo-like (sampling) + no_stop bayrağı- Demo davranışı: do_sample=True, temperature/top_p payload'dan- max_new_tokens: payload/slider değeri (KIRPMA YOK, direkt kullanılır)- İsteğe bağlı: no_stop=True ile stopping_criteria devre dışı- Tek görsel işleme; IM_START/END otomatik; 3D/4D/5D tensör uyumlu- Çıktıya post-format/deduplicate UYGULANMAZ (demo ile bire bir)"""import os7 unmodified linesfrom PIL import Imageimport requests# --- Opsiyonel bağımlılıklar ---try:import cv2CV2_AVAILABLE = True1 unmodified lineCV2_AVAILABLE = Falseprint("Warning: OpenCV (cv2) not available; video is disabled.")# --- LLaVA / Transformers ---try:from llava.constants import (IMAGE_TOKEN_INDEX,22 unmodified linesexcept Exception:HF_HUB_AVAILABLE = False# ------------- HF Hub init (opsiyonel) -------------api = Nonerepo_name = ""if HF_HUB_AVAILABLE and "HF_TOKEN" in os.environ:6 unmodified linesapi = Nonerepo_name = ""# ------------- Klasörler -------------LOGDIR = "./logs"VOTEDIR = "./votes"os.makedirs(LOGDIR, exist_ok=True)os.makedirs(VOTEDIR, exist_ok=True)# ------------- Global durum -------------tokenizer = Nonemodel = Noneimage_processor = None1 unmodified lineargs = Nonemodel_initialized = False# ------------- Yardımcılar -------------def _safe_upload(path: str):if api and repo_name and os.path.isfile(path):try:9 unmodified linesdef _conv_log_path():t = datetime.datetime.now()p = os.path.join(LOGDIR, f"{t.year:04d}-{t.month:02d}-{t.day:02d}-user_conv.json")os.makedirs(os.path.dirname(p), exist_ok=True)return pdef load_image_any(image_input):"""Desteklenen formatlar:- 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]try:raw = base64.b64decode(s)return Image.open(BytesIO(raw)).convert("RGB")except Exception as e:raise ValueError(f"Invalid image string (not URL/path/base64): {e}")elif isinstance(image_input, dict) and "image" in image_input:return load_image_any(image_input["image"])else:1 unmodified linedef _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:2 unmodified linesexcept Exception:return False# ------------- Çekirdek üretim -------------def _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)15 unmodified linesconv_mode_override: str | None = None,det_seed: int | None = None,no_stop: bool = False,min_new_tokens: int | None = None, # opsiyonel, uzunluğu zorlamak istersen):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/konuşma hazırla (her çağrıda sıfırdan, demo gibi)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()# Görüntüyü yükletry:pil_img = load_image_any(image_input)except Exception as e:return {"error": f"Failed to load image: {e}"}# Log için kaydetimg_hash = "NA"img_path = 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üyü tensöre çevirdevice = 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: # (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:3 unmodified linesimage_tensor = first.unsqueeze(0) if isinstance(first, torch.Tensor) and first.ndim == 3 else firstelse:return {"error": "Image processing returned empty"}# Demo tarafında half + to(device) kalıbı yaygınimage_tensor = image_tensor.to(device=device, dtype=dtype)except Exception as e:return {"error": f"Image processing failed: {e}"}# Prompt & tokenizasyonprompt, input_ids = _build_prompt_and_ids(chatbot, message_text, device)stopping = None if no_stop else _stopping(chatbot, input_ids)# (opsiyonel) deterministik samplingif det_seed is not None:try:det_seed = int(det_seed)4 unmodified linesexcept Exception:pass# 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# generate kwargs (demo-like)gen_kwargs = dict(inputs=input_ids,images=image_tensor,1 unmodified linetemperature=float(temperature),top_p=float(top_p),repetition_penalty=float(repetition_penalty),max_new_tokens=int(max_new_tokens), # KIRPMA YOKuse_cache=False,pad_token_id=eos_id,eos_token_id=eos_id,length_penalty=1.0,early_stopping=False,stopping_criteria=None if no_stop else [stopping],)if min_new_tokens is not None:try:mn = int(min_new_tokens)if mn > 0 and mn <= int(max_new_tokens):1 unmodified lineexcept Exception:pass# Üretimtry:with torch.no_grad():outputs = chatbot.model.generate(**gen_kwargs)gen = outputs[0][input_ids.shape[1]:]text = chatbot.tokenizer.decode(gen, skip_special_tokens=True)# Konuşmaya yerleştir (demo gibi)chatbot.conversation.messages[-1][-1] = textexcept Exception as e:return {"error": f"Generation failed: {e}"}# Log yaztry: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())if img_path:_safe_upload(img_path)except Exception as e:print(f"[log] failed: {e}")return {"status": "success", "response": text, "conversation_id": id(chatbot.conversation)}# ------------- API Yüzeyi -------------def query(payload: dict):"""HF Endpoint ana giriş noktası (demo uyumlu)"""global model_initialized, tokenizer, model, image_processor, context_len, argsif not model_initialized:if not initialize_model():return {"error": "Model initialization failed"}2 unmodified linestry:message = payload.get("message") or payload.get("query") or payload.get("prompt") or payload.get("istem") or ""image = payload.get("image") or payload.get("image_url") or payload.get("img") or Noneif not message.strip():return {"error": "Missing 'message' text"}if image is None:return {"error": "Missing 'image'. Use 'image', 'image_url', or 'img'."}# Demo: slider benzeri parametrelermax_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)# (Opsiyonel) deterministik sample için seeddet_seed = payload.get("det_seed", None)if det_seed is not None:try:det_seed = int(det_seed)except Exception:det_seed = None# (Yeni) stopping_criteria kapatma bayrağıno_stop = bool(payload.get("no_stop", False))# (Opsiyonel) min_new_tokensmnt = payload.get("min_new_tokens", None)if mnt is not None:try:mnt = int(mnt)except Exception:mnt = Nonereturn generate_response(message_text=message,28 unmodified lines"device": str(next(model.parameters()).device) if model else "Unknown",}# ------------- Model init -------------class _Args:def __init__(self):16 unmodified linestokenizer, model, image_processor, context_len)conv_mode_auto = _guess_conv_mode(model_path)if args.conv_mode and args.conv_mode != conv_mode_auto:self.conv_mode = args.conv_modeelse:self.conv_mode = conv_mode_autoargs.conv_mode = conv_mode_autoself.conversation = conv_templates[self.conv_mode].copy()self.num_frames = args.num_frames14 unmodified lineschat_manager = ChatSessionManager()def initialize_model():"""Modeli yükle (lazy)"""global tokenizer, model, image_processor, context_len, argsif not LLAVA_AVAILABLE:print("LLaVA not available; cannot init.")4 unmodified linestokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit)# Cihaztry:_ = next(model.parameters()).deviceexcept Exception:if torch.cuda.is_available():model = model.to(torch.device("cuda"))model.eval()# Chatbot initchat_manager.init_if_needed(args, args.model_path, tokenizer, model, image_processor, context_len)print("[init] model/tokenizer/image_processor loaded.")return True1 unmodified lineprint(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}")1234567891011127 unmodified lines202122232425261 unmodified line2829303132333422 unmodified lines5758596061626 unmodified lines69707172737475767778791 unmodified line8182838485869 unmodified lines969798991001011021031041052 unmodified lines1081091101111121131141151161171 unmodified line1191201211221231241251261271282 unmodified lines13113213313413513613713813914014114214314414515 unmodified lines1611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042053 unmodified lines2092102112122132142152162172182192202212222234 unmodified lines2282292302312322332342352362372382392402412421 unmodified line2442452462472482492502512522532542552562572582592602612622632642652662672681 unmodified line2702712722732742752762772782792802812822832842852865 unmodified lines2922932942952962972982993003013023033043053063073082 unmodified lines31131231331431531631731831932032132232332432532632732832933033133233328 unmodified lines36236336436536636736816 unmodified lines38538638738838939039139214 unmodified lines4074084094104114124 unmodified lines4174184194204214224234244254264274281 unmodified line430431432433434435436# -*- 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 os7 unmodified linesfrom PIL import Imageimport requests# --- Opsiyonel ---try:import cv2CV2_AVAILABLE = True1 unmodified lineCV2_AVAILABLE = Falseprint("Warning: OpenCV (cv2) not available; video is disabled.")# --- LLaVA ---try:from llava.constants import (IMAGE_TOKEN_INDEX,22 unmodified linesexcept Exception:HF_HUB_AVAILABLE = Falseapi = Nonerepo_name = ""if HF_HUB_AVAILABLE and "HF_TOKEN" in os.environ:6 unmodified linesapi = Nonerepo_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:9 unmodified linesdef _conv_log_path():t = datetime.datetime.now()p = os.path.join(LOGDIR, f"{t.year:04d}-{t.month:02d}-{t.day:02d}-user_conv.json")os.makedirs(os.path.dirname(p), exist_ok=True)return 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)return Image.open(BytesIO(raw)).convert("RGB")elif isinstance(image_input, dict) and "image" in image_input:return load_image_any(image_input["image"])else:1 unmodified linedef _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:2 unmodified linesexcept Exception:return Falsedef _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)15 unmodified linesconv_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:3 unmodified linesimage_tensor = first.unsqueeze(0) if isinstance(first, torch.Tensor) and first.ndim == 3 else firstelse:return {"error": "Image processing returned empty"}image_tensor = image_tensor.to(device=device, dtype=dtype)except 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,1 unmodified linetemperature=float(temperature),top_p=float(top_p),repetition_penalty=float(repetition_penalty),max_new_tokens=int(max_new_tokens),use_cache=False,pad_token_id=pad_id,eos_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):1 unmodified lineexcept 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():return {"error": "Model initialization failed"}2 unmodified linestry:message = payload.get("message") or payload.get("query") or payload.get("prompt") or payload.get("istem") or ""image = payload.get("image") or payload.get("image_url") or payload.get("img") or Noneif 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,28 unmodified lines"device": str(next(model.parameters()).device) if model else "Unknown",}# -------- init --------class _Args:def __init__(self):16 unmodified linestokenizer, 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_autoargs.conv_mode = self.conv_modeself.conversation = conv_templates[self.conv_mode].copy()self.num_frames = args.num_frames14 unmodified lineschat_manager = ChatSessionManager()def initialize_model():global tokenizer, model, image_processor, context_len, argsif not LLAVA_AVAILABLE:print("LLaVA not available; cannot init.")4 unmodified linestokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit)try:_ = next(model.parameters()).deviceexcept Exception:if torch.cuda.is_available():model = model.to(torch.device("cuda"))model.eval()chat_manager.init_if_needed(args, args.model_path, tokenizer, model, image_processor, context_len)print("[init] model/tokenizer/image_processor loaded.")return True1 unmodified lineprint(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}")
handler.py+68-120