Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from together import Together
|
| 4 |
+
import base64
|
| 5 |
+
|
| 6 |
+
# Initialize the Together client
|
| 7 |
+
client = Together(api_key=os.environ.get('TOGETHER_API_KEY'))
|
| 8 |
+
|
| 9 |
+
def process_image(image):
|
| 10 |
+
# Convert the image to base64
|
| 11 |
+
buffered = BytesIO()
|
| 12 |
+
image.save(buffered, format="PNG")
|
| 13 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 14 |
+
|
| 15 |
+
# Prepare the messages for the API call
|
| 16 |
+
messages = [
|
| 17 |
+
{"role": "system", "content": "You are an AI assistant that can analyze images and generate code based on their content."},
|
| 18 |
+
{"role": "user", "content": [
|
| 19 |
+
{"type": "image_url", "image_url": f"data:image/png;base64,{img_str}"},
|
| 20 |
+
{"type": "text", "text": "Analyze this image and generate Python code that could recreate or represent the main elements seen in the image."}
|
| 21 |
+
]}
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
# Make the API call
|
| 25 |
+
response = client.chat.completions.create(
|
| 26 |
+
model="meta-llama/Llama-Vision-Free",
|
| 27 |
+
messages=messages,
|
| 28 |
+
max_tokens=512,
|
| 29 |
+
temperature=0.7,
|
| 30 |
+
top_p=0.7,
|
| 31 |
+
top_k=50,
|
| 32 |
+
repetition_penalty=1,
|
| 33 |
+
stop=["<|eot_id|>", "<|eom_id|>"]
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Extract the generated code from the response
|
| 37 |
+
generated_code = response.choices[0].message.content
|
| 38 |
+
|
| 39 |
+
# Generate HTML to display the code with syntax highlighting
|
| 40 |
+
html_output = f"""
|
| 41 |
+
<pre><code class="language-python">{generated_code}</code></pre>
|
| 42 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
|
| 43 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
|
| 44 |
+
<script>hljs.highlightAll();</script>
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
return html_output
|
| 48 |
+
|
| 49 |
+
# Create the Gradio interface
|
| 50 |
+
iface = gr.Interface(
|
| 51 |
+
fn=process_image,
|
| 52 |
+
inputs=gr.Image(type="pil"),
|
| 53 |
+
outputs=gr.HTML(),
|
| 54 |
+
title="Llama Vision Free Code Generation",
|
| 55 |
+
description="Upload an image, and this demo will use the Llama Vision Free model to analyze it and generate relevant Python code."
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Launch the interface
|
| 59 |
+
iface.launch()
|