kz919 commited on
Commit
189d2e5
·
verified ·
1 Parent(s): 344632c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -0
app.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import base64
3
+ import requests
4
+ import io
5
+ from PIL import Image
6
+ import numpy as np
7
+
8
+ API_KEY = os.environ['API_KEY']
9
+ URL = os.environ['URL']
10
+
11
+ def sketch_to_text(image):
12
+ if image is None or not isinstance(image, dict) or 'composite' not in image:
13
+ return "Please write something first."
14
+
15
+ # Extract the image data from the dictionary
16
+ image_data = image['composite']
17
+ # Convert the image data to a PIL Image
18
+ pil_image = Image.fromarray(image_data.astype(np.uint8))
19
+
20
+ # Convert the image to base64
21
+ buffered = io.BytesIO()
22
+ pil_image.save(buffered, format="PNG")
23
+ img_str = base64.b64encode(buffered.getvalue()).decode()
24
+
25
+ # Prepare the API request
26
+ headers = {
27
+ "Content-Type": "application/json",
28
+ "Authorization": f"Bearer {API_KEY}"
29
+ }
30
+ payload = {
31
+ "model": "Llama-3.2-11B-Vision-Instruct",
32
+ "messages": [
33
+ {
34
+ "role": "user",
35
+ "content": [
36
+ {
37
+ "type": "text",
38
+ "text": "Please read the forumla in the image and transcribe it into latex code, respond with code only, make sure the code is enclosed within a pair of $$"
39
+ },
40
+ {
41
+ "type": "image_url",
42
+ "image_url": {
43
+ "url": f"data:image/png;base64,{img_str}"
44
+ }
45
+ }
46
+ ]
47
+ }
48
+ ],
49
+ "max_tokens": 300
50
+ }
51
+
52
+ # Make the API request
53
+ response = requests.post(URL, headers=headers, json=payload)
54
+
55
+ if response.status_code == 200:
56
+ return response.json()["choices"][0]["message"]["content"], response.json()["choices"][0]["message"]["content"]
57
+ else:
58
+ return f"Error: {response.status_code}, {response.text}", f"Error: {response.status_code}, {response.text}"
59
+
60
+ # Create the Gradio interface
61
+ with gr.Blocks() as iface:
62
+ gr.Markdown("# Pix2Latex")
63
+ gr.Markdown("Transcribing handwritten forumla into latex with Llama3.2 instruct")
64
+
65
+ with gr.Column(scale=1):
66
+ input_image = gr.ImageEditor()
67
+
68
+ with gr.Row():
69
+ with gr.Column(scale=1):
70
+ output1 = gr.Textbox(label="Raw")
71
+ with gr.Column(scale=1):
72
+ output2 = gr.Markdown(label="Rendered")
73
+
74
+ input_image.change(fn=sketch_to_text, inputs=input_image, outputs=[output1, output2])
75
+
76
+ gr.Markdown("How to use: 1. write your formula in the box above. 2. See it in real time, have fun doing math?")
77
+
78
+ # Launch the app
79
+ iface.launch()