handle py
#21
by ismailhakki37 - opened
123452 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748495051529 unmodified lines62636465666768698 unmodified lines787980818283848586878889909179 unmodified lines17117217317417517647 unmodified lines224225226227228229230231232233234235236237238239240241242243244245246247248249250149 unmodified lines40040140240340440574 unmodified lines48048148248348448548610 unmodified lines497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528import osimport datetime# Try to import cv2, but make it optionaltry:2 unmodified linesexcept ImportError:CV2_AVAILABLE = Falseprint("Warning: cv2 (OpenCV) not available. Video processing will be disabled.")import torchimport numpy as npimport hashlibimport PILimport base64import jsonimport requestsfrom PIL import Imagefrom io import BytesIOfrom transformers import TextStreamer, TextIteratorStreamerfrom threading import Threadfrom llava import conversation as conversation_libfrom llava.constants import DEFAULT_IMAGE_TOKENfrom 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_modelfrom llava.utils import disable_torch_initfrom llava.mm_utils import (tokenizer_image_token,process_images,get_model_name_from_path,KeywordsStoppingCriteria,)from huggingface_hub import HfApifrom huggingface_hub import loginfrom huggingface_hub import revision_exists# Initialize Hugging Face APIif "HF_TOKEN" in os.environ:login(token=os.environ["HF_TOKEN"], write_permission=True)api = HfApi()repo_name = os.environ.get("LOG_REPO", "")else:api = Nonerepo_name = ""9 unmodified linescontext_len = Noneargs = None# Gradio artık kullanılmıyor - Hugging Face endpoint için gerekli değildef 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")8 unmodified linesdef vote_last_response(state, vote_type, model_selector):if api and repo_name:with open(get_conv_vote_filename(), "a") as fout:data = {"type": vote_type,"model": model_selector,"state": state,}fout.write(json.dumps(data) + "\n")try:api.upload_file(path_or_fileobj=get_conv_vote_filename(),path_in_repo=get_conv_vote_filename().replace("./votes/", ""),79 unmodified linesclass InferenceDemo(object):def __init__(self, args, model_path, tokenizer, model, image_processor, context_len) -> None:disable_torch_init()self.tokenizer, self.model, self.image_processor, self.context_len = (47 unmodified linesdef clear_history():"""Clear conversation history"""chatbot_instance = chat_manager.get_chatbot(args, model_path, tokenizer, model, image_processor, context_len)chatbot_instance.conversation = conv_templates[chatbot_instance.conv_mode].copy()return {"status": "success", "message": "Conversation history cleared"}def add_message(message_text, image_input=None):"""Add a message to the conversation"""global chat_image_numif not hasattr(add_message, 'chat_image_num'):add_message.chat_image_num = 0if image_input:add_message.chat_image_num += 1if add_message.chat_image_num > 1:chat_manager.reset_chatbot()add_message.chat_image_num = 1return {"status": "success", "message": "Message added"}def generate_response(message_text, image_input, temperature=0.05, top_p=1.0, max_output_tokens=4096):"""Generate response for the given message and image"""try:if not message_text or not image_input:return {"error": "Both message text and image are required"}149 unmodified lines"""Initialize the model and tokenizer"""global tokenizer, model, image_processor, context_len, argstry:# Set default argumentsclass Args:74 unmodified linesreturn {"status": "healthy","model_initialized": model_initialized,"cuda_available": torch.cuda.is_available()}def get_model_info():10 unmodified lines# For backward compatibility and testingif __name__ == "__main__":import argparseargparser = argparse.ArgumentParser()argparser.add_argument("--server_name", default="0.0.0.0", type=str)argparser.add_argument("--port", default="6123", type=str)argparser.add_argument("--model_path", default="PULSE-ECG/PULSE-7B", type=str)argparser.add_argument("--model-base", type=str, default=None)argparser.add_argument("--num-gpus", type=int, default=1)argparser.add_argument("--conv-mode", type=str, default=None)argparser.add_argument("--temperature", type=float, default=0.05)argparser.add_argument("--max-new-tokens", type=int, default=1024)argparser.add_argument("--num_frames", type=int, default=16)argparser.add_argument("--load-8bit", action="store_true")argparser.add_argument("--load-4bit", action="store_true")argparser.add_argument("--debug", action="store_true")args = argparser.parse_args()model_path = args.model_pathfilt_invalid = "cut"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)print("### image_processor",image_processor)print("### tokenzier",tokenizer)model=model.to(torch.device('cuda'))print("Model initialized successfully!")print("This handler is now ready for Hugging Face endpoints.")print("Use the 'query' function as the main endpoint.")1234567891011122 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970719 unmodified lines8182838485868 unmodified lines959697989910010110210310410510610710810979 unmodified lines18919019119219319419519619747 unmodified lines245246247248249250251252253254255256257258259260261262263264265266267268269149 unmodified lines41942042142242342442542642742874 unmodified lines50350450550650750850951051151210 unmodified lines523524525526527528import osimport datetimeimport torchimport numpy as npimport hashlibimport jsonimport requestsfrom PIL import Imagefrom io import BytesIO# Try to import cv2, but make it optionaltry:2 unmodified linesexcept ImportError:CV2_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_TOKENfrom 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_modelfrom llava.utils import disable_torch_initfrom llava.mm_utils import (tokenizer_image_token,process_images,get_model_name_from_path,KeywordsStoppingCriteria,)LLAVA_AVAILABLE = Trueexcept ImportError as e:LLAVA_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 = Trueexcept ImportError:HF_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)api = HfApi()repo_name = os.environ.get("LOG_REPO", "")except Exception as e:print(f"Failed to initialize HF API: {e}")api = Nonerepo_name = ""else:api = Nonerepo_name = ""9 unmodified linescontext_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")8 unmodified linesdef vote_last_response(state, vote_type, model_selector):if 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/", ""),79 unmodified linesclass 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 = (47 unmodified linesdef clear_history():"""Clear conversation history"""if not LLAVA_AVAILABLE:return {"error": "LLaVA modules not available"}try:chatbot_instance = chat_manager.get_chatbot(args, model_path, tokenizer, model, image_processor, context_len)chatbot_instance.conversation = conv_templates[chatbot_instance.conv_mode].copy()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):"""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"}149 unmodified lines"""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:74 unmodified linesreturn {"status": "healthy","model_initialized": model_initialized,"cuda_available": torch.cuda.is_available(),"llava_available": LLAVA_AVAILABLE,"transformers_available": TRANSFORMERS_AVAILABLE,"cv2_available": CV2_AVAILABLE}def get_model_info():10 unmodified lines# 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.")
handler.py+88-88