import os import torch import gradio as gr import tempfile import secrets from pathlib import Path from transformers import AutoModelForCausalLM, AutoTokenizer, BlipForConditionalGeneration, AutoProcessor from PIL import Image # Load Vision-Language Model vl_model_name = "Salesforce/blip-image-captioning-large" vl_model = BlipForConditionalGeneration.from_pretrained(vl_model_name) vl_processor = AutoProcessor.from_pretrained(vl_model_name) # Load Text Model model_name = "Qwen/Qwen2.5-Math-1.5B-Instruct" device = "cuda" if torch.cuda.is_available() else "cpu" model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto") tokenizer = AutoTokenizer.from_pretrained(model_name) math_messages = [] def process_image(image, shouldConvert=False): global math_messages math_messages = [] # Reset when uploading an image if shouldConvert: new_img = Image.new('RGB', size=(image.width, image.height), color=(255, 255, 255)) new_img.paste(image, (0, 0), mask=image) image = new_img # Convert the image to tensor inputs = vl_processor(images=image, return_tensors="pt") output = vl_model.generate(**inputs) description = vl_processor.batch_decode(output, skip_special_tokens=True)[0] return f"Math-related content detected: {description}" def get_math_response(image_description, user_question): global math_messages if not math_messages: math_messages.append({'role': 'system', 'content': 'You are a helpful math assistant.'}) math_messages = math_messages[:1] content = f'Image description: {image_description}\n\n' if image_description else '' query = f"{content}User question: {user_question}" math_messages.append({'role': 'user', 'content': query}) model_inputs = tokenizer(query, return_tensors="pt").to(device) output = model.generate(**model_inputs, max_new_tokens=512) answer = tokenizer.decode(output[0], skip_special_tokens=True) yield answer.replace("\\", "\\\\") math_messages.append({'role': 'assistant', 'content': answer}) def math_chat_bot(image, sketchpad, question, state): current_tab_index = state["tab_index"] image_description = None if current_tab_index == 0: if image is not None: image_description = process_image(image) elif current_tab_index == 1: if sketchpad and sketchpad["composite"]: image_description = process_image(sketchpad["composite"], True) yield from get_math_response(image_description, question) css = """ #qwen-md .katex-display { display: inline; } #qwen-md .katex-display>.katex { display: inline; } #qwen-md .katex-display>.katex>.katex-html { display: inline; } """ def tabs_select(e: gr.SelectData, _state): _state["tab_index"] = e.index # 创建Gradio接口 with gr.Blocks(css=css) as demo: gr.HTML("""\
""" """