kz919 commited on
Commit
8ec545b
·
verified ·
1 Parent(s): a22ebc0

Create app.py

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