Update handler.py
#35
by ismailhakki37 - opened
1235 unmodified lines91011121314151 unmodified line1718192021222317 unmodified lines4142434445464748495051525354551 unmodified line575859606162637 unmodified lines7172737475767778798081828384858687888990916 unmodified lines98991001011021031041051061071081091104 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062075 unmodified lines2132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804816 unmodified lines4884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815821 unmodified line5845855865875885895905915925935945955965975985996006011 unmodified line603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639import osimport datetimeimport torch5 unmodified linesfrom PIL import Imagefrom io import BytesIO# Try to import cv2, but make it optionaltry:import cv2CV2_AVAILABLE = True1 unmodified lineCV2_AVAILABLE = Falseprint("Warning: cv2 (OpenCV) not available. Video processing will be disabled.")# Try to import llava modules, but make them optionaltry:from llava import conversation as conversation_libfrom llava.constants import DEFAULT_IMAGE_TOKEN17 unmodified linesLLAVA_AVAILABLE = Falseprint(f"Warning: LLaVA modules not available: {e}")# Try to import transformerstry:from transformers import TextStreamer, TextIteratorStreamerTRANSFORMERS_AVAILABLE = Trueexcept ImportError:TRANSFORMERS_AVAILABLE = Falseprint("Warning: Transformers not available")# Try to import huggingface_hubtry:from huggingface_hub import HfApi, loginHF_HUB_AVAILABLE = True1 unmodified lineHF_HUB_AVAILABLE = Falseprint("Warning: Hugging Face Hub not available")# Initialize Hugging Face APIif HF_HUB_AVAILABLE and "HF_TOKEN" in os.environ:try:login(token=os.environ["HF_TOKEN"], write_permission=True)7 unmodified linesapi = Nonerepo_name = ""external_log_dir = "./logs"LOGDIR = external_log_dirVOTEDIR = "./votes"# Global variables for model and tokenizertokenizer = Nonemodel = Noneimage_processor = Nonecontext_len = Noneargs = Nonedef get_conv_log_filename():t = datetime.datetime.now()name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-user_conv.json")return namedef get_conv_vote_filename():t = datetime.datetime.now()6 unmodified linesif api and repo_name:try:with open(get_conv_vote_filename(), "a") as fout:data = {"type": vote_type,"model": model_selector,"state": state,}fout.write(json.dumps(data) + "\n")api.upload_file(path_or_fileobj=get_conv_vote_filename(),path_in_repo=get_conv_vote_filename().replace("./votes/", ""),4 unmodified linesdef is_valid_video_filename(name):if not CV2_AVAILABLE:return False # Video processing disabledvideo_extensions = ["avi", "mp4", "mov", "mkv", "flv", "wmv", "mjpeg"]ext = name.split(".")[-1].lower()return ext in video_extensionsdef is_valid_image_filename(name):image_extensions = ["jpg", "jpeg", "png", "bmp", "gif", "tiff", "webp", "heic", "heif", "jfif", "svg", "eps", "raw"]ext = name.split(".")[-1].lower()return ext in image_extensionsdef sample_frames(video_file, num_frames):if not CV2_AVAILABLE:raise ImportError("cv2 (OpenCV) not available. Video processing is disabled.")video = cv2.VideoCapture(video_file)total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))interval = total_frames // num_framesframes = []for i in range(total_frames):ret, frame = video.read()if not ret:continueif i % interval == 0:pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))frames.append(pil_img)video.release()return framesdef load_image(image_file):if image_file.startswith("http") or image_file.startswith("https"):response = requests.get(image_file)if response.status_code == 200:image = Image.open(BytesIO(response.content)).convert("RGB")else:raise ValueError("Failed to load image from URL")else:print("Load image from local file")print(image_file)image = Image.open(image_file).convert("RGB")return imagedef process_base64_image(base64_string):"""Process base64 encoded image string"""try:# Remove data URL prefix if presentif base64_string.startswith('data:image'):base64_string = base64_string.split(',')[1]# Decode base64 to bytesimage_data = base64.b64decode(base64_string)# Convert to PIL Imageimage = Image.open(BytesIO(image_data)).convert("RGB")return imageexcept Exception as e:raise ValueError(f"Failed to process base64 image: {e}")def process_image_input(image_input):"""Process different types of image input (file path, URL, or base64)"""if isinstance(image_input, str):if image_input.startswith("http"):return load_image(image_input)elif os.path.exists(image_input):return load_image(image_input)else:# Try to process as base64return process_base64_image(image_input)elif isinstance(image_input, dict) and "image" in image_input:# Handle base64 image from dictreturn process_base64_image(image_input["image"])else:raise ValueError("Unsupported image input format")class InferenceDemo(object):def __init__(self, args, model_path, tokenizer, model, image_processor, context_len) -> None: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,)model_name = get_model_name_from_path(model_path)if "llama-2" in model_name.lower():conv_mode = "llava_llama_2"5 unmodified linesconv_mode = "qwen_1_5"else:conv_mode = "llava_v0"if args.conv_mode is not None and conv_mode != args.conv_mode:print("[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}".format(conv_mode, args.conv_mode, args.conv_mode))else:args.conv_mode = conv_modeself.conv_mode = conv_modeself.conversation = conv_templates[args.conv_mode].copy()self.num_frames = args.num_framesclass ChatSessionManager:def __init__(self):self.chatbot_instance = Nonedef initialize_chatbot(self, args, model_path, tokenizer, model, image_processor, context_len):self.chatbot_instance = InferenceDemo(args, model_path, tokenizer, model, image_processor, context_len)print(f"Initialized Chatbot instance with ID: {id(self.chatbot_instance)}")def reset_chatbot(self):self.chatbot_instance = Nonedef get_chatbot(self, args, model_path, tokenizer, model, image_processor, context_len):if self.chatbot_instance is None:self.initialize_chatbot(args, model_path, tokenizer, model, image_processor, context_len)2 unmodified lineschat_manager = ChatSessionManager()def clear_history():"""Clear conversation history"""if not LLAVA_AVAILABLE:return {"error": "LLaVA modules not available"}try:chatbot_instance = chat_manager.get_chatbot(args, args.model_path if args else "PULSE-ECG/PULSE-7B", tokenizer, model, image_processor, context_len)try:if hasattr(chatbot_instance, 'conv_mode') and chatbot_instance.conv_mode and LLAVA_AVAILABLE:chatbot_instance.conversation = conv_templates[chatbot_instance.conv_mode].copy()else:# Use default conversation templatechatbot_instance.conversation = chatbot_instance.conversation.__class__()except Exception as e:print(f"[DEBUG] Failed to reset conversation in clear_history: {e}")return {"status": "success", "message": "Conversation history cleared"}except Exception as e:return {"error": f"Failed to clear history: {str(e)}"}def add_message(message_text, image_input=None):"""Add a message to the conversation"""return {"status": "success", "message": "Message added"}def generate_response(message_text, image_input, temperature=0.05, top_p=1.0, max_output_tokens=4096, repetition_penalty=1.0, conv_mode_override=None):"""Generate response for the given message and image"""if not LLAVA_AVAILABLE:return {"error": "LLaVA modules not available"}try:if not message_text or not image_input:return {"error": "Both message text and image are required"}our_chatbot = chat_manager.get_chatbot(args, args.model_path if args else "PULSE-ECG/PULSE-7B", tokenizer, model, image_processor, context_len)# Process image inputtry:image = process_image_input(image_input)except Exception as e:return {"error": f"Failed to process image: {str(e)}"}# Save image for loggingall_image_hash = []all_image_path = []# Generate hash for the imageimg_byte_arr = BytesIO()image.save(img_byte_arr, format='JPEG')img_byte_arr = img_byte_arr.getvalue()image_hash = hashlib.md5(img_byte_arr).hexdigest()all_image_hash.append(image_hash)# Save image to logst = datetime.datetime.now()filename = os.path.join(LOGDIR,"serve_images",f"{t.year}-{t.month:02d}-{t.day:02d}",f"{image_hash}.jpg",)all_image_path.append(filename)if not os.path.isfile(filename):os.makedirs(os.path.dirname(filename), exist_ok=True)print("image save to", filename)image.save(filename)# Process image for modeltry:print(f"[DEBUG] Processing image for model...")processed_images = process_images([image], our_chatbot.image_processor, our_chatbot.model.config)print(f"[DEBUG] Processed images length: {len(processed_images)}")if len(processed_images) == 0:return {"error": "Image processing returned empty list"}image_tensor = processed_images[0]image_tensor = image_tensor.half().to(our_chatbot.model.device)image_tensor = image_tensor.unsqueeze(0)print(f"[DEBUG] Image tensor shape: {image_tensor.shape}")except Exception as e:print(f"[DEBUG] Image processing error: {str(e)}")return {"error": f"Image processing failed: {str(e)}"}# Prepare conversation - reset for each request to avoid history issuestry:if hasattr(our_chatbot, 'conv_mode') and our_chatbot.conv_mode and LLAVA_AVAILABLE:our_chatbot.conversation = conv_templates[our_chatbot.conv_mode].copy()else:# Use default conversation templateour_chatbot.conversation = our_chatbot.conversation.__class__()except Exception as e:print(f"[DEBUG] Failed to reset conversation: {e}")# Continue with existing conversationinp = DEFAULT_IMAGE_TOKEN + "\n" + message_textour_chatbot.conversation.append_message(our_chatbot.conversation.roles[0], inp)our_chatbot.conversation.append_message(our_chatbot.conversation.roles[1], None)prompt = our_chatbot.conversation.get_prompt()# Tokenize inputinput_ids = tokenizer_image_token(prompt, our_chatbot.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(our_chatbot.model.device)# No stopping criteria - let model generate freely up to max_new_tokensprint(f"[DEBUG] No stopping criteria - free generation up to {max_output_tokens} tokens")stopping_criteria = None# Generate responsewith torch.no_grad():outputs = our_chatbot.model.generate(inputs=input_ids,images=image_tensor,do_sample=False,temperature=temperature,top_p=top_p,max_new_tokens=max_output_tokens,repetition_penalty=repetition_penalty,use_cache=False,pad_token_id=our_chatbot.tokenizer.eos_token_id,eos_token_id=our_chatbot.tokenizer.eos_token_id,length_penalty=1.0, # Don't penalize longer sequences)# Decode responsetry:print(f"[DEBUG] Outputs shape: {outputs.shape if hasattr(outputs, 'shape') else 'No shape attr'}")print(f"[DEBUG] Outputs length: {len(outputs) if hasattr(outputs, '__len__') else 'No length'}")print(f"[DEBUG] Input IDs shape: {input_ids.shape}")if len(outputs) == 0:return {"error": "Model generated empty output"}response = our_chatbot.tokenizer.decode(outputs[0][input_ids.shape[1]:], skip_special_tokens=True)print(f"[DEBUG] Conversation messages length: {len(our_chatbot.conversation.messages)}")if len(our_chatbot.conversation.messages) > 0:last_message = our_chatbot.conversation.messages[-1]print(f"[DEBUG] Last message: {last_message}")if isinstance(last_message, list) and len(last_message) > 1:our_chatbot.conversation.messages[-1][-1] = responseprint(f"[DEBUG] Response added to conversation")else:print(f"[DEBUG] Last message format unexpected: {last_message}")# Add response as new message if format is wrongour_chatbot.conversation.append_message(our_chatbot.conversation.roles[1], response)else:print("[DEBUG] No conversation messages found")# Add response as new messageour_chatbot.conversation.append_message(our_chatbot.conversation.roles[1], response)print(f"[DEBUG] Generated response length: {len(response)}")except Exception as e:print(f"[DEBUG] Response decoding error: {str(e)}")return {"error": f"Response decoding failed: {str(e)}"}# Log conversationhistory = [(message_text, response)]with open(get_conv_log_filename(), "a") as fout:data = {"type": "chat","model": "PULSE-7b","state": history,"images": all_image_hash,"images_path": all_image_path}print("#### conv log", data)fout.write(json.dumps(data) + "\n")# Upload files to Hugging Face if configuredif api and repo_name:try:for upload_img in all_image_path:api.upload_file(path_or_fileobj=upload_img,path_in_repo=upload_img.replace("./logs/", ""),repo_id=repo_name,repo_type="dataset",)# Upload conversation logapi.upload_file(path_or_fileobj=get_conv_log_filename(),path_in_repo=get_conv_log_filename().replace("./logs/", ""),repo_id=repo_name,repo_type="dataset")except Exception as e:print(f"Failed to upload files: {e}")return {"status": "success","response": response,"conversation_id": id(our_chatbot.conversation)}except Exception as e:return {"error": f"Generation failed: {str(e)}"}def upvote_last_response(conversation_id):"""Upvote the last response"""try:vote_last_response({"conversation_id": conversation_id}, "upvote", "PULSE-7B")return {"status": "success", "message": "Thank you for your voting!"}except Exception as e:return {"error": f"Failed to upvote: {str(e)}"}def downvote_last_response(conversation_id):"""Downvote the last response"""try:vote_last_response({"conversation_id": conversation_id}, "downvote", "PULSE-7B")return {"status": "success", "message": "Thank you for your voting!"}except Exception as e:return {"error": f"Failed to downvote: {str(e)}"}def flag_response(conversation_id):"""Flag the last response"""try:vote_last_response({"conversation_id": conversation_id}, "flag", "PULSE-7B")return {"status": "success", "message": "Response flagged successfully"}except Exception as e:return {"error": f"Failed to flag response: {str(e)}"}# Initialize model when module is importeddef initialize_model():"""Initialize the model and tokenizer"""global tokenizer, model, image_processor, context_len, argsif not LLAVA_AVAILABLE:print("LLaVA modules not available, skipping model initialization")return Falsetry:# Set default argumentsclass Args:def __init__(self):self.model_path = "PULSE-ECG/PULSE-7B"6 unmodified linesself.load_8bit = Falseself.load_4bit = Falseself.debug = Falseargs = Args()# Load modelmodel_path = args.model_pathmodel_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)print("### image_processor", image_processor)print("### tokenizer", tokenizer)# Move model to GPU if availableif torch.cuda.is_available():model = model.to(torch.device('cuda'))print("Model moved to CUDA")else:print("CUDA not available, using CPU")return Trueexcept Exception as e:print(f"Failed to initialize model: {e}")return False# Don't initialize model on import - do it lazilymodel_initialized = False# Main endpoint function for Hugging Facedef query(payload):"""Main endpoint function for Hugging Face inference API"""global model_initialized# Lazy initialization - initialize model on first callif not model_initialized:print("Initializing model on first query...")model_initialized = initialize_model()if not model_initialized:return {"error": "Model initialization failed"}try:print(f"[DEBUG] query payload keys={list(payload.keys()) if hasattr(payload,'keys') else 'N/A'}")# Extract prompt with multiple possible keysmessage_text = (payload.get("message") orpayload.get("query") orpayload.get("prompt") orpayload.get("istem") or "")# Extract image with multiple possible keysimage_input = (payload.get("image") orpayload.get("image_url") orpayload.get("img") or None)# Extract generation parameters with fallbackstemperature = float(payload.get("temperature", 0.05))top_p = float(payload.get("top_p", 1.0))max_output_tokens = int(payload.get("max_output_tokens",payload.get("max_new_tokens",payload.get("max_tokens", 8192))))repetition_penalty = float(payload.get("repetition_penalty", 1.0))conv_mode_override = payload.get("conv_mode", None)if not message_text or not message_text.strip():return {"error": "Missing prompt text. Use 'message', 'query', 'prompt', or 'istem' key"}if not image_input:return {"error": "Missing image. Use 'image', 'image_url', or 'img' key"}# Generate response with all parametersresult = generate_response(message_text=message_text,image_input=image_input,temperature=temperature,top_p=top_p,max_output_tokens=max_output_tokens,repetition_penalty=repetition_penalty,conv_mode_override=conv_mode_override)return resultexcept Exception as e:return {"error": f"Query failed: {str(e)}"}# Additional utility endpointsdef health_check():"""Health check endpoint"""return {"status": "healthy","model_initialized": model_initialized,1 unmodified line"llava_available": LLAVA_AVAILABLE,"transformers_available": TRANSFORMERS_AVAILABLE,"cv2_available": CV2_AVAILABLE,"lazy_loading": True # Model will be loaded on first query}def get_model_info():"""Get model information"""if not model_initialized:return {"error": "Model not initialized yet","lazy_loading": True,"note": "Model will be loaded on first query"}return {"model_path": args.model_path if args else "Unknown","model_type": "PULSE-7B",1 unmodified line"device": str(model.device) if model else "Unknown"}# Hugging Face EndpointHandler classclass EndpointHandler:"""Hugging Face endpoint handler class"""def __init__(self, model_dir):"""Initialize the endpoint handler"""self.model_dir = model_dirprint(f"EndpointHandler initialized with model_dir: {model_dir}")def __call__(self, payload):"""Main endpoint function - handles Hugging Face payload format"""# Hugging Face sends payload in "inputs" wrapperif "inputs" in payload:# Extract the actual payload from inputs wrapperactual_payload = payload["inputs"]return query(actual_payload)else:# Direct payload (for backward compatibility)return query(payload)def health_check(self):"""Health check endpoint"""return health_check()def get_model_info(self):"""Get model information"""return get_model_info()# For backward compatibility and testingif __name__ == "__main__":print("Handler module loaded successfully!")print("This handler is now ready for Hugging Face endpoints.")print("Use the 'query' function as the main endpoint.")print("Or use EndpointHandler class for Hugging Face compatibility.")1234565 unmodified lines121314151617181 unmodified line2021222324252617 unmodified lines4445464748495051525354555657581 unmodified line606162636465667 unmodified lines74757677787980818283848586878889909192939495966 unmodified lines1031041051061071081094 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601615 unmodified lines1671681691701711721731741751761771781791801811821831841851861871882 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853866 unmodified lines3933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844851 unmodified line4874884894904914924934944954964974981 unmodified line500501502503504505506507508509510511512513514515516517518# -*- coding: utf-8 -*-# handler.py — PULSE-7B / LLaVA endpoint (robust + deterministic-ready)import osimport datetimeimport torch5 unmodified linesfrom PIL import Imagefrom io import BytesIO# Optional cv2try:import cv2CV2_AVAILABLE = True1 unmodified lineCV2_AVAILABLE = Falseprint("Warning: cv2 (OpenCV) not available. Video processing will be disabled.")# LLaVA stacktry:from llava import conversation as conversation_libfrom llava.constants import DEFAULT_IMAGE_TOKEN17 unmodified linesLLAVA_AVAILABLE = Falseprint(f"Warning: LLaVA modules not available: {e}")# Transformerstry:from transformers import GenerationConfigTRANSFORMERS_AVAILABLE = Trueexcept ImportError:TRANSFORMERS_AVAILABLE = Falseprint("Warning: Transformers not available")# HF Hub (optional)try:from huggingface_hub import HfApi, loginHF_HUB_AVAILABLE = True1 unmodified lineHF_HUB_AVAILABLE = Falseprint("Warning: Hugging Face Hub not available")# HF Hub init (optional)if HF_HUB_AVAILABLE and "HF_TOKEN" in os.environ:try:login(token=os.environ["HF_TOKEN"], write_permission=True)7 unmodified linesapi = Nonerepo_name = ""# Logsexternal_log_dir = "./logs"LOGDIR = external_log_dirVOTEDIR = "./votes"# Globalstokenizer = Nonemodel = Noneimage_processor = Nonecontext_len = Noneargs = Nonemodel_initialized = False# ----- Utils -----def get_conv_log_filename():t = datetime.datetime.now()return os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-user_conv.json")def get_conv_vote_filename():t = datetime.datetime.now()6 unmodified linesif api and repo_name:try:with open(get_conv_vote_filename(), "a") as fout:fout.write(json.dumps({"type": vote_type, "model": model_selector, "state": state}) + "\n")api.upload_file(path_or_fileobj=get_conv_vote_filename(),path_in_repo=get_conv_vote_filename().replace("./votes/", ""),4 unmodified linesdef is_valid_video_filename(name):if not CV2_AVAILABLE:return Falsereturn name.split(".")[-1].lower() in ["avi", "mp4", "mov", "mkv", "flv", "wmv", "mjpeg"]def is_valid_image_filename(name):return name.split(".")[-1].lower() in ["jpg","jpeg","png","bmp","gif","tiff","webp","heic","heif","jfif","svg","eps","raw"]def load_image(image_file):if image_file.startswith("http"):r = requests.get(image_file)if r.status_code == 200:return Image.open(BytesIO(r.content)).convert("RGB")raise ValueError("Failed to load image from URL")return Image.open(image_file).convert("RGB")def process_base64_image(base64_string):if base64_string.startswith('data:image'):base64_string = base64_string.split(',')[1]image_data = base64.b64decode(base64_string)return Image.open(BytesIO(image_data)).convert("RGB")def process_image_input(image_input):if isinstance(image_input, str):if image_input.startswith("http"):return load_image(image_input)elif os.path.exists(image_input):return load_image(image_input)else:return process_base64_image(image_input)elif isinstance(image_input, dict) and "image" in image_input:return process_base64_image(image_input["image"])else:raise ValueError("Unsupported image input format")# ----- Chat session -----class InferenceDemo(object):def __init__(self, args, model_path, tokenizer, model, image_processor, context_len) -> None: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)model_name = get_model_name_from_path(model_path)if "llama-2" in model_name.lower():conv_mode = "llava_llama_2"5 unmodified linesconv_mode = "qwen_1_5"else:conv_mode = "llava_v0"if args.conv_mode is not None and conv_mode != args.conv_mode:print(f"[WARNING] auto inferred conv_mode={conv_mode}, using {args.conv_mode}")else:args.conv_mode = conv_modeself.conv_mode = args.conv_modeself.conversation = conv_templates[self.conv_mode].copy()self.num_frames = args.num_framesclass ChatSessionManager:def __init__(self):self.chatbot_instance = Nonedef initialize_chatbot(self, args, model_path, tokenizer, model, image_processor, context_len):self.chatbot_instance = InferenceDemo(args, model_path, tokenizer, model, image_processor, context_len)print(f"Initialized Chatbot instance with ID: {id(self.chatbot_instance)}")def reset_chatbot(self):self.chatbot_instance = Nonedef get_chatbot(self, args, model_path, tokenizer, model, image_processor, context_len):if self.chatbot_instance is None:self.initialize_chatbot(args, model_path, tokenizer, model, image_processor, context_len)2 unmodified lineschat_manager = ChatSessionManager()def clear_history():if not LLAVA_AVAILABLE:return {"error": "LLaVA modules not available"}try:inst = chat_manager.get_chatbot(args, args.model_path if args else "PULSE-ECG/PULSE-7B",tokenizer, model, image_processor, context_len)mode = getattr(inst, 'conv_mode', None)if mode and mode in conv_templates:inst.conversation = conv_templates[mode].copy()else:inst.conversation = inst.conversation.__class__()return {"status": "success", "message": "Conversation history cleared"}except Exception as e:return {"error": f"Failed to clear history: {str(e)}"}# ----- Robust prefix stripper -----def _strip_prefix_relaxed(text: str, prefix: str) -> str:try:if text.startswith(prefix):return text[len(prefix):]t_norm = " ".join(text.split())p_norm = " ".join(prefix.split())if t_norm.startswith(p_norm):idx = text.find(prefix.splitlines()[0]) if prefix.splitlines() else -1if idx >= 0:return text[idx + len(prefix.splitlines()[0]):]except Exception:passreturn text# ----- Core generate -----def generate_response(message_text,image_input,temperature=0.05,top_p=1.0,max_output_tokens=1024,repetition_penalty=1.0,conv_mode_override=None,do_sample=False, # default greedy -> deterministikseed=None,use_stop=True):if not LLAVA_AVAILABLE:return {"error": "LLaVA modules not available"}try:if not message_text or not image_input:return {"error": "Both message text and image are required"}# Determinism knobsif seed is not None:try:seed = int(seed)torch.manual_seed(seed)np.random.seed(seed)except Exception:passinst = chat_manager.get_chatbot(args, args.model_path if args else "PULSE-ECG/PULSE-7B",tokenizer, model, image_processor, context_len)# Imageimage = process_image_input(image_input)img_byte_arr = BytesIO()image.save(img_byte_arr, format='JPEG')image_hash = hashlib.md5(img_byte_arr.getvalue()).hexdigest()# Save image to logst = datetime.datetime.now()filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{image_hash}.jpg")os.makedirs(os.path.dirname(filename), exist_ok=True)image.save(filename)# Preprocessprocessed_images = process_images([image], inst.image_processor, inst.model.config)if len(processed_images) == 0:return {"error": "Image processing returned empty list"}image_tensor = processed_images[0].half().to(inst.model.device).unsqueeze(0)# Conversationif conv_mode_override:inst.conversation = conv_templates[conv_mode_override].copy()else:inst.conversation = conv_templates[inst.conv_mode].copy()inp = DEFAULT_IMAGE_TOKEN + "\n" + message_textinst.conversation.append_message(inst.conversation.roles[0], inp)inst.conversation.append_message(inst.conversation.roles[1], None)prompt = inst.conversation.get_prompt()# Tokenizeinput_ids = tokenizer_image_token(prompt, inst.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(inst.model.device)# Stop criteriastopping_criteria = Nonestop_str = inst.conversation.sep if inst.conversation.sep_style != SeparatorStyle.TWO else inst.conversation.sep2if use_stop:stopping_criteria = KeywordsStoppingCriteria([stop_str], inst.tokenizer, input_ids)# PAD/EOS safetypad_id = inst.tokenizer.pad_token_ideos_id = inst.tokenizer.eos_token_id if inst.tokenizer.eos_token_id is not None else pad_idif pad_id is None:# safety net (rare)inst.tokenizer.add_special_tokens({"pad_token": inst.tokenizer.eos_token or "</s>"})pad_id = inst.tokenizer.pad_token_ideos_id = inst.tokenizer.eos_token_id or pad_idgen_cfg = GenerationConfig(do_sample=bool(do_sample),temperature=float(temperature),top_p=float(top_p),max_new_tokens=int(max_output_tokens),repetition_penalty=float(repetition_penalty),pad_token_id=pad_id,eos_token_id=eos_id)with torch.no_grad():outputs = inst.model.generate(inputs=input_ids,images=image_tensor,generation_config=gen_cfg,use_cache=True,stopping_criteria=[stopping_criteria] if stopping_criteria is not None else None,return_dict_in_generate=True)# Robust decodesequences = outputs.sequencesgen_ids = sequences[0]full_text = inst.tokenizer.decode(gen_ids, skip_special_tokens=True)prompt_text = inst.tokenizer.decode(input_ids[0], skip_special_tokens=True)if gen_ids.shape[0] > input_ids.shape[1]:response = inst.tokenizer.decode(gen_ids[input_ids.shape[1]:], skip_special_tokens=True).strip()else:response = _strip_prefix_relaxed(full_text, prompt_text).strip()if not response:response = full_text.replace(stop_str, "").strip()# Add to conversationif len(inst.conversation.messages) > 0 and isinstance(inst.conversation.messages[-1], list) and len(inst.conversation.messages[-1]) > 1:inst.conversation.messages[-1][-1] = responseelse:inst.conversation.append_message(inst.conversation.roles[1], response)# Logwith open(get_conv_log_filename(), "a") as fout:fout.write(json.dumps({"type": "chat","model": "PULSE-7b","state": [(message_text, response)],"images": [image_hash],"images_path": [filename]}) + "\n")return {"status": "success", "response": response, "conversation_id": id(inst.conversation)}except Exception as e:return {"error": f"Generation failed: {str(e)}"}# ----- Votes -----def upvote_last_response(conversation_id):try:vote_last_response({"conversation_id": conversation_id}, "upvote", "PULSE-7B")return {"status": "success", "message": "Upvoted"}except Exception as e:return {"error": str(e)}def downvote_last_response(conversation_id):try:vote_last_response({"conversation_id": conversation_id}, "downvote", "PULSE-7B")return {"status": "success", "message": "Downvoted"}except Exception as e:return {"error": str(e)}def flag_response(conversation_id):try:vote_last_response({"conversation_id": conversation_id}, "flag", "PULSE-7B")return {"status": "success", "message": "Flagged"}except Exception as e:return {"error": str(e)}# ----- Init model (with PAD/EOS safety) -----def initialize_model():global tokenizer, model, image_processor, context_len, argsif not LLAVA_AVAILABLE:print("LLaVA modules not available, skipping model initialization")return Falsetry:class Args:def __init__(self):self.model_path = "PULSE-ECG/PULSE-7B"6 unmodified linesself.load_8bit = Falseself.load_4bit = Falseself.debug = Falseargs = Args()model_name = get_model_name_from_path(args.model_path)tok, mdl, img_proc, ctx_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit)# PAD/EOS safetyif tok.eos_token_id is None and tok.eos_token is None:try:tok.add_special_tokens({"eos_token": "</s>"})except Exception:passif tok.pad_token_id is None:if tok.eos_token is not None:tok.pad_token = tok.eos_tokenelse:if tok.unk_token is None:try:tok.add_special_tokens({"unk_token": "<unk>"})except Exception:passtok.pad_token = tok.unk_token or "</s>"tokenizer, model, image_processor, context_len = tok, mdl, img_proc, ctx_lenif torch.cuda.is_available():model = model.to(torch.device('cuda'))print("Model moved to CUDA")else:print("CUDA not available, using CPU")return Trueexcept Exception as e:print(f"Failed to initialize model: {e}")return False# ----- Query entrypoint -----def query(payload):global model_initializedif not model_initialized:print("Initializing model on first query...")model_initialized = initialize_model()if not model_initialized:return {"error": "Model initialization failed"}try:# Log incoming keysprint(f"[DEBUG] query payload keys={list(payload.keys()) if hasattr(payload,'keys') else 'N/A'}")# Inputsmessage_text = (payload.get("message") or payload.get("query") or payload.get("prompt") or payload.get("istem") or "").strip()image_input = (payload.get("image") or payload.get("image_url") or payload.get("img") or None)# Gen paramstemperature = float(payload.get("temperature", 0.05))top_p = float(payload.get("top_p", 1.0))max_output_tokens = int(payload.get("max_output_tokens", payload.get("max_new_tokens", payload.get("max_tokens", 1024))))repetition_penalty = float(payload.get("repetition_penalty", 1.0))conv_mode_override = payload.get("conv_mode", None)# Determinism togglesdo_sample = bool(payload.get("do_sample", False)) # default greedyseed = payload.get("seed", None)use_stop = bool(payload.get("use_stop", True)) # default stop criteria açıkif not message_text:return {"error": "Missing prompt text. Provide 'message' (or 'query'/'prompt'/'istem')."}if not image_input:return {"error": "Missing image. Provide 'image' (url/base64/path) or 'image_url'/'img'."}return generate_response(message_text=message_text,image_input=image_input,temperature=temperature,top_p=top_p,max_output_tokens=max_output_tokens,repetition_penalty=repetition_penalty,conv_mode_override=conv_mode_override,do_sample=do_sample,seed=seed,use_stop=use_stop)except Exception as e:return {"error": f"Query failed: {str(e)}"}# ----- Health / Info -----def health_check():return {"status": "healthy","model_initialized": model_initialized,1 unmodified line"llava_available": LLAVA_AVAILABLE,"transformers_available": TRANSFORMERS_AVAILABLE,"cv2_available": CV2_AVAILABLE,"lazy_loading": True}def get_model_info():if not model_initialized:return {"error": "Model not initialized yet", "lazy_loading": True}return {"model_path": args.model_path if args else "Unknown","model_type": "PULSE-7B",1 unmodified line"device": str(model.device) if model else "Unknown"}# ----- HF Endpoint handler -----class EndpointHandler:def __init__(self, model_dir):self.model_dir = model_dirprint(f"EndpointHandler initialized with model_dir: {model_dir}")def __call__(self, payload):if "inputs" in payload:return query(payload["inputs"])return query(payload)def health_check(self):return health_check()def get_model_info(self):return get_model_info()if __name__ == "__main__":print("Handler loaded and ready.")
handler.py+228-349