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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoModelForCausalLM,AutoProcessor,pipeline
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import os
|
| 5 |
+
import tempfile
|
| 6 |
+
import torch
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import secrets
|
| 9 |
+
|
| 10 |
+
# Initialise Hugging Face LLM
|
| 11 |
+
model_id="microsoft/Phi-3.5-vision-instruct"
|
| 12 |
+
model=AutoModelForCausalLM.from_pretrained(
|
| 13 |
+
model_id,
|
| 14 |
+
trust_remote_code=True,
|
| 15 |
+
torch_dtype=torch.float16,
|
| 16 |
+
use_flash_attention_2=False)
|
| 17 |
+
|
| 18 |
+
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True, num_crops=16)
|
| 19 |
+
math_messages=[]
|
| 20 |
+
# Function for processing the image
|
| 21 |
+
def process_image(image,should_convert=False):
|
| 22 |
+
'''
|
| 23 |
+
Saves the uploaded image or sketch and then extracts math-related descriptions using the model
|
| 24 |
+
'''
|
| 25 |
+
global math_messages
|
| 26 |
+
math_messages=[]
|
| 27 |
+
# create a temporary directory for saving images
|
| 28 |
+
uploaded_file_dir=os.environ.get("GRADIO_TEMP_DIR") or str(Path(tempfile.gettempdir())/"gradio")
|
| 29 |
+
os.makedirs(uploaded_file_dir,exist_ok=True)
|
| 30 |
+
# saves the uploaded image as a temporary file
|
| 31 |
+
name = f"tmp{secrets.token_hex(20)}.jpg"
|
| 32 |
+
filename = os.path.join(uploaded_file_dir, name)
|
| 33 |
+
# If the input was a sketch then convert into RGB format
|
| 34 |
+
if should_convert:
|
| 35 |
+
new_img = Image.new('RGB', size=(image.width, image.height), color=(255, 255, 255))
|
| 36 |
+
new_img.paste(image, (0, 0), mask=image)
|
| 37 |
+
image = new_img
|
| 38 |
+
# Saves the image in the temporary file
|
| 39 |
+
image.save(filename)
|
| 40 |
+
# Calling the model to process images
|
| 41 |
+
messages = [{
|
| 42 |
+
'role': 'system',
|
| 43 |
+
'content': [{'text': 'You are a helpful assistant.'}]
|
| 44 |
+
}, {
|
| 45 |
+
'role': 'user',
|
| 46 |
+
'content': [
|
| 47 |
+
{'image': f'file://{filename}'},
|
| 48 |
+
{'text': 'Please describe the math-related content in this image, ensuring that any LaTeX formulas are correctly transcribed. Non-mathematical details do not need to be described.'}
|
| 49 |
+
]
|
| 50 |
+
}]
|
| 51 |
+
prompt = processor.tokenizer.apply_chat_template(
|
| 52 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 53 |
+
)
|
| 54 |
+
# Process the input
|
| 55 |
+
inputs = processor(prompt, image, return_tensors="pt")
|
| 56 |
+
|
| 57 |
+
# Generate the response
|
| 58 |
+
generation_args = {
|
| 59 |
+
"max_new_tokens": 1000,
|
| 60 |
+
"temperature": 0.2,
|
| 61 |
+
"do_sample": True,
|
| 62 |
+
}
|
| 63 |
+
generate_ids = model.generate(**inputs, eos_token_id=processor.tokenizer.eos_token_id, **generation_args)
|
| 64 |
+
|
| 65 |
+
# Decode the response
|
| 66 |
+
generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
|
| 67 |
+
response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 68 |
+
return response
|
| 69 |
+
|
| 70 |
+
# Function to get math-response from the processed image
|
| 71 |
+
def get_math_response(image_description,user_question):
|
| 72 |
+
global math_messages
|
| 73 |
+
if not math_messages:
|
| 74 |
+
math_messages.append({'role': 'system', 'content': 'You are a helpful math assistant.'})
|
| 75 |
+
math_messages = math_messages[:1]
|
| 76 |
+
if image_description is not None:
|
| 77 |
+
content = f'Image description: {image_description}\n\n'
|
| 78 |
+
else:
|
| 79 |
+
content = ''
|
| 80 |
+
query = f"{content}User question: {user_question}"
|
| 81 |
+
math_messages.append({'role': 'user', 'content': query})
|
| 82 |
+
pipe = pipeline("text-generation", model="deepseek-ai/DeepSeek-V2.5-1210", trust_remote_code=True)
|
| 83 |
+
response=pipe(math_messages)
|
| 84 |
+
print(response)
|
| 85 |
+
answer = None
|
| 86 |
+
for resp in response:
|
| 87 |
+
if resp.output is None:
|
| 88 |
+
continue
|
| 89 |
+
answer = resp.output.choices[0].message.content
|
| 90 |
+
yield answer.replace("\\", "\\\\")
|
| 91 |
+
print(f'query: {query}\nanswer: {answer}')
|
| 92 |
+
if answer is None:
|
| 93 |
+
math_messages.pop()
|
| 94 |
+
else:
|
| 95 |
+
math_messages.append({'role': 'assistant', 'content': answer})
|
| 96 |
+
# creating the chatbot
|
| 97 |
+
def math_chat_bot(image, sketchpad, question, state):
|
| 98 |
+
current_tab_index = state["tab_index"]
|
| 99 |
+
image_description = None
|
| 100 |
+
# Upload
|
| 101 |
+
if current_tab_index == 0:
|
| 102 |
+
if image is not None:
|
| 103 |
+
image_description = process_image(image)
|
| 104 |
+
# Sketch
|
| 105 |
+
elif current_tab_index == 1:
|
| 106 |
+
print(sketchpad)
|
| 107 |
+
if sketchpad and sketchpad["composite"]:
|
| 108 |
+
image_description = process_image(sketchpad["composite"], True)
|
| 109 |
+
yield from get_math_response(image_description, question)
|
| 110 |
+
|
| 111 |
+
css = """
|
| 112 |
+
#qwen-md .katex-display { display: inline; }
|
| 113 |
+
#qwen-md .katex-display>.katex { display: inline; }
|
| 114 |
+
#qwen-md .katex-display>.katex>.katex-html { display: inline; }
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
def tabs_select(e: gr.SelectData, _state):
|
| 118 |
+
_state["tab_index"] = e.index
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# εε»ΊGradioζ₯ε£
|
| 122 |
+
with gr.Blocks(css=css) as demo:
|
| 123 |
+
gr.HTML(
|
| 124 |
+
"""\
|
| 125 |
+
<center><font size=3>This WebUI is based on Qwen2-VL for OCR and Qwen2.5-Math for mathematical reasoning. You can input either images or texts of mathematical or arithmetic problems.</center>"""
|
| 126 |
+
)
|
| 127 |
+
state = gr.State({"tab_index": 0})
|
| 128 |
+
with gr.Row():
|
| 129 |
+
with gr.Column():
|
| 130 |
+
with gr.Tabs() as input_tabs:
|
| 131 |
+
with gr.Tab("Upload"):
|
| 132 |
+
input_image = gr.Image(type="pil", label="Upload"),
|
| 133 |
+
with gr.Tab("Sketch"):
|
| 134 |
+
input_sketchpad = gr.Sketchpad(type="pil", label="Sketch", layers=False)
|
| 135 |
+
input_tabs.select(fn=tabs_select, inputs=[state])
|
| 136 |
+
input_text = gr.Textbox(label="input your question")
|
| 137 |
+
with gr.Row():
|
| 138 |
+
with gr.Column():
|
| 139 |
+
clear_btn = gr.ClearButton(
|
| 140 |
+
[*input_image, input_sketchpad, input_text])
|
| 141 |
+
with gr.Column():
|
| 142 |
+
submit_btn = gr.Button("Submit", variant="primary")
|
| 143 |
+
with gr.Column():
|
| 144 |
+
output_md = gr.Markdown(label="answer",
|
| 145 |
+
latex_delimiters=[{
|
| 146 |
+
"left": "\\(",
|
| 147 |
+
"right": "\\)",
|
| 148 |
+
"display": True
|
| 149 |
+
}, {
|
| 150 |
+
"left": "\\begin\{equation\}",
|
| 151 |
+
"right": "\\end\{equation\}",
|
| 152 |
+
"display": True
|
| 153 |
+
}, {
|
| 154 |
+
"left": "\\begin\{align\}",
|
| 155 |
+
"right": "\\end\{align\}",
|
| 156 |
+
"display": True
|
| 157 |
+
}, {
|
| 158 |
+
"left": "\\begin\{alignat\}",
|
| 159 |
+
"right": "\\end\{alignat\}",
|
| 160 |
+
"display": True
|
| 161 |
+
}, {
|
| 162 |
+
"left": "\\begin\{gather\}",
|
| 163 |
+
"right": "\\end\{gather\}",
|
| 164 |
+
"display": True
|
| 165 |
+
}, {
|
| 166 |
+
"left": "\\begin\{CD\}",
|
| 167 |
+
"right": "\\end\{CD\}",
|
| 168 |
+
"display": True
|
| 169 |
+
}, {
|
| 170 |
+
"left": "\\[",
|
| 171 |
+
"right": "\\]",
|
| 172 |
+
"display": True
|
| 173 |
+
}],
|
| 174 |
+
elem_id="qwen-md")
|
| 175 |
+
submit_btn.click(
|
| 176 |
+
fn=math_chat_bot,
|
| 177 |
+
inputs=[*input_image, input_sketchpad, input_text, state],
|
| 178 |
+
outputs=output_md)
|
| 179 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
numpy==1.24.4
|
| 3 |
+
Pillow==10.3.0
|
| 4 |
+
Requests==2.31.0
|
| 5 |
+
torch
|
| 6 |
+
torchvision
|
| 7 |
+
transformers==4.43.0
|
| 8 |
+
accelerate==0.30.0
|