Ayush0804 commited on
Commit
592c01e
·
verified ·
1 Parent(s): c6133ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -12
app.py CHANGED
@@ -1,17 +1,162 @@
1
- import gradio as gr
2
- from transformers import pipeline
 
 
 
 
 
3
 
4
- def generate_response(text):
5
- pipe = pipeline("text-generation", model="text-davinci-003")
6
- response = pipe(text, max_length=512)[0]['generated_text']
7
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- with gr.Blocks() as demo:
10
- gr.Markdown("## Math Reasoning Chatbot")
11
- txt = gr.Textbox(label="Enter your math problem")
12
- btn = gr.Button("Submit")
13
- output = gr.Textbox()
14
 
15
- btn.click(fn=generate_response, inputs=txt, outputs=output)
 
 
 
 
 
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  demo.launch()
 
1
+ from langchain.prompts import PromptTemplate
2
+ from langchain_huggingface import HuggingFaceEndpoint
3
+ from PIL import Image
4
+ import os
5
+ import secrets
6
+ from pathlib import Path
7
+ import tempfile
8
 
9
+ # Initialize the Hugging Face BLIP model
10
+ image_captioning_model = HuggingFaceEndpoint(
11
+ endpoint_url="https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-base",
12
+ huggingfacehub_api_token=os.getenv("HUGGING_FACE_API"), # Ensure you set this in your environment
13
+ temperature=0.7,
14
+ max_new_tokens=1024,
15
+ )
16
+ math_llm=HuggingFaceEndpoint(
17
+ endpoint_url="https://api-inference.huggingface.co/models/meta-llama/Llama-3.2-3B-Instruct",
18
+ huggingfacehub_api_token=os.getenv("HUGGING_FACE_API"), # Ensure you set this in your environment
19
+ temperature=0.7,
20
+ max_new_tokens=1024,)
21
+ # Function to process the image
22
+ def process_image(image, shouldConvert=False):
23
+ # Ensure temporary directory exists
24
+ uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
25
+ Path(tempfile.gettempdir()) / "gradio"
26
+ )
27
+ os.makedirs(uploaded_file_dir, exist_ok=True)
28
+
29
+ # Save the uploaded image
30
+ name = f"tmp{secrets.token_hex(20)}.jpg"
31
+ filename = os.path.join(uploaded_file_dir, name)
32
+ if shouldConvert:
33
+ # Convert image to RGB mode if it contains transparency
34
+ new_img = Image.new("RGB", size=(image.width, image.height), color=(255, 255, 255))
35
+ new_img.paste(image, (0, 0), mask=image)
36
+ image = new_img
37
+ image.save(filename)
38
 
39
+ # Define a PromptTemplate for text instruction
40
+ template = """
41
+ You are a helpful AI assistant.
42
+ Please describe the math-related content in this image, ensuring that any LaTeX formulas are correctly transcribed.
43
+ Non-mathematical details do not need to be described.
44
 
45
+ Image Path: {image}
46
+ """
47
+ prompt_template = PromptTemplate(
48
+ input_variables=["image"], # Dynamically insert the image path
49
+ template=template
50
+ )
51
 
52
+ # Create the text instruction by rendering the prompt template
53
+ prompt = prompt_template.format(image=f"file://{filename}")
54
+
55
+ # Use the model with both the image and the generated prompt
56
+ with open(filename, "rb") as img_file:
57
+ response = image_captioning_model({
58
+ "inputs": {
59
+ "image": img_file,
60
+ "text": prompt
61
+ }
62
+ })
63
+
64
+ # Return the model's response
65
+ return response
66
+
67
+ def get_math_response(image_description, user_question):
68
+ template = """
69
+ You are a helpful AI assistant specialized in solving math reasoning problems.
70
+ Analyze the following question carefully and provide a step-by-step explanation along with the answer.
71
+ Image description : {image_description}
72
+ Question: {user_question}?
73
+ """
74
+
75
+ prompt_template = PromptTemplate(
76
+ input_variables=["user_question","image_description"], # Define the placeholder(s) in the template
77
+ template=template
78
+ )
79
+ formatted_prompt = prompt_template.format(user_question=user_question, image_description=image_description)
80
+
81
+ # Pass the formatted prompt to the model
82
+ response = math_llm(formatted_prompt)
83
+
84
+ # Print the response
85
+ yield response
86
+
87
+ def math_chat_bot(image, sketchpad, question, state):
88
+ current_tab_index = state["tab_index"]
89
+ image_description = None
90
+ # Upload
91
+ if current_tab_index == 0:
92
+ if image is not None:
93
+ image_description = process_image(image)
94
+ # Sketch
95
+ elif current_tab_index == 1:
96
+ print(sketchpad)
97
+ if sketchpad and sketchpad["composite"]:
98
+ image_description = process_image(sketchpad["composite"], True)
99
+ yield from get_math_response(image_description, question)
100
+ css = """
101
+ #qwen-md .katex-display { display: inline; }
102
+ #qwen-md .katex-display>.katex { display: inline; }
103
+ #qwen-md .katex-display>.katex>.katex-html { display: inline; }
104
+ """
105
+ def tabs_select(e: gr.SelectData, _state):
106
+ _state["tab_index"] = e.index
107
+
108
+ with gr.Blocks(css=css) as demo:
109
+
110
+ state = gr.State({"tab_index": 0})
111
+ with gr.Row():
112
+ with gr.Column():
113
+ with gr.Tabs() as input_tabs:
114
+ with gr.Tab("Upload"):
115
+ input_image = gr.Image(type="pil", label="Upload"),
116
+ with gr.Tab("Sketch"):
117
+ input_sketchpad = gr.Sketchpad(type="pil", label="Sketch", layers=False)
118
+ input_tabs.select(fn=tabs_select, inputs=[state])
119
+ input_text = gr.Textbox(label="input your question")
120
+ with gr.Row():
121
+ with gr.Column():
122
+ clear_btn = gr.ClearButton(
123
+ [*input_image, input_sketchpad, input_text])
124
+ with gr.Column():
125
+ submit_btn = gr.Button("Submit", variant="primary")
126
+ with gr.Column():
127
+ output_md = gr.Markdown(label="answer",
128
+ latex_delimiters=[{
129
+ "left": "\\(",
130
+ "right": "\\)",
131
+ "display": True
132
+ }, {
133
+ "left": "\\begin\{equation\}",
134
+ "right": "\\end\{equation\}",
135
+ "display": True
136
+ }, {
137
+ "left": "\\begin\{align\}",
138
+ "right": "\\end\{align\}",
139
+ "display": True
140
+ }, {
141
+ "left": "\\begin\{alignat\}",
142
+ "right": "\\end\{alignat\}",
143
+ "display": True
144
+ }, {
145
+ "left": "\\begin\{gather\}",
146
+ "right": "\\end\{gather\}",
147
+ "display": True
148
+ }, {
149
+ "left": "\\begin\{CD\}",
150
+ "right": "\\end\{CD\}",
151
+ "display": True
152
+ }, {
153
+ "left": "\\[",
154
+ "right": "\\]",
155
+ "display": True
156
+ }],
157
+ elem_id="qwen-md")
158
+ submit_btn.click(
159
+ fn=math_chat_bot,
160
+ inputs=[*input_image, input_sketchpad, input_text, state],
161
+ outputs=output_md)
162
  demo.launch()