soiz1 commited on
Commit
2b448ee
·
verified ·
1 Parent(s): f3cbed6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -234
app.py CHANGED
@@ -1,212 +1,28 @@
1
- from flask import Flask, request, Response, render_template
2
  from huggingface_hub import hf_hub_download
3
  from llama_cpp import Llama
 
4
 
5
- app = Flask(__name__)
6
-
7
- # HTML content as a string
8
- HTML_CONTENT = '''
9
- <!DOCTYPE html>
10
- <html lang="en">
11
- <head>
12
- <meta charset="UTF-8">
13
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
14
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
15
- <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
16
- <link rel="preconnect" href="https://fonts.googleapis.com">
17
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
18
- <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap" rel="stylesheet">
19
- <title>AI Chat Interface</title>
20
- <style>
21
- *{
22
- padding: 0;
23
- margin: 0;
24
- font-family: 'Poppins', sans-serif;
25
- box-sizing: border-box;
26
- }
27
- body {
28
- overflow: hidden;
29
- }
30
-
31
- /* Hide scrollbar only for Webkit browsers (Chrome, Safari, Opera) */
32
- ::-webkit-scrollbar {
33
- display: none;
34
- }
35
-
36
- body{
37
- width: 100%;
38
- height: 100vh;
39
- background-color: #212121;
40
- }
41
-
42
- .chat{
43
- display: flex;
44
- gap: 20px;
45
- padding: 25px;
46
- color: #fff;
47
- font-size: 15px;
48
- font-weight: 300;
49
- }
50
-
51
- .chat img{
52
- width: 35px;
53
- height: 35px;
54
- border-radius: 50px;
55
- }
56
-
57
- .response{
58
- background-color: #212121;
59
- }
60
-
61
- .messagebar{
62
- position: fixed;
63
- bottom: 0;
64
- height: 5rem;
65
- width: 100%;
66
- display: flex;
67
- align-items: center;
68
- justify-content: center;
69
- background-color: #212121;
70
- }
71
-
72
- .messagebar .bar-wrapper{
73
- background-color: #2f2f2f;
74
- border-radius: 20px;
75
- width: 70vw;
76
- padding: 10px;
77
- display: flex;
78
- align-items: center;
79
- justify-content: space-between;
80
- }
81
-
82
- .bar-wrapper input{
83
- width: 100%;
84
- padding: 5px;
85
- border: none;
86
- outline: none;
87
- font-size: 14px;
88
- background: none;
89
- color: #ccc;
90
- }
91
-
92
- .bar-wrapper input::placeholder{
93
- color: #ccc;
94
- }
95
-
96
- .messagebar button{
97
- display: flex;
98
- align-items: center;
99
- justify-content: center;
100
- background: none;
101
- border: none;
102
- color: #fff;
103
- cursor: pointer;
104
- }
105
-
106
- .message-box{
107
- height: calc(100vh - 5rem);
108
- overflow-y: auto;
109
- }
110
- </style>
111
- </head>
112
- <body>
113
- <div class="chatbox-wrapper">
114
- <div class="message-box" id="chat-container">
115
- <div class="chat response">
116
- <img src="https://freelogopng.com/images/all_img/1681038800chatgpt-logo-black.png" alt="AI">
117
- <span>こんにちは! <br>
118
- どのようにお手伝いできますか?
119
- </span>
120
- </div>
121
- </div>
122
- <div class="messagebar">
123
- <div class="bar-wrapper">
124
- <input type="text" id="user-input" placeholder="Enter your message...">
125
- <button onclick="sendMessage()">
126
- <span class="material-symbols-rounded">
127
- send
128
- </span>
129
- </button>
130
- </div>
131
- </div>
132
- </div>
133
-
134
- <script>
135
- const messageBar = document.querySelector("#user-input");
136
- const sendBtn = document.querySelector(".bar-wrapper button");
137
- const messageBox = document.querySelector("#chat-container");
138
-
139
- function addMessage(message, isUser) {
140
- const messageElement = document.createElement('div');
141
- messageElement.classList.add('chat');
142
- if (!isUser) messageElement.classList.add('response');
143
-
144
- const imgElement = document.createElement('img');
145
- imgElement.src = isUser ? "https://wallpaperaccess.com/full/1595920.jpg" : "https://freelogopng.com/images/all_img/1681038800chatgpt-logo-black.png";
146
- imgElement.alt = isUser ? "User" : "AI";
147
-
148
- const spanElement = document.createElement('span');
149
- spanElement.textContent = message;
150
-
151
- messageElement.appendChild(imgElement);
152
- messageElement.appendChild(spanElement);
153
-
154
- messageBox.appendChild(messageElement);
155
- messageBox.scrollTop = messageBox.scrollHeight;
156
- }
157
-
158
- function sendMessage() {
159
- const message = messageBar.value.trim();
160
- if (message) {
161
- addMessage(message, true);
162
- messageBar.value = '';
163
-
164
- const eventSource = new EventSource(`/chat?message=${encodeURIComponent(message)}`);
165
- let aiResponse = '';
166
-
167
- eventSource.onmessage = function(event) {
168
- if (event.data === '[DONE]') {
169
- eventSource.close();
170
- } else {
171
- aiResponse += event.data;
172
- const aiMessageElement = document.querySelector('.chat.response:last-child span');
173
- if (aiMessageElement) {
174
- aiMessageElement.textContent = aiResponse;
175
- } else {
176
- addMessage(aiResponse, false);
177
- }
178
- }
179
- };
180
-
181
- eventSource.onerror = function(error) {
182
- console.error('EventSource failed:', error);
183
- eventSource.close();
184
- };
185
- }
186
- }
187
-
188
- messageBar.addEventListener('keypress', function(event) {
189
- if (event.key === 'Enter') {
190
- sendMessage();
191
- }
192
- });
193
- </script>
194
- </body>
195
- </html>
196
- '''
197
  def download_model():
