Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import openai
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
import io
|
5 |
+
import numpy as np
|
6 |
+
import base64
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
# 将图像转换为 base64,以便在 gradio 中显示
|
10 |
+
def get_image_data(plt):
|
11 |
+
buf = io.BytesIO()
|
12 |
+
plt.savefig(buf, format='PNG')
|
13 |
+
buf.seek(0)
|
14 |
+
img = Image.open(buf)
|
15 |
+
return img
|
16 |
+
|
17 |
+
# 执行 Python 代码并生成图像
|
18 |
+
def execute_code(code):
|
19 |
+
exec(code)
|
20 |
+
return get_image_data(plt)
|
21 |
+
|
22 |
+
openai.api_key = 'your-openai-key'
|
23 |
+
|
24 |
+
def gpt3_inference(prompt):
|
25 |
+
response = openai.Completion.create(
|
26 |
+
engine="text-davinci-002",
|
27 |
+
prompt=prompt,
|
28 |
+
max_tokens=100
|
29 |
+
)
|
30 |
+
code = response.choices[0].text.strip()
|
31 |
+
img = execute_code(code)
|
32 |
+
return img
|
33 |
+
|
34 |
+
iface = gr.Interface(fn=gpt3_inference, inputs="text", outputs="image")
|
35 |
+
iface.launch()
|