mistpe commited on
Commit
4b1765d
1 Parent(s): 47c46ec

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +208 -0
app.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from flask import Flask, request, jsonify, send_file
3
+ import logging
4
+ import re
5
+ import os
6
+ import time
7
+ import plotly.graph_objects as go
8
+ import numpy as np
9
+ from mpl_toolkits.mplot3d import Axes3D
10
+ import matplotlib.pyplot as plt
11
+ from io import BytesIO
12
+ import matplotlib
13
+ matplotlib.use('Agg')
14
+
15
+ app = Flask(__name__)
16
+ app.static_folder = 'static'
17
+ logging.basicConfig(level=logging.DEBUG)
18
+
19
+ @app.route('/v2/images/generations', methods=['POST'])
20
+ def generate_image_cf():
21
+ # 获取前端请求中的数据
22
+ data = request.json
23
+ logging.debug(f"Received request data: {data}")
24
+
25
+ # 提取 Cloudflare 账户 ID 和 API 令牌
26
+ cloudflare_account_id = data.get('CLOUDFLARE_ACCOUNT_ID')
27
+ cloudflare_api_token = data.get('cloudflare_api_token')
28
+ prompt = data.get('prompt')
29
+
30
+ if not cloudflare_account_id or not cloudflare_api_token or not prompt:
31
+ return jsonify({'error': 'Missing required parameters'}), 400
32
+
33
+ # 构造 Cloudflare API 请求
34
+ url = f"https://api.cloudflare.com/client/v4/accounts/{cloudflare_account_id}/ai/run/@cf/stabilityai/stable-diffusion-xl-base-1.0"
35
+ headers = {"Authorization": f"Bearer {cloudflare_api_token}"}
36
+ payload = {"prompt": prompt}
37
+
38
+ # 发送请求到 Cloudflare API
39
+ response = requests.post(url, headers=headers, json=payload)
40
+ logging.debug(f"Response status code: {response.status_code}")
41
+
42
+ # 检查响应状态码
43
+ if response.status_code != 200:
44
+ return jsonify({'error': 'Failed to generate image'}), response.status_code
45
+
46
+ # 获取完整的响应内容
47
+ response_data = response.content
48
+ logging.debug(f"Response content: {response_data}")
49
+
50
+ # 生成图像文件名
51
+ img_filename = f'image_{int(time.time())}.png'
52
+ save_path = os.path.join(app.static_folder, img_filename)
53
+
54
+ # 将图像保存到 'static' 目录
55
+ with open(save_path, 'wb') as f:
56
+ f.write(response_data)
57
+
58
+ # 构造返回给前端的数据
59
+ img_url = f'https://mistpe-flask.hf.space/static/{img_filename}'
60
+ result = {
61
+ "created": int(time.time()),
62
+ "data": [
63
+ {"url": img_url}
64
+ ]
65
+ }
66
+ return jsonify(result)
67
+
68
+ def preprocess_prompt(prompt):
69
+ # 使用非捕获组 (?:...) 来匹配任意字符
70
+ pattern = r'@startmindmap\n((?:.*?\n)*?)@endmindmap'
71
+ match = re.search(pattern, prompt, re.DOTALL)
72
+ if (match):
73
+ mindmap_content = match.group(1)
74
+ processed_prompt = f"@startmindmap\n{mindmap_content}\n@endmindmap"
75
+ else:
76
+ processed_prompt = prompt
77
+ return processed_prompt
78
+
79
+ @app.route('/v1/images/generations', methods=['POST'])
80
+ def generate_image_plantuml():
81
+ # 获取前端请求中的数据
82
+ data = request.json
83
+ logging.debug(f"Received request data: {data}")
84
+
85
+ # 预处理 prompt
86
+ processed_prompt = preprocess_prompt(data['prompt'])
87
+ logging.debug(f"Processed prompt: {processed_prompt}")
88
+
89
+ # 将数据发送到 https://mistpe-plantuml.hf.space/coder 接口
90
+ response = requests.post('https://mistpe-plantuml.hf.space/coder', data=processed_prompt.encode('utf-8'))
91
+ logging.debug(f"Response status code: {response.status_code}")
92
+
93
+ # 检查响应状态码
94
+ if response.status_code != 200:
95
+ return jsonify({'error': 'Failed to generate image'}), response.status_code
96
+
97
+ # 获取完整的响应内容
98
+ response_data = response.content
99
+ logging.debug(f"Response content: {response_data}")
100
+
101
+ created = 1589478378 # 假设这是一个固定值
102
+ url = f"https://mistpe-plantuml.hf.space/png/{response_data.decode('utf-8')}"
103
+
104
+ # 构造返回给前端的数据
105
+ result = {
106
+ "created": created,
107
+ "data": [
108
+ {
109
+ "url": url
110
+ }
111
+ ]
112
+ }
113
+ return jsonify(result)
114
+
115
+ @app.route('/api/3d-surface', methods=['POST'])
116
+ def generate_3d_surface():
117
+ data = request.json
118
+ prompt = data['prompt']
119
+
120
+ # 提取#start和#end之间的代码
121
+ start_index = prompt.find("#start") + len("#start")
122
+ end_index = prompt.find("#end")
123
+ code = prompt[start_index:end_index].strip()
124
+
125
+ # 创建一个字典来存储局部变量
126
+ local_vars = {}
127
+
128
+ # 执行前端传入的代码,并传入局部变量字典
129
+ exec(code, globals(), local_vars)
130
+
131
+ # 从局部变量字典中获取 'fig' 对象
132
+ fig = local_vars.get('fig')
133
+
134
+ # 检查 'fig' 是否已定义
135
+ if fig is None:
136
+ return jsonify({"error": "No figure 'fig' defined in the provided code."}), 400
137
+
138
+ # 保存图表为 HTML 文件
139
+ html_filename = f'3d_surface_plot_{int(time.time())}.html'
140
+ fig.write_html(f'static/{html_filename}')
141
+
142
+ # 构建 HTML 文件的 URL
143
+ html_url = f'https://mistpe-flask.hf.space/static/{html_filename}'
144
+
145
+ # 保存 fig 对象为图像文件
146
+ img_filename = f'3d_surface_plot_{int(time.time())}.png'
147
+ fig.write_image(f'static/{img_filename}')
148
+
149
+ # 构建图像文件的 URL
150
+ img_url = f'https://mistpe-flask.hf.space/static/{img_filename}'
151
+
152
+ # 返回 JSON 格式的响应, 包含 HTML 和图像的访问链接
153
+ return jsonify({
154
+ "created": int(time.time()),
155
+ "data": [
156
+ {"url": img_url},
157
+ {"url": html_url}
158
+ ]
159
+ })
160
+
161
+ @app.route('/api/3d-sphere', methods=['POST'])
162
+ def generate_3d_sphere():
163
+ # 获取请求中的代码
164
+ code = request.json['prompt']
165
+
166
+ # 判断代码是否以'''python开头和'''结尾
167
+ if code.startswith("```python") and code.endswith("```"):
168
+ # 如果是,则删除开头和结尾的字符串
169
+ code = '\n'.join(code.split('\n')[1:-1])
170
+
171
+ # 在主线程中执行代码生成 3D 图像
172
+ fig = plt.figure()
173
+ ax = fig.add_subplot(111, projection='3d')
174
+ exec(code)
175
+
176
+ # 将 3D 图像保存为 PNG 格式
177
+ buf = BytesIO()
178
+ plt.savefig(buf, format='png')
179
+ buf.seek(0)
180
+
181
+ # 生成图像文件名
182
+ img_filename = f'3d_sphere_{int(time.time())}.png'
183
+ save_path = os.path.join(app.static_folder, img_filename)
184
+
185
+ # 将图像保存到 'static' 目录
186
+ with open(save_path, 'wb') as f:
187
+ f.write(buf.getvalue())
188
+
189
+ # 返回 JSON 格式的响应,包含图像的访问链接
190
+ img_url = f'https://mistpe-flask.hf.space/static/{img_filename}'
191
+ return {
192
+ "created": int(time.time()),
193
+ "data": [
194
+ {
195
+ "url": img_url
196
+ }
197
+ ]
198
+ }
199
+
200
+ @app.route('/', methods=['POST'])
201
+ def health_check():
202
+ return jsonify({'status': 'OK'}), 200
203
+
204
+ if __name__ == '__main__':
205
+ # 确保 static 目录存在
206
+ if not os.path.exists('static'):
207
+ os.makedirs('static')
208
+ app.run(host='0.0.0.0', port=7860, debug=True)