198
  model_name = "bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF"
199
- model_file = "DeepSeek-Coder-V2-Lite-Instruct-Q6_K.gguf" # or another quantized version
200
- return hf_hub_download(repo_id=model_name, filename=model_file)
 
 
 
 
201
 
202
  def initialize_model():
203
  try:
204
  model_path = download_model()
 
 
205
  return Llama(
206
  model_path=model_path,
207
  n_ctx=4096,
208
  n_threads=4,
209
- n_gpu_layers=-1 # Use GPU if available
210
  )
211
  except Exception as e:
212
  print(f"Error initializing model: {e}")
@@ -219,45 +35,46 @@ system_prompt = (
219
  "and technical questions, providing clear and concise answers."
220
  )
221
 
222
- chat_history = [{"role": "system", "content": system_prompt}]
223
-
224
- @app.route('/')
225
- def index():
226
- return render_template('index.html') # You should move your HTML to a templates folder
227
-
228
- @app.route('/chat')
229
- def chat():
230
- global chat_history
231
- user_message = request.args.get('message', '')
232
- if not llm:
233
- return Response("data: Model not loaded\n\ndata: [DONE]\n\n", content_type='text/event-stream')
234
 
235
- chat_history.append({"role": "user", "content": user_message})
 
236
 
237
- def generate():
238
- ai_response = ""
239
- # Format messages for the model
240
- messages = [{"role": msg["role"], "content": msg["content"]} for msg in chat_history]
241
-
242
- stream = llm.create_chat_completion(
243
- messages=messages,
244
- max_tokens=1000,
245
- stop=["User:"],
246
- stream=True
247
- )
248
-
249
- for output in stream:
250
- chunk = output['choices'][0]['delta'].get('content', '')
251
- if chunk:
252
- ai_response += chunk
253
- yield f"data: {chunk}\n\n"
254
-
255
- chat_history.append({"role": "assistant", "content": ai_response.strip()})
256
- if len(chat_history) > 10: # Limit history to last 10 messages
257
- chat_history = chat_history[-10:]
258
- yield "data: [DONE]\n\n"
259
 
260
- return Response(generate(), content_type='text/event-stream')
 
 
 
 
 
 
 
 
 
261
 
262
- if __name__ == '__main__':
263
- app.run(debug=True, port=7860, host="0.0.0.0")
 
 
1
+ import gradio as gr
2
  from huggingface_hub import hf_hub_download
3
  from llama_cpp import Llama
4
+ import html
5
 
6
+ # モデルのダウンロードと初期化
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  def download_model():
8
  model_name = "bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF"
9
+ model_file = "DeepSeek-Coder-V2-Lite-Instruct-Q6_K.gguf"
10
+ try:
11
+ return hf_hub_download(repo_id=model_name, filename=model_file)
12
+ except Exception as e:
13
+ print(f"Model download failed: {e}")
14
+ return None
15
 
16
  def initialize_model():
17
  try:
18
  model_path = download_model()
19
+ if not model_path:
20
+ return None
21
  return Llama(
22
  model_path=model_path,
23
  n_ctx=4096,
24
  n_threads=4,
25
+ n_gpu_layers=-1
26
  )
27
  except Exception as e:
28
  print(f"Error initializing model: {e}")
 
35
  "and technical questions, providing clear and concise answers."
36
  )
37
 
38
+ # チャットボットの処理関数
39
+ def respond(message, chat_history):
40
+ if not message or not llm:
41
+ return chat_history
 
 
 
 
 
 
 
 
42
 
43
+ # チャット履歴の構築(システムプロンプト + 過去の会話 + 新しいメッセージ)
44
+ messages = [{"role": "system", "content": system_prompt}]
45
 
46
+ for user_msg, bot_msg in chat_history:
47
+ messages.append({"role": "user", "content": user_msg})
48
+ messages.append({"role": "assistant", "content": bot_msg})
49
+
50
+ messages.append({"role": "user", "content": message})
51
+
52
+ # AIからのレスポンス生成
53
+ response = llm.create_chat_completion(
54
+ messages=messages,
55
+ max_tokens=1000,
56
+ stop=["User:"],
57
+ stream=False
58
+ )
59
+
60
+ ai_response = response['choices'][0]['message']['content']
61
+
62
+ # チャット履歴に追加
63
+ chat_history.append((message, ai_response))
64
+
65
+ return chat_history
 
 
66
 
67
+ # Gradioインターフェースの作成
68
+ with gr.Blocks() as demo:
69
+ gr.Markdown("# AI Coding Assistant")
70
+
71
+ chatbot = gr.Chatbot(height=500)
72
+ msg = gr.Textbox(label="Your Message")
73
+ clear = gr.Button("Clear")
74
+
75
+ msg.submit(respond, [msg, chatbot], chatbot)
76
+ clear.click(lambda: None, None, chatbot, queue=False)
77
 
78
+ # アプリの起動
79
+ if __name__ == "__main__":
80
+ demo.launch(server_name="0.0.0.0", server_port=7860)