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("""\

""" """

📖 Qwen2-Math Demo
""" """\
This WebUI is based on Qwen2-VL for OCR and Qwen2-Math for mathematical reasoning. You can input either images or texts of mathematical or arithmetic problems.
""" ) state = gr.State({"tab_index": 0}) with gr.Row(): with gr.Column(): with gr.Tabs() as input_tabs: with gr.Tab("Upload"): input_image = gr.Image(type="pil", label="Upload"), with gr.Tab("Sketch"): input_sketchpad = gr.Sketchpad(type="pil", label="Sketch", layers=False) input_tabs.select(fn=tabs_select, inputs=[state]) input_text = gr.Textbox(label="input your question") with gr.Row(): with gr.Column(): clear_btn = gr.ClearButton( [*input_image, input_sketchpad, input_text]) with gr.Column(): submit_btn = gr.Button("Submit", variant="primary") with gr.Column(): output_md = gr.Markdown(label="answer", latex_delimiters=[{ "left": "\\(", "right": "\\)", "display": True }, { "left": "\\begin\{equation\}", "right": "\\end\{equation\}", "display": True }, { "left": "\\begin\{align\}", "right": "\\end\{align\}", "display": True }, { "left": "\\begin\{alignat\}", "right": "\\end\{alignat\}", "display": True }, { "left": "\\begin\{gather\}", "right": "\\end\{gather\}", "display": True }, { "left": "\\begin\{CD\}", "right": "\\end\{CD\}", "display": True }, { "left": "\\[", "right": "\\]", "display": True }], elem_id="qwen-md") submit_btn.click( fn=math_chat_bot, inputs=[*input_image, input_sketchpad, input_text, state], outputs=output_md) if __name__ == "__main__": demo.launch()