File size: 3,423 Bytes
296c0a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import anthropic
import base64
import gradio as gr
import mimetypes

def generate_playground_link(code):
    """
    Generate a Gradio app link from the code.
    """
    base64_code = base64.b64encode(code.encode()).decode()
    return f"https://www.gradio.app/playground?code={base64_code}&reqs=&demo=Blank"

def extract_code(message):
    """
    Extract the code from a message that is formatted in Markdown with triple backticks.
    Include the triple backticks in the return value.
    """
    return message.split('```python')[1].split('```')[0]


def get_response(data, history):
    """
    Get a response from the Anthropic API based on the image and user message.
    """
    client = anthropic.Anthropic()
    response = []
    if data["files"]:
        response.append("Generating Gradio app based on the image...")
        yield response
        image = data["files"][0]  # str filepath
        image_data = base64.standard_b64encode(open(image, "rb").read()).decode("utf-8")
        image_media_type = mimetypes.guess_type(image)[0]
        message = client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=1024,
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image",
                            "source": {
                                "type": "base64",
                                "media_type": image_media_type,
                                "data": image_data,
                            },
                        },
                        {
                            "type": "text",
                            "text": "Based on the screenshot, write the Python code to generate this Gradio app. Try to recreate the Gradio UI, not necessarily the underlying data or machine learning model. Respond in Markdown enclosing the code in triple backticks."
                        }
                    ],
                }
            ],
        )
    else:
        response.append("Generating Gradio app based on the description...")
        yield response
        request = data["text"]
        message = client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=1024,
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text": request
                        },
                        {
                            "type": "text",
                            "text": "Based on the user's request, write the Python code to generate this Gradio app. Focus on the Gradio UI, not necessarily the underlying data or machine learning model. Respond in Markdown enclosing the code in triple backticks."
                        }
                    ],
                }
            ],
        )
    code = extract_code(message.content[0].text)
    formatted_code = f"```python\n{code}\n```"
    response.append(formatted_code)
    yield response
    response.append("[Try it out in the Gradio playground](" + generate_playground_link(code) + ")")
    yield response


demo = gr.ChatInterface(
    get_response, 
    type="messages", 
    multimodal=True,
    title="Gradio Playground Bot",
)

if __name__ == "__main__":
    demo.launch()