ItsBadForYa commited on
Commit
6437228
·
verified ·
1 Parent(s): 57cf5a0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -0
app.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import os
4
+ import json
5
+
6
+ # 从刚才设置的保险箱中安全读取密钥
7
+ API_KEY = os.environ.get("COZE_API_KEY")
8
+ BOT_ID = os.environ.get("COZE_BOT_ID")
9
+
10
+ def generate_image(prompt):
11
+ if not API_KEY or not BOT_ID:
12
+ return None, "系统错误:未配置 API_KEY 或 BOT_ID"
13
+
14
+ # 扣子 v3 API 的标准请求地址 (国内版为 api.coze.cn)
15
+ url = "https://api.coze.cn/v3/chat"
16
+
17
+ headers = {
18
+ "Authorization": f"Bearer {API_KEY}",
19
+ "Content-Type": "application/json"
20
+ }
21
+
22
+ # 构造发送给扣子的数据
23
+ payload = {
24
+ "bot_id": BOT_ID,
25
+ "user_id": "gradio_user_001", # 可以自定义一个用户ID
26
+ "stream": False, # 为了简单,我们不使用流式输出
27
+ "auto_save_history": True,
28
+ "additional_messages": [
29
+ {
30
+ "role": "user",
31
+ "content": prompt,
32
+ "content_type": "text"
33
+ }
34
+ ]
35
+ }
36
+
37
+ try:
38
+ # 发送请求给扣子
39
+ response = requests.post(url, headers=headers, json=payload)
40
+ response.raise_for_status()
41
+ data = response.json()
42
+
43
+ # 解析扣子返回的数据,提取图片 URL
44
+ # 注意:这里的解析逻辑可能需要根据你扣子工作流的实际返回格式微调
45
+ messages = data.get("data", {}).get("messages", [])
46
+ for msg in messages:
47
+ if msg.get("type") == "answer":
48
+ # 假设你的工作流直接返回了包含图片 Markdown 或 URL 的文本
49
+ # 如果是 Markdown 格式的图片 ![image](url),可以直接被 Gradio 识别
50
+ # 这里我们简单地将扣子的回复原样返回
51
+ return msg.get("content"), "生成成功!"
52
+
53
+ return None, "未能从扣子获取到图片,请检查工作流配置。"
54
+
55
+ except Exception as e:
56
+ return None, f"请求失败: {str(e)}"
57
+
58
+ # 使用 Gradio Blocks 搭建精美界面
59
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
60
+ gr.Markdown("# 🎨 我的专属 AI 绘图工作站")
61
+ gr.Markdown("输入画面描述,调用云端扣子工作流生成高质量图像。")
62
+
63
+ with gr.Row():
64
+ with gr.Column(scale=1):
65
+ prompt_input = gr.Textbox(
66
+ label="画面描述 (Prompt)",
67
+ placeholder="例如:一只赛博朋克风格的机械猫,霓虹灯背景,8k分辨率...",
68
+ lines=5
69
+ )
70
+ submit_btn = gr.Button("🚀 开始生成", variant="primary")
71
+ status_output = gr.Textbox(label="运行状态", interactive=False)
72
+
73
+ with gr.Column(scale=1):
74
+ # 如果你的扣子返回的是纯图片 URL,这里用 gr.Image
75
+ # 如果返回的是包含图片的 Markdown 文本,建议用 gr.Markdown
76
+ image_output = gr.Markdown(label="生成结果")
77
+
78
+ # 绑定按钮点击事件
79
+ submit_btn.click(
80
+ fn=generate_image,
81
+ inputs=[prompt_input],
82
+ outputs=[image_output, status_output]
83
+ )
84
+
85
+ # 启动应用
86
+ demo.launch()