root commited on
Commit
92e38f5
1 Parent(s): 178c449

Update space

Browse files
Files changed (1) hide show
  1. app.py +91 -184
app.py CHANGED
@@ -1,190 +1,97 @@
1
  import gradio as gr
2
- #from huggingface_hub import InferenceClient
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- #from new_chat import Conversation, ChatgptAPI
8
-
9
- import os
10
- from pathlib import Path
11
- from openai import OpenAI
12
-
13
- class ChatgptAPI:
14
- def __init__(self, ):
15
- self.client = OpenAI(
16
- api_key = os.environ.get("OPENAI_API_KEY"),
17
- base_url = "https://api.moonshot.cn/v1",
18
- )
19
- def get_single_round_completion(self, file_path, prompt, conversation):
20
- conversation.append_question(prompt)
21
- file_object = self.client.files.create(file=Path(file_path), purpose="file-extract")
22
- file_content = self.client.files.content(file_id=file_object.id).text
23
- messages = [
24
- {
25
- "role": "system",
26
- "content": "你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。",
27
- },
28
- {
29
- "role": "system",
30
- "content": file_content,
31
- },
32
- {"role": "user", "content": prompt},
33
- ]
34
- completion = self.client.chat.completions.create(
35
- model="moonshot-v1-32k",
36
- messages=messages,
37
- temperature=0.3,
38
- )
39
- message=completion.choices[0].message.content
40
- conversation.append_answer(message)
41
- return message, conversation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
-
44
- def get_multi_round_completion(self, prompt, conversation, model='gpt-3.5-turbo'):
45
- conversation.append_question(prompt)
46
- prompts = conversation.get_prompts()
47
-
48
- response = openai.ChatCompletion.create(
49
- model=model,
50
- messages=prompts,
51
- temperature=0,
52
- max_tokens=2048,
53
- top_p=1,
54
- )
55
- message = response.choices[0].message['content']
56
- conversation.append_answer(message)
57
-
58
- return message, conversation
59
-
60
- class Conversation:
61
- def __init__(self, system_prompt='iii', num_of_round = 5):
62
- self.num_of_round = num_of_round
63
- self.history = []
64
- self.initialized = False
65
- self.history.append({"role": "system", "content": system_prompt})
66
-
67
- if len(system_prompt) > 0:
68
- #logger.info(f'Conversation initialized with system prompt: {system_prompt}')
69
- self.initialized = True
70
-
71
- def is_initialized(self):
72
- return self.initialized
73
-
74
- def append_question(self, question):
75
- self.history.append({"role": "user", "content": question})
76
-
77
- def append_answer(self, answer):
78
- self.history.append({"role": "assistant", "content": answer})
79
-
80
- if len(self.history) > self.num_of_round * 2:
81
- del self.history[1:3]
82
-
83
- def clear(self):
84
- self.history.clear()
85
- self.initialized = False
86
-
87
- def get_prompts(self):
88
- return self.history
89
-
90
- def round_size(self):
91
- return 0 if len(self.history) < 2 else len(self.hitory) - 1
92
-
93
- def get_history_messages(self):
94
- return [(u['content'], b['content']) for u,b in zip(self.history[1::2], self.history[2::2])]
95
-
96
-
97
-
98
- chat_api = ChatgptAPI()
99
-
100
- def predict(system_input, password_input, user_in_file, user_input, conversation):
101
- if password_input != os.environ.get("USER_KEY"):
102
- return [(None, "Wrong password!")], conversation, user_input
103
-
104
- if conversation.is_initialized() == False:
105
- conversation = Conversation(system_input, 5)
106
- _, conversation = chat_api.get_single_round_completion(user_in_file, user_input, conversation)
107
- return conversation.get_history_messages(), conversation, None
108
- #_, conversation = chat_api.get_multi_round_completion(user_input, conversation)
109
- #return conversation.get_history_messages(), conversation, None
110
-
111
-
112
- def clear_history(conversation):
113
- conversation.clear()
114
- return None, conversation
115
-
116
-
117
- with gr.Blocks(css="#chatbot{height:350px} .overflow-y-auto{height:600px}") as demo:
118
- chatbot = gr.Chatbot(elem_id="chatbot")
119
- conversation = gr.State(value=Conversation())
120
-
121
- with gr.Row():
122
- system_in_txt = gr.Textbox(lines=1, label="User Name:", placeholder="Enter user name")
123
- password_in_txt = gr.Textbox(lines=1, label="Password:", placeholder="Enter password")
124
-
125
- with gr.Row():
126
- user_in_file = gr.File(label="Upload File")
127
- user_in_txt = gr.Textbox(lines=3, label="User role content:", placeholder="Enter text...", container=False)
128
-
129
- with gr.Row():
130
- reset_button = gr.Button("Reset")
131
- submit_button = gr.Button("Submit")
132
-
133
- submit_button.click(predict, [system_in_txt, password_in_txt, user_in_file, user_in_txt, conversation], [chatbot, conversation, user_in_txt])
134
- reset_button.click(clear_history, [conversation], [chatbot, conversation], queue=False)
135
-
136
- '''
137
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
138
-
139
-
140
- def respond(
141
- message,
142
- history: list[tuple[str, str]],
143
- system_message,
144
- max_tokens,
145
- temperature,
146
- top_p,
147
- ):
148
- messages = [{"role": "system", "content": system_message}]
149
-
150
- for val in history:
151
- if val[0]:
152
- messages.append({"role": "user", "content": val[0]})
153
- if val[1]:
154
- messages.append({"role": "assistant", "content": val[1]})
155
-
156
- messages.append({"role": "user", "content": message})
157
-
158
- response = ""
159
-
160
- for message in client.chat_completion(
161
- messages,
162
- max_tokens=max_tokens,
163
- stream=True,
164
- temperature=temperature,
165
- top_p=top_p,
166
- ):
167
- token = message.choices[0].delta.content
168
-
169
- response += token
170
- yield response
171
 
172
- demo = gr.ChatInterface(
173
- respond,
174
- additional_inputs=[
175
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
176
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
177
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
178
- gr.Slider(
179
- minimum=0.1,
180
- maximum=1.0,
181
- value=0.95,
182
- step=0.05,
183
- label="Top-p (nucleus sampling)",
184
- ),
185
- ],
 
186
  )
187
- '''
188
 
