Gopal2002 commited on
Commit
544c1e9
Β·
verified Β·
1 Parent(s): 8eaa122

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -0
app.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import datetime
4
+ import json
5
+ import base64
6
+ import tempfile
7
+ import os
8
+
9
+ # API endpoints
10
+ LOGIN_URL = "http://164.52.195.95/login"
11
+ CHAT_URL = "http://164.52.195.95/v1/chat/completions"
12
+
13
+ # Global token
14
+ access_token = None
15
+ chat_history = []
16
+
17
+ def login_user(username, password):
18
+ global access_token, chat_history
19
+ print("Attempting login...")
20
+ try:
21
+ response = requests.post(
22
+ LOGIN_URL,
23
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
24
+ data={
25
+ "grant_type": "password",
26
+ "username": username,
27
+ "password": password,
28
+ "scope": "",
29
+ "client_id": "string",
30
+ "client_secret": "********"
31
+ }
32
+ )
33
+ print("Login response status:", response.status_code)
34
+ response.raise_for_status()
35
+ token_data = response.json()
36
+ access_token = token_data["access_token"]
37
+ chat_history = []
38
+ return gr.update(visible=False), gr.update(visible=True), "βœ… Login successful!"
39
+ except Exception as e:
40
+ print("Login failed:", e)
41
+ return gr.update(), gr.update(), f"❌ Login failed: {e}"
42
+
43
+ def make_return(chatbot, msg="", image=None, alert_text=None):
44
+ return chatbot, msg, image, gr.update(visible=bool(alert_text), value=alert_text or "")
45
+
46
+ def send_message(message_text, image_files, chatbot):
47
+ global chat_history, access_token
48
+ print("Sending message:", message_text)
49
+ if access_token is None:
50
+ return make_return(chatbot + [{"role": "assistant", "content": "Please login first."}])
51
+
52
+ media_blocks = []
53
+ image_previews = []
54
+ if image_files:
55
+ for image_file in image_files:
56
+ try:
57
+ with open(image_file, "rb") as img_f:
58
+ base64_image = base64.b64encode(img_f.read()).decode("utf-8")
59
+ data_uri = f"data:image/jpeg;base64,{base64_image}"
60
+ media_blocks.append({
61
+ "type": "image_url",
62
+ "image_url": {"url": data_uri}
63
+ })
64
+ image_previews.append(data_uri)
65
+ except Exception as e:
66
+ print("Error encoding image:", e)
67
+ return make_return(chatbot + [{"role": "user", "content": message_text}, {"role": "assistant", "content": f"Image processing failed: {e}"}], "", None, f"❌ Image processing failed: {e}")
68
+
69
+ message_group = []
70
+
71
+ for i in range(0, len(chatbot), 2):
72
+ user_msg = chatbot[i]
73
+ assistant_msg = chatbot[i + 1] if i + 1 < len(chatbot) else {"role": "assistant", "content": ""}
74
+
75
+ user_content = user_msg["content"]
76
+ if isinstance(user_content, str):
77
+ message_group.append({
78
+ "role": "user",
79
+ "content": [{"type": "text", "text": user_content}]
80
+ })
81
+ elif isinstance(user_content, list):
82
+ message_group.append({
83
+ "role": "user",
84
+ "content": user_content
85
+ })
86
+
87
+ if isinstance(assistant_msg["content"], str):
88
+ message_group.append({
89
+ "role": "assistant",
90
+ "content": assistant_msg["content"]
91
+ })
92
+
93
+ new_msg = [{"type": "text", "text": message_text}]
94
+ if media_blocks:
95
+ new_msg.extend(media_blocks)
96
+
97
+ message_group.append({
98
+ "role": "user",
99
+ "content": new_msg
100
+ })
101
+
102
+ payload = {
103
+ "model": "./models/Llama-3.2-11B-Vision-Instruct",
104
+ "messages": message_group,
105
+ "temperature": 0.3,
106
+ "max_tokens": 500,
107
+ "stream": True
108
+ }
109
+
110
+ # print("Final Payload:", json.dumps(payload, indent=2)[-1000:])
111
+
112
+ headers = {
113
+ "Authorization": f"Bearer {access_token}",
114
+ "Content-Type": "application/json"
115
+ }
116
+
117
+ response_text = ""
118
+ try:
119
+ with requests.post(CHAT_URL, headers=headers, json=payload, stream=True) as response:
120
+ print("Streaming response...")
121
+ if response.status_code != 200:
122
+ try:
123
+ error_json = response.json()
124
+ error_msg = error_json.get("message", "Unknown error")
125
+ except:
126
+ error_msg = response.text
127
+ return make_return(chatbot, "", None, f"❌ API Error {response.status_code}: {error_msg}")
128
+
129
+ for line in response.iter_lines():
130
+ if line:
131
+ line = line.decode("utf-8")
132
+ print("Stream chunk:", line)
133
+ if line.startswith("data:"):
134
+ content = line[5:].strip()
135
+ if content == "[DONE]":
136
+ break
137
+ try:
138
+ data_json = json.loads(content)
139
+ delta = data_json["choices"][0]["delta"]
140
+ token = delta.get("content", "")
141
+ response_text += token
142
+ yield chatbot + [
143
+ {"role": "user", "content": message_text},
144
+ {"role": "assistant", "content": response_text}
145
+ ], "", None, gr.update(visible=False)
146
+ except Exception as json_err:
147
+ print("Error parsing stream chunk:", json_err)
148
+ continue
149
+ except Exception as e:
150
+ print("Error during streaming:", e)
151
+ return make_return(chatbot + [
152
+ {"role": "user", "content": message_text},
153
+ {"role": "assistant", "content": f"❌ Error: {e}"}
154
+ ], "", None, f"❌ {e}")
155
+
156
+ print("Final assistant response:", response_text)
157
+ return make_return(chatbot + [
158
+ {"role": "user", "content": message_text},
159
+ {"role": "assistant", "content": response_text}
160
+ ])
161
+
162
+ # === UI ===
163
+ with gr.Blocks(css="""
164
+ .message-input-box textarea {
165
+ border-radius: 16px !important;
166
+ padding: 12px !important;
167
+ background-color: #2c2c2c;
168
+ color: white;
169
+ }
170
+ .message-input-box textarea::placeholder {
171
+ color: #aaa;
172
+ }
173
+ .toast-alert {
174
+ background-color: #ff4d4f;
175
+ color: white;
176
+ padding: 10px 16px;
177
+ border-radius: 8px;
178
+ margin: 10px 0;
179
+ font-weight: bold;
180
+ }
181
+ """) as app:
182
+ gr.Markdown("# πŸ€– Secure AI Assistant Panel")
183
+
184
+ with gr.Column(visible=True) as login_page:
185
+ username = gr.Textbox(label="Username")
186
+ password = gr.Textbox(label="Password", type="password")
187
+ login_btn = gr.Button("Login")
188
+ login_status = gr.Markdown(visible=True)
189
+
190
+ with gr.Column(visible=False) as chat_page:
191
+ chatbot = gr.Chatbot(label="Chat", show_label=False, height=420, type="messages")
192
+ with gr.Row():
193
+ msg = gr.Textbox(label="", placeholder="Ask anything", elem_classes=["message-input-box"])
194
+ send_btn = gr.Button("Send")
195
+ img = gr.File(label="Upload Images (optional)", type="filepath", interactive=True, file_types=[".png", ".jpg", ".jpeg"], file_count="multiple")
196
+ image_preview = gr.Image(label="Image Preview", visible=False)
197
+ error_alert = gr.Markdown(visible=False, elem_classes=["toast-alert"])
198
+
199
+ login_btn.click(fn=login_user, inputs=[username, password], outputs=[login_page, chat_page, login_status])
200
+ send_btn.click(fn=send_message, inputs=[msg, img, chatbot], outputs=[chatbot, msg, image_preview, error_alert])
201
+
202
+ app.launch()