Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,85 +6,87 @@ import tempfile
|
|
| 6 |
from pathlib import Path
|
| 7 |
import secrets
|
| 8 |
|
| 9 |
-
#
|
| 10 |
image_to_text = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
|
| 11 |
math_reasoning = pipeline("text2text-generation", model="google/flan-t5-large")
|
| 12 |
|
| 13 |
-
|
| 14 |
-
# Helper function to process images
|
| 15 |
def process_image(image, should_convert=False):
|
| 16 |
-
|
| 17 |
-
Saves an uploaded image and
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(Path(tempfile.gettempdir()) / "gradio")
|
| 24 |
os.makedirs(uploaded_file_dir, exist_ok=True)
|
|
|
|
| 25 |
# Save the uploaded image as a temporary file
|
| 26 |
name = f"tmp{secrets.token_hex(8)}.jpg"
|
| 27 |
filename = os.path.join(uploaded_file_dir, name)
|
| 28 |
-
|
| 29 |
if should_convert:
|
| 30 |
-
#
|
| 31 |
-
new_img = Image.new(
|
| 32 |
new_img.paste(image, (0, 0), mask=image)
|
| 33 |
image = new_img
|
|
|
|
| 34 |
image.save(filename)
|
| 35 |
-
|
| 36 |
# Generate text description of the image
|
| 37 |
description = image_to_text(Image.open(filename))[0]['generated_text']
|
| 38 |
-
|
| 39 |
-
# Clean up file
|
| 40 |
os.remove(filename)
|
| 41 |
return description
|
| 42 |
|
| 43 |
-
|
| 44 |
def get_math_response(image_description, user_question):
|
| 45 |
-
|
| 46 |
-
Generates a math
|
| 47 |
-
|
| 48 |
-
:param user_question:
|
| 49 |
-
'''
|
| 50 |
prompt = ""
|
| 51 |
if image_description:
|
| 52 |
-
prompt += f"Image
|
| 53 |
if user_question:
|
| 54 |
-
prompt += f"User question
|
| 55 |
else:
|
| 56 |
-
return "Please provide a valid
|
| 57 |
-
|
|
|
|
| 58 |
response = math_reasoning(prompt, max_length=512)[0]['generated_text']
|
| 59 |
return response
|
| 60 |
|
| 61 |
-
|
| 62 |
# Combined chatbot logic
|
| 63 |
-
def
|
| 64 |
-
current_tab_index = state[
|
| 65 |
image_description = None
|
| 66 |
|
| 67 |
# Handle image upload
|
| 68 |
if current_tab_index == 0:
|
| 69 |
if image is not None:
|
| 70 |
-
image_description = process_image(image
|
|
|
|
| 71 |
# Handle sketchpad input
|
| 72 |
elif current_tab_index == 1:
|
| 73 |
-
if sketchpad and sketchpad[
|
| 74 |
-
image_description = process_image(sketchpad[
|
| 75 |
-
|
|
|
|
| 76 |
return get_math_response(image_description, question)
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def tabs_select(e: gr.SelectData, _state):
|
| 81 |
-
_state["tab_index"] = e.index
|
| 82 |
-
|
| 83 |
css = """
|
| 84 |
#qwen-md .katex-display { display: inline; }
|
| 85 |
#qwen-md .katex-display>.katex { display: inline; }
|
| 86 |
#qwen-md .katex-display>.katex>.katex-html { display: inline; }
|
| 87 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
with gr.Blocks(css=css) as demo:
|
| 89 |
gr.HTML("""\
|
| 90 |
<p align="center"><img src="https://huggingface.co/front/assets/huggingface_logo.svg" style="height: 60px"/><p>"""
|
|
@@ -93,23 +95,24 @@ with gr.Blocks(css=css) as demo:
|
|
| 93 |
<center><font size=3>This demo uses Hugging Face models for OCR and mathematical reasoning. You can input images or text-based questions.</center>"""
|
| 94 |
)
|
| 95 |
state = gr.State({"tab_index": 0})
|
|
|
|
| 96 |
with gr.Row():
|
| 97 |
with gr.Column():
|
| 98 |
with gr.Tabs() as input_tabs:
|
| 99 |
with gr.Tab("Upload"):
|
| 100 |
-
input_image = gr.Image(type="pil", label="Upload")
|
| 101 |
with gr.Tab("Sketch"):
|
| 102 |
-
input_sketchpad = gr.Sketchpad(
|
| 103 |
input_tabs.select(fn=tabs_select, inputs=[state])
|
| 104 |
-
input_text = gr.Textbox(label="
|
| 105 |
with gr.Row():
|
| 106 |
with gr.Column():
|
| 107 |
-
clear_btn = gr.ClearButton(
|
| 108 |
-
[*input_image, input_sketchpad, input_text])
|
| 109 |
with gr.Column():
|
| 110 |
submit_btn = gr.Button("Submit", variant="primary")
|
|
|
|
| 111 |
with gr.Column():
|
| 112 |
-
output_md = gr.Markdown(label="
|
| 113 |
latex_delimiters=[{
|
| 114 |
"left": "\\(",
|
| 115 |
"right": "\\)",
|
|
@@ -118,30 +121,18 @@ with gr.Blocks(css=css) as demo:
|
|
| 118 |
"left": "\\begin\{equation\}",
|
| 119 |
"right": "\\end\{equation\}",
|
| 120 |
"display": True
|
| 121 |
-
}, {
|
| 122 |
-
"left": "\\begin\{align\}",
|
| 123 |
-
"right": "\\end\{align\}",
|
| 124 |
-
"display": True
|
| 125 |
-
}, {
|
| 126 |
-
"left": "\\begin\{alignat\}",
|
| 127 |
-
"right": "\\end\{alignat\}",
|
| 128 |
-
"display": True
|
| 129 |
-
}, {
|
| 130 |
-
"left": "\\begin\{gather\}",
|
| 131 |
-
"right": "\\end\{gather\}",
|
| 132 |
-
"display": True
|
| 133 |
-
}, {
|
| 134 |
-
"left": "\\begin\{CD\}",
|
| 135 |
-
"right": "\\end\{CD\}",
|
| 136 |
-
"display": True
|
| 137 |
}, {
|
| 138 |
"left": "\\[",
|
| 139 |
"right": "\\]",
|
| 140 |
"display": True
|
| 141 |
}],
|
| 142 |
elem_id="qwen-md")
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from pathlib import Path
|
| 7 |
import secrets
|
| 8 |
|
| 9 |
+
# Initialize Hugging Face pipelines
|
| 10 |
image_to_text = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
|
| 11 |
math_reasoning = pipeline("text2text-generation", model="google/flan-t5-large")
|
| 12 |
|
| 13 |
+
# Helper function to process image
|
|
|
|
| 14 |
def process_image(image, should_convert=False):
|
| 15 |
+
"""
|
| 16 |
+
Saves an uploaded image and extracts math-related descriptions using the image-to-text pipeline.
|
| 17 |
+
"""
|
| 18 |
+
# Create temporary directory for saving images
|
| 19 |
+
uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
|
| 20 |
+
Path(tempfile.gettempdir()) / "gradio"
|
| 21 |
+
)
|
|
|
|
| 22 |
os.makedirs(uploaded_file_dir, exist_ok=True)
|
| 23 |
+
|
| 24 |
# Save the uploaded image as a temporary file
|
| 25 |
name = f"tmp{secrets.token_hex(8)}.jpg"
|
| 26 |
filename = os.path.join(uploaded_file_dir, name)
|
| 27 |
+
|
| 28 |
if should_convert:
|
| 29 |
+
# Convert image to RGB if required
|
| 30 |
+
new_img = Image.new('RGB', size=(image.width, image.height), color=(255, 255, 255))
|
| 31 |
new_img.paste(image, (0, 0), mask=image)
|
| 32 |
image = new_img
|
| 33 |
+
|
| 34 |
image.save(filename)
|
| 35 |
+
|
| 36 |
# Generate text description of the image
|
| 37 |
description = image_to_text(Image.open(filename))[0]['generated_text']
|
| 38 |
+
|
| 39 |
+
# Clean up temporary file
|
| 40 |
os.remove(filename)
|
| 41 |
return description
|
| 42 |
|
| 43 |
+
# Function to handle math reasoning based on question and image description
|
| 44 |
def get_math_response(image_description, user_question):
|
| 45 |
+
"""
|
| 46 |
+
Generates a math-related response using the image description and user question.
|
| 47 |
+
"""
|
|
|
|
|
|
|
| 48 |
prompt = ""
|
| 49 |
if image_description:
|
| 50 |
+
prompt += f"Image description: {image_description}\n"
|
| 51 |
if user_question:
|
| 52 |
+
prompt += f"User question: {user_question}\n"
|
| 53 |
else:
|
| 54 |
+
return "Please provide a valid question."
|
| 55 |
+
|
| 56 |
+
# Generate a math-related response using text2text generation
|
| 57 |
response = math_reasoning(prompt, max_length=512)[0]['generated_text']
|
| 58 |
return response
|
| 59 |
|
|
|
|
| 60 |
# Combined chatbot logic
|
| 61 |
+
def math_chat_bot(image, sketchpad, question, state):
|
| 62 |
+
current_tab_index = state["tab_index"]
|
| 63 |
image_description = None
|
| 64 |
|
| 65 |
# Handle image upload
|
| 66 |
if current_tab_index == 0:
|
| 67 |
if image is not None:
|
| 68 |
+
image_description = process_image(image)
|
| 69 |
+
|
| 70 |
# Handle sketchpad input
|
| 71 |
elif current_tab_index == 1:
|
| 72 |
+
if sketchpad and sketchpad["composite"]:
|
| 73 |
+
image_description = process_image(sketchpad["composite"], should_convert=True)
|
| 74 |
+
|
| 75 |
+
# Get the math reasoning response
|
| 76 |
return get_math_response(image_description, question)
|
| 77 |
|
| 78 |
+
# CSS for formatting LaTeX
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
css = """
|
| 80 |
#qwen-md .katex-display { display: inline; }
|
| 81 |
#qwen-md .katex-display>.katex { display: inline; }
|
| 82 |
#qwen-md .katex-display>.katex>.katex-html { display: inline; }
|
| 83 |
"""
|
| 84 |
+
|
| 85 |
+
# Tab selection callback
|
| 86 |
+
def tabs_select(e: gr.SelectData, _state):
|
| 87 |
+
_state["tab_index"] = e.index
|
| 88 |
+
|
| 89 |
+
# Gradio interface
|
| 90 |
with gr.Blocks(css=css) as demo:
|
| 91 |
gr.HTML("""\
|
| 92 |
<p align="center"><img src="https://huggingface.co/front/assets/huggingface_logo.svg" style="height: 60px"/><p>"""
|
|
|
|
| 95 |
<center><font size=3>This demo uses Hugging Face models for OCR and mathematical reasoning. You can input images or text-based questions.</center>"""
|
| 96 |
)
|
| 97 |
state = gr.State({"tab_index": 0})
|
| 98 |
+
|
| 99 |
with gr.Row():
|
| 100 |
with gr.Column():
|
| 101 |
with gr.Tabs() as input_tabs:
|
| 102 |
with gr.Tab("Upload"):
|
| 103 |
+
input_image = gr.Image(type="pil", label="Upload")
|
| 104 |
with gr.Tab("Sketch"):
|
| 105 |
+
input_sketchpad = gr.Sketchpad(label="Sketch", layers=False)
|
| 106 |
input_tabs.select(fn=tabs_select, inputs=[state])
|
| 107 |
+
input_text = gr.Textbox(label="Input your question")
|
| 108 |
with gr.Row():
|
| 109 |
with gr.Column():
|
| 110 |
+
clear_btn = gr.ClearButton([input_image, input_sketchpad, input_text])
|
|
|
|
| 111 |
with gr.Column():
|
| 112 |
submit_btn = gr.Button("Submit", variant="primary")
|
| 113 |
+
|
| 114 |
with gr.Column():
|
| 115 |
+
output_md = gr.Markdown(label="Answer",
|
| 116 |
latex_delimiters=[{
|
| 117 |
"left": "\\(",
|
| 118 |
"right": "\\)",
|
|
|
|
| 121 |
"left": "\\begin\{equation\}",
|
| 122 |
"right": "\\end\{equation\}",
|
| 123 |
"display": True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
}, {
|
| 125 |
"left": "\\[",
|
| 126 |
"right": "\\]",
|
| 127 |
"display": True
|
| 128 |
}],
|
| 129 |
elem_id="qwen-md")
|
| 130 |
+
|
| 131 |
+
submit_btn.click(
|
| 132 |
+
fn=math_chat_bot,
|
| 133 |
+
inputs=[input_image, input_sketchpad, input_text, state],
|
| 134 |
+
outputs=output_md
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# Launch Gradio app
|
| 138 |
+
demo.launch()
|