189
- if __name__ == "__main__":
190
- demo.launch()
 
1
  import gradio as gr
 
2
 
3
+ # 自定义HTML/CSS/JavaScript
4
+ custom_html = """
5
+ <style>
6
+ body {
7
+ font-family: Arial, sans-serif;
8
+ background-color: #f0f0f0;
9
+ }
10
+ .container {
11
+ max-width: 800px;
12
+ margin: 0 auto;
13
+ padding: 20px;
14
+ background-color: white;
15
+ border-radius: 10px;
16
+ box-shadow: 0 0 10px rgba(0,0,0,0.1);
17
+ }
18
+ h1 {
19
+ color: #333;
20
+ }
21
+ #custom-button {
22
+ background-color: #4CAF50;
23
+ border: none;
24
+ color: white;
25
+ padding: 15px 32px;
26
+ text-align: center;
27
+ text-decoration: none;
28
+ display: inline-block;
29
+ font-size: 16px;
30
+ margin: 4px 2px;
31
+ cursor: pointer;
32
+ }
33
+ #update-area {
34
+ margin-top: 20px;
35
+ padding: 10px;
36
+ border: 1px solid #ddd;
37
+ }
38
+ </style>
39
+
40
+ <div class="container">
41
+ <h1>动态更新界面示例</h1>
42
+ <button id="custom-button" onclick="updateInterface()">更新界面</button>
43
+ <div id="update-area">
44
+ 点击按钮来更新这里的内容
45
+ </div>
46
+ </div>
47
+
48
+ <script>
49
+ function updateInterface() {
50
+ // 调用Gradio函数
51
+ var gradioApp = document.querySelector("gradio-app");
52
+ if (gradioApp == null) gradioApp = document.querySelector("body > gradio-app");
53
+ gradioApp.querySelector("#component-0").querySelector("button").click();
54
+ }
55
+
56
+ // 监听Gradio输出的变化
57
+ document.addEventListener('DOMContentLoaded', (event) => {
58
+ var gradioApp = document.querySelector("gradio-app");
59
+ if (gradioApp == null) gradioApp = document.querySelector("body > gradio-app");
60
+ var outputElement = gradioApp.querySelector("#component-2");
61
 
62
+ var observer = new MutationObserver(function(mutations) {
63
+ mutations.forEach(function(mutation) {
64
+ if (mutation.type === "childList") {
65
+ document.getElementById("update-area").innerHTML = outputElement.textContent;
66
+ }
67
+ });
68
+ });
69
+
70
+ var config = { childList: true, subtree: true };
71
+ observer.observe(outputElement, config);
72
+ });
73
+ </script>
74
+
75
+ <!-- Gradio组件将被插入到这里 -->
76
+ <div id="gradio-app"></div>
77
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
+ # Gradio函数
80
+ def update_content():
81
+ import datetime
82
+ current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
83
+ return f"界面已更新,当前时间: {current_time}"
84
+
85
+ # 创建Gradio界面
86
+ iface = gr.Interface(
87
+ fn=update_content,
88
+ inputs=[],
89
+ outputs="text",
90
+ title=None,
91
+ description=None,
92
+ article=None,
93
+ layout="vertical"
94
  )
 
95
 
96
+
97
+ iface.launch(inline=False, share=True, html=custom_html)