Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files12345678910111213141516171819201 unmodified line2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081 unmodified line110111112113114115116117118119from threading import Threadfrom llava_llama3.serve.cli import chat_llavafrom llava_llama3.model.builder import load_pretrained_modelimport gradio as grimport torchfrom PIL import Imageimport argparseimport spacesimport osimport timeroot_path = os.path.dirname(os.path.abspath(__file__))print(root_path)parser = argparse.ArgumentParser()parser.add_argument("--model-path", type=str, default="TheFinAI/FinLLaVA")parser.add_argument("--device", type=str, default="cuda:0")parser.add_argument("--conv-mode", type=str, default="llama_3")parser.add_argument("--temperature", type=float, default=0.7)parser.add_argument("--max-new-tokens", type=int, default=512)1 unmodified lineparser.add_argument("--load-4bit", action="store_true")args = parser.parse_args()# load modeltokenizer, llava_model, image_processor, context_len = load_pretrained_model(args.model_path,None,'llava_llama3',args.load_8bit,args.load_4bit,device=args.device)@spaces.GPUdef bot_streaming(message, history):print(message)image_path = None# Check if there's an image in the current messageif message["files"]:# message["files"][-1] could be a dictionary or a stringif isinstance(message["files"][-1], dict):image_path = message["files"][-1]["path"]else:image_path = message["files"][-1]else:# If no image in the current message, look in the history for the last image pathfor hist in history:if isinstance(hist[0], tuple):image_path = hist[0][0]# Error handling if no image path is foundif image_path is None:raise gr.Error("You need to upload an image for LLaVA to work.")# If the image_path is a string, no need to load it into a PIL image# Just use the path directly in the next stepsprint(f"\033[91m{image_path}, {type(image_path)}\033[0m")# Generate the prompt for the modelprompt = message['text']streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)# Set up the generation arguments, including the streamergeneration_kwargs = dict(args=args,image_file=image_path,text=prompt,tokenizer=tokenizer,model=llava_model,streamer=streamer,image_processor=image_processor, # todo: input model name or pathcontext_len=context_len)# Define the function to call `chat_llava` with the given argumentsdef generate_output(generation_kwargs):chat_llava(**generation_kwargs)# Start the generation in a separate threadthread = Thread(target=generate_output, kwargs=generation_kwargs)thread.start()# Initialize a buffer to accumulate the generated textbuffer = ""# Allow the generation to starttime.sleep(0.5)# Iterate over the streamer to handle the incoming text in chunksfor new_text in streamer:# Look for the end of text token and remove itif "<|eot_id|>" in new_text:new_text = new_text.split("<|eot_id|>")[0]# Add the new text to the bufferbuffer += new_text# Remove the prompt from the generated text (if necessary)generated_text_without_prompt = buffer[len(prompt):]# Simulate processing time (optional)time.sleep(0.06)# Yield the current generated text for further processing or displayyield generated_text_without_promptchatbot = gr.Chatbot(scale=1)1 unmodified linewith gr.Blocks(fill_height=True) as demo:gr.ChatInterface(fn=bot_streaming,title="FinLLaVA",examples=[{"text": "What is on the flower?", "files": ["./bee.jpg"]},{"text": "How to make this pastry?", "files": ["./baklava.png"]},{"text":"What is this?","files":["http://images.cocodataset.org/val2017/000000039769.jpg"]}],stop_btn="Stop Generation",multimodal=True,textbox=chat_input,123456789101112131415161718192021222324252627282930313233343536371 unmodified line39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293941 unmodified line96979899100101102103104105106import timefrom threading import Threadimport gradio as grimport torchfrom PIL import Imagefrom transformers import AutoProcessor, LlavaForConditionalGeneration, TextIteratorStreamer, TextStreamer# import spacesimport argparsefrom llava_llama3.model.builder import load_pretrained_modelfrom llava_llama3.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKENfrom llava_llama3.conversation import conv_templates, SeparatorStylefrom llava_llama3.utils import disable_torch_initfrom llava_llama3.mm_utils import process_images, tokenizer_image_token, get_model_name_from_pathfrom llava_llama3.serve.cli import chat_llavaimport requestsfrom io import BytesIOimport base64import osimport globimport pandas as pdfrom tqdm import tqdmimport jsonroot_path = os.path.dirname(os.path.abspath(__file__))print(f'\033[92m{root_path}\033[0m')os.environ['GRADIO_TEMP_DIR'] = root_pathparser = argparse.ArgumentParser()parser.add_argument("--model-path", type=str, default="/mnt/nvme1n1/toby/LLaVA/checkpoints/0806_onlyllava_llava-finma-8B-v0.4-v8/checkpoint-2000")parser.add_argument("--device", type=str, default="cuda")parser.add_argument("--conv-mode", type=str, default="llama_3")parser.add_argument("--temperature", type=float, default=0.7)parser.add_argument("--max-new-tokens", type=int, default=512)1 unmodified lineparser.add_argument("--load-4bit", action="store_true")args = parser.parse_args()# Load modeltokenizer, llava_model, image_processor, context_len = load_pretrained_model(args.model_path,None,'llava_llama3',args.load_8bit,args.load_4bit,device=args.device)def bot_streaming(message, history):print(message)image_file = Noneif message["files"]:if type(message["files"][-1]) == dict:image_file = message["files"][-1]["path"]else:image_file = message["files"][-1]else:for hist in history:if type(hist[0]) == tuple:image_file = hist[0][0]if image_file is None:gr.Error("You need to upload an image for LLaVA to work.")returnstreamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)def generate():print('\033[92mRunning chat\033[0m')output = chat_llava(args=args,image_file=image_file,text=message['text'],tokenizer=tokenizer,model=llava_model,image_processor=image_processor,context_len=context_len,streamer=streamer)return outputthread = Thread(target=generate)thread.start()# thread.join()buffer = ""# output = generate()for new_text in streamer:buffer += new_textgenerated_text_without_prompt = buffertime.sleep(0.06)yield generated_text_without_promptchatbot = gr.Chatbot(scale=1)1 unmodified linewith gr.Blocks(fill_height=True) as demo:gr.ChatInterface(fn=bot_streaming,title="FinLLaVA Demo",examples=[{"text": "What is in this picture?", "files": ["http://images.cocodataset.org/val2017/000000039769.jpg"]},],description="",stop_btn="Stop Generation",multimodal=True,textbox=chat_input,
app.py+60-73