akhaliq HF staff commited on
Commit
9dc7fb7
1 Parent(s): 82ee039

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -45
app.py CHANGED
@@ -5,21 +5,14 @@ import base64
5
  from io import BytesIO
6
  from PIL import Image
7
  import numpy as np
8
- import json
9
 
10
  # Initialize the Together client
11
  api_key = os.environ.get('TOGETHER_API_KEY')
12
- client = None
13
-
14
- if api_key:
15
- try:
16
- client = Together(api_key=api_key)
17
- except Exception as e:
18
- print(f"Error initializing Together client: {e}")
19
 
20
  def generate_gradio_app(image):
21
- if not api_key or not client:
22
- return "Error: TOGETHER_API_KEY not set or client initialization failed. Please check your API key."
23
 
24
  try:
25
  # Convert numpy array to PIL Image
@@ -31,65 +24,53 @@ def generate_gradio_app(image):
31
  image.save(buffered, format="PNG")
32
  img_str = base64.b64encode(buffered.getvalue()).decode()
33
 
34
- # Prepare the messages for the API call
35
- system_message = "You are an AI assistant that can analyze wireframe images and generate detailed Gradio code based on their content."
36
- user_message = f"""
37
- <image>
38
- data:image/png;base64,{img_str}
39
- </image>
40
-
41
- Analyze this wireframe image and generate a complete Python code using Gradio that recreates all the main elements seen in the image. Provide a complete, runnable Gradio application.
42
- """
43
-
44
- messages = [
45
- {"role": "system", "content": system_message},
46
- {"role": "user", "content": user_message}
47
- ]
48
-
49
  # Make the API call
50
  response = client.chat.completions.create(
51
  model="meta-llama/Llama-Vision-Free",
52
- messages=messages,
53
- max_tokens=5000,
54
  temperature=0.7,
55
  top_p=0.7,
56
  top_k=50,
57
  repetition_penalty=1,
 
 
58
  )
59
 
60
- # Extract the generated code from the response
61
- generated_code = response.choices[0].message.content
62
- return generated_code
 
 
 
 
63
 
64
  except Exception as e:
65
  error_message = str(e)
66
- if "400" in error_message:
67
- return "Error 400: Bad Request. The API request was invalid. Please check your input and try again."
68
- elif "401" in error_message:
69
- return "Error 401: Unauthorized. Please check your API key and ensure it's correctly set."
70
- elif "429" in error_message:
71
- return "Error 429: Too Many Requests. Please wait a moment and try again."
72
- elif "500" in error_message:
73
- return "Error 500: Internal Server Error. There's an issue with the API service. Please try again later."
74
- else:
75
- return f"An unexpected error occurred: {error_message}\nPlease try again or contact support if the issue persists."
76
 
77
  with gr.Blocks() as demo:
78
- gr.Markdown("# Turn your wireframe into a Gradio app")
79
- gr.Markdown("Upload an image of your UI design and we'll build a Gradio app for you.")
80
 
81
  with gr.Row():
82
  with gr.Column(scale=1):
83
  image_input = gr.Image(label="Upload a screenshot", elem_id="image_upload")
84
- generate_button = gr.Button("Generate Gradio app", variant="primary")
85
 
86
  with gr.Column(scale=2):
87
- code_output = gr.Code(language="python", label="Generated Gradio Code", lines=30)
88
 
89
  generate_button.click(
90
  fn=generate_gradio_app,
91
  inputs=[image_input],
92
- outputs=[code_output]
93
  )
94
 
95
  demo.launch()
 
5
  from io import BytesIO
6
  from PIL import Image
7
  import numpy as np
 
8
 
9
  # Initialize the Together client
10
  api_key = os.environ.get('TOGETHER_API_KEY')
11
+ client = Together(api_key=api_key)
 
 
 
 
 
 
12
 
13
  def generate_gradio_app(image):
14
+ if not api_key:
15
+ return "Error: TOGETHER_API_KEY not set. Please check your API key."
16
 
17
  try:
18
  # Convert numpy array to PIL Image
 
24
  image.save(buffered, format="PNG")
25
  img_str = base64.b64encode(buffered.getvalue()).decode()
26
 
27
+ # Prepare the message for the API call
28
+ # Using the format: <image>{base64_image}</image>\nHuman: {prompt}\nAssistant:
29
+ message = f"""<image>{img_str}</image>
30
+ Human: Analyze this wireframe image and suggest a simple Gradio app layout based on it. Describe the main elements you see and how they could be implemented using Gradio components.
31
+ Assistant: Certainly! I'll analyze the wireframe image and suggest a simple Gradio app layout based on what I see. Let me describe the main elements and how they could be implemented using Gradio components."""
32
+
 
 
 
 
 
 
 
 
 
33
  # Make the API call
34
  response = client.chat.completions.create(
35
  model="meta-llama/Llama-Vision-Free",
36
+ messages=[{"role": "user", "content": message}],
37
+ max_tokens=512,
38
  temperature=0.7,
39
  top_p=0.7,
40
  top_k=50,
41
  repetition_penalty=1,
42
+ stop=["<|eot_id|>", "<|eom_id|>"],
43
+ stream=True
44
  )
45
 
46
+ # Collect the streamed response
47
+ generated_text = ""
48
+ for chunk in response:
49
+ if chunk.choices[0].delta.content is not None:
50
+ generated_text += chunk.choices[0].delta.content
51
+
52
+ return generated_text
53
 
54
  except Exception as e:
55
  error_message = str(e)
56
+ return f"An error occurred: {error_message}\nPlease try again or check your API key and connection."
 
 
 
 
 
 
 
 
 
57
 
58
  with gr.Blocks() as demo:
59
+ gr.Markdown("# Analyze wireframe and suggest Gradio app layout")
60
+ gr.Markdown("Upload an image of your UI design for analysis and suggestions.")
61
 
62
  with gr.Row():
63
  with gr.Column(scale=1):
64
  image_input = gr.Image(label="Upload a screenshot", elem_id="image_upload")
65
+ generate_button = gr.Button("Analyze and Suggest", variant="primary")
66
 
67
  with gr.Column(scale=2):
68
+ text_output = gr.Textbox(label="Analysis and Suggestions", lines=10)
69
 
70
  generate_button.click(
71
  fn=generate_gradio_app,
72
  inputs=[image_input],
73
+ outputs=[text_output]
74
  )
75
 
76
  demo.launch()