bluenevus commited on
Commit
29b1ac3
·
1 Parent(s): 77a5b77

Update app.py via AI Editor

Browse files
Files changed (1) hide show
  1. app.py +371 -1
app.py CHANGED
@@ -1 +1,371 @@
1
- -
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import threading
3
+ import logging
4
+ import uuid
5
+ import shutil
6
+ import json
7
+ import tempfile
8
+ from flask import Flask, request as flask_request, make_response
9
+ import dash
10
+ from dash import dcc, html, Input, Output, State, callback_context
11
+ import dash_bootstrap_components as dbc
12
+ import openai
13
+ import base64
14
+ import datetime
15
+ from werkzeug.utils import secure_filename
16
+ import chromadb
17
+ from chromadb.config import Settings
18
+ from langchain.embeddings.openai import OpenAIEmbeddings
19
+ from langchain.vectorstores import Chroma
20
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
21
+
22
+ # ========== GLOBALS AND LOGGING ==========
23
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(threadName)s %(message)s")
24
+ logger = logging.getLogger("AskTricare")
25
+
26
+ app_flask = Flask(__name__)
27
+ SESSION_DATA = {}
28
+ SESSION_LOCKS = {}
29
+ SESSION_DIR_BASE = os.path.join(tempfile.gettempdir(), "asktricare_sessions")
30
+ os.makedirs(SESSION_DIR_BASE, exist_ok=True)
31
+ VECTOR_DB_DIR = os.path.join(os.getcwd(), "vector_db")
32
+ DOCS_DIR = os.path.join(os.getcwd(), "doc")
33
+ os.makedirs(DOCS_DIR, exist_ok=True)
34
+ os.makedirs(VECTOR_DB_DIR, exist_ok=True)
35
+
36
+ openai.api_key = os.environ.get("OPENAI_API_KEY")
37
+
38
+ # ========== VECTOR DB SHARED ==========
39
+ chroma_client = chromadb.Client(Settings(
40
+ chroma_db_impl="duckdb+parquet",
41
+ persist_directory=VECTOR_DB_DIR,
42
+ ))
43
+ embeddings = OpenAIEmbeddings(model="text-embedding-ada-002", openai_api_key=openai.api_key)
44
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
45
+
46
+ def ingest_docs():
47
+ logger.info("Starting document ingestion...")
48
+ file_paths = []
49
+ for root, _, files in os.walk(DOCS_DIR):
50
+ for f in files:
51
+ if f.lower().endswith(('.txt', '.pdf', '.md', '.docx')):
52
+ file_paths.append(os.path.join(root, f))
53
+ documents = []
54
+ metadatas = []
55
+ ids = []
56
+ for path in file_paths:
57
+ try:
58
+ with open(path, "r", encoding="utf-8", errors="ignore") as infile:
59
+ content = infile.read()
60
+ chunks = text_splitter.split_text(content)
61
+ for idx, chunk in enumerate(chunks):
62
+ documents.append(chunk)
63
+ metadatas.append({"source": path, "chunk": idx})
64
+ ids.append(f"{os.path.basename(path)}_{idx}")
65
+ except Exception as e:
66
+ logger.error(f"Error ingesting {path}: {e}")
67
+ if documents:
68
+ vectordb = Chroma(
69
+ collection_name="asktricare",
70
+ embedding_function=embeddings,
71
+ persist_directory=VECTOR_DB_DIR,
72
+ client_settings=Settings(chroma_db_impl="duckdb+parquet", persist_directory=VECTOR_DB_DIR),
73
+ )
74
+ vectordb.add_texts(documents, metadatas=metadatas, ids=ids)
75
+ vectordb.persist()
76
+ logger.info(f"Ingested {len(documents)} chunks from {len(file_paths)} files.")
77
+ else:
78
+ logger.info("No new documents to ingest.")
79
+
80
+ if not os.listdir(VECTOR_DB_DIR):
81
+ ingest_docs()
82
+
83
+ vectordb = Chroma(
84
+ collection_name="asktricare",
85
+ embedding_function=embeddings,
86
+ persist_directory=VECTOR_DB_DIR,
87
+ client_settings=Settings(chroma_db_impl="duckdb+parquet", persist_directory=VECTOR_DB_DIR),
88
+ )
89
+
90
+ # ========== SESSION MANAGEMENT ==========
91
+ def get_session_id():
92
+ sid = flask_request.cookies.get("asktricare_session_id")
93
+ if not sid:
94
+ sid = str(uuid.uuid4())
95
+ return sid
96
+
97
+ def get_session_dir(session_id):
98
+ d = os.path.join(SESSION_DIR_BASE, session_id)
99
+ os.makedirs(d, exist_ok=True)
100
+ return d
101
+
102
+ def get_session_lock(session_id):
103
+ if session_id not in SESSION_LOCKS:
104
+ SESSION_LOCKS[session_id] = threading.Lock()
105
+ return SESSION_LOCKS[session_id]
106
+
107
+ def get_session_state(session_id):
108
+ if session_id not in SESSION_DATA:
109
+ SESSION_DATA[session_id] = {
110
+ "messages": [],
111
+ "uploads": [],
112
+ "created": datetime.datetime.utcnow().isoformat()
113
+ }
114
+ return SESSION_DATA[session_id]
115
+
116
+ def save_session_state(session_id):
117
+ state = get_session_state(session_id)
118
+ d = get_session_dir(session_id)
119
+ with open(os.path.join(d, "state.json"), "w") as f:
120
+ json.dump(state, f)
121
+
122
+ def load_session_state(session_id):
123
+ d = get_session_dir(session_id)
124
+ path = os.path.join(d, "state.json")
125
+ if os.path.exists(path):
126
+ with open(path, "r") as f:
127
+ SESSION_DATA[session_id] = json.load(f)
128
+
129
+ # ========== APP SETUP ==========
130
+ app = dash.Dash(
131
+ __name__,
132
+ server=app_flask,
133
+ suppress_callback_exceptions=True,
134
+ external_stylesheets=[dbc.themes.BOOTSTRAP, "/assets/custom.css"],
135
+ update_title="Ask Tricare"
136
+ )
137
+
138
+ # ========== LAYOUT ==========
139
+ def chat_message_card(msg, is_user):
140
+ align = "end" if is_user else "start"
141
+ color = "primary" if is_user else "secondary"
142
+ avatar = "🧑" if is_user else "🤖"
143
+ return dbc.Card(
144
+ dbc.CardBody([
145
+ html.Div([
146
+ html.Span(avatar, style={"fontSize": "2rem"}),
147
+ html.Span(msg, style={"whiteSpace": "pre-wrap", "marginLeft": "0.75rem"})
148
+ ], style={"display": "flex", "alignItems": "center", "justifyContent": align})
149
+ ]),
150
+ className=f"mb-2 ms-3 me-3",
151
+ color=color,
152
+ inverse=is_user,
153
+ style={"maxWidth": "80%", "alignSelf": f"flex-{align}"}
154
+ )
155
+
156
+ def uploaded_file_card(filename, is_img):
157
+ ext = os.path.splitext(filename)[1].lower()
158
+ icon = "🖼️" if is_img else "📄"
159
+ return dbc.Card(
160
+ dbc.CardBody([
161
+ html.Span(icon, style={"fontSize": "2rem", "marginRight": "0.5rem"}),
162
+ html.Span(filename)
163
+ ]),
164
+ className="mb-2",
165
+ color="tertiary"
166
+ )
167
+
168
+ def disclaimer_card():
169
+ return dbc.Card(
170
+ dbc.CardBody([
171
+ html.H5("Disclaimer", className="card-title"),
172
+ html.P("This information is not private. Do not send PII or PHI. For official guidance visit the Tricare website.", style={"fontSize": "0.95rem"})
173
+ ]),
174
+ className="mb-2"
175
+ )
176
+
177
+ def left_navbar(session_id, chat_history, uploads):
178
+ return html.Div([
179
+ html.Div([
180
+ html.H3("Ask Tricare", className="mb-3 mt-3", style={"fontWeight": "bold"}),
181
+ disclaimer_card(),
182
+ dcc.Upload(
183
+ id="file-upload",
184
+ children=dbc.Button("Upload Document/Image", color="secondary", className="mb-2", style={"width": "100%"}),
185
+ multiple=True,
186
+ style={"width": "100%"}
187
+ ),
188
+ html.Div([uploaded_file_card(os.path.basename(f["name"]), f["is_img"]) for f in uploads], id="upload-list"),
189
+ html.Hr(),
190
+ html.H5("Chat History", className="mb-2"),
191
+ html.Ul([html.Li(html.Span((msg['role'] + ": " + msg['content'])[:40] + ("..." if len(msg['content']) > 40 else ""), style={"fontSize": "0.92rem"})) for msg in chat_history[-6:]], style={"listStyle": "none", "paddingLeft": "0"}),
192
+ ], style={"padding": "1rem"})
193
+ ], style={"backgroundColor": "#f8f9fa", "height": "100vh", "overflowY": "auto"})
194
+
195
+ def right_main(chat_history, loading, error):
196
+ chat_cards = []
197
+ for msg in chat_history:
198
+ if msg['role'] == "user":
199
+ chat_cards.append(chat_message_card(msg['content'], is_user=True))
200
+ elif msg['role'] == "assistant":
201
+ chat_cards.append(chat_message_card(msg['content'], is_user=False))
202
+ return html.Div([
203
+ dbc.Card([
204
+ dbc.CardBody([
205
+ html.Div(chat_cards, id="chat-window", style={"minHeight": "60vh", "display": "flex", "flexDirection": "column", "justifyContent": "flex-end"}),
206
+ html.Div([
207
+ dcc.Textarea(
208
+ id="user-input",
209
+ placeholder="Type your question...",
210
+ style={"width": "100%", "height": "60px", "resize": "vertical", "wordWrap": "break-word"},
211
+ wrap="soft",
212
+ maxLength=1000,
213
+ autoFocus=True
214
+ ),
215
+ dbc.Button("Send", id="send-btn", color="primary", className="mt-2", style={"float": "right", "minWidth": "100px"}),
216
+ ], style={"marginTop": "1rem"}),
217
+ html.Div(error, id="error-message", style={"color": "#bb2124", "marginTop": "0.5rem"}),
218
+ ])
219
+ ], className="mt-3"),
220
+ dcc.Loading(id="loading", type="default", fullscreen=False, style={"position": "absolute", "top": "5%", "left": "50%"})
221
+ ], style={"padding": "1rem", "backgroundColor": "#fff", "height": "100vh", "overflowY": "auto"})
222
+
223
+ app.layout = html.Div([
224
+ dcc.Store(id="session-id", storage_type="local"),
225
+ dcc.Location(id="url"),
226
+ html.Div([
227
+ html.Div(id='left-navbar', style={"width": "30vw", "height": "100vh", "position": "fixed", "left": 0, "top": 0, "zIndex": 2, "overflowY": "auto"}),
228
+ html.Div(id='right-main', style={"marginLeft": "30vw", "width": "70vw", "overflowY": "auto"})
229
+ ], style={"display": "flex"})
230
+ ])
231
+
232
+ # ========== CALLBACKS ==========
233
+ @app.callback(
234
+ Output("session-id", "data"),
235
+ Input("url", "href"),
236
+ prevent_initial_call=False
237
+ )
238
+ def assign_session_id(_):
239
+ sid = get_session_id()
240
+ d = get_session_dir(sid)
241
+ load_session_state(sid)
242
+ logger.info(f"Assigned session id: {sid}")
243
+ resp = dash.no_update
244
+ return sid
245
+
246
+ @app.callback(
247
+ Output("left-navbar", "children"),
248
+ Output("right-main", "children"),
249
+ Input("session-id", "data"),
250
+ Input("send-btn", "n_clicks"),
251
+ Input("file-upload", "contents"),
252
+ State("file-upload", "filename"),
253
+ State("user-input", "value"),
254
+ State("right-main", "children"),
255
+ State("left-navbar", "children"),
256
+ prevent_initial_call=False
257
+ )
258
+ def main_callback(session_id, send_clicks, file_contents, file_names, user_input, right_children, left_children):
259
+ trigger = callback_context.triggered[0]['prop_id'].split('.')[0] if callback_context.triggered else ""
260
+ if not session_id:
261
+ session_id = get_session_id()
262
+ session_lock = get_session_lock(session_id)
263
+ with session_lock:
264
+ load_session_state(session_id)
265
+ state = get_session_state(session_id)
266
+ error = ""
267
+ loading = False
268
+
269
+ # File upload
270
+ if trigger == "file-upload" and file_contents and file_names:
271
+ uploads = []
272
+ if not isinstance(file_contents, list):
273
+ file_contents = [file_contents]
274
+ file_names = [file_names]
275
+ for c, n in zip(file_contents, file_names):
276
+ header, data = c.split(',', 1)
277
+ ext = os.path.splitext(n)[1].lower()
278
+ is_img = ext in [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp"]
279
+ fname = secure_filename(f"{datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')}_{n}")
280
+ session_dir = get_session_dir(session_id)
281
+ fp = os.path.join(session_dir, fname)
282
+ with open(fp, "wb") as f:
283
+ f.write(base64.b64decode(data))
284
+ uploads.append({"name": fname, "is_img": is_img, "path": fp})
285
+ state["uploads"].extend(uploads)
286
+ save_session_state(session_id)
287
+ logger.info(f"Session {session_id}: Uploaded files {[u['name'] for u in uploads]}")
288
+
289
+ # Chat send
290
+ if trigger == "send-btn" and user_input and user_input.strip():
291
+ loading = True
292
+ state["messages"].append({"role": "user", "content": user_input})
293
+ try:
294
+ # RAG: retrieve relevant docs
295
+ docs = []
296
+ try:
297
+ retr = vectordb.similarity_search(user_input, k=3)
298
+ docs = [d.page_content for d in retr]
299
+ except Exception as e:
300
+ logger.warning(f"Vector search failed: {e}")
301
+ context = "\n\n".join(docs)
302
+ messages = [
303
+ {"role": "system", "content": "You are Ask Tricare, a helpful assistant for TRICARE health benefits. Respond conversationally, and cite relevant sources when possible. If you do not know, say so."},
304
+ ]
305
+ for m in state["messages"]:
306
+ messages.append({"role": m["role"], "content": m["content"]})
307
+ if context.strip():
308
+ messages.append({"role": "system", "content": f"Relevant reference material:\n{context}"})
309
+ response = openai.ChatCompletion.create(
310
+ model="gpt-3.5-turbo",
311
+ messages=messages,
312
+ max_tokens=700,
313
+ temperature=0.2,
314
+ )
315
+ reply = response.choices[0].message.content
316
+ state["messages"].append({"role": "assistant", "content": reply})
317
+ logger.info(f"Session {session_id}: User: {user_input} | Assistant: {reply}")
318
+ error = ""
319
+ except Exception as e:
320
+ error = f"Error: {e}"
321
+ logger.error(f"Session {session_id}: {error}")
322
+ save_session_state(session_id)
323
+ loading = False
324
+
325
+ chat_history = state.get("messages", [])
326
+ uploads = state.get("uploads", [])
327
+ left = left_navbar(session_id, chat_history, uploads)
328
+ right = right_main(chat_history, loading, error)
329
+ return left, right
330
+
331
+ # ========== SESSION COOKIE ==========
332
+ @app_flask.after_request
333
+ def set_session_cookie(resp):
334
+ sid = flask_request.cookies.get("asktricare_session_id")
335
+ if not sid:
336
+ sid = str(uuid.uuid4())
337
+ resp.set_cookie("asktricare_session_id", sid, max_age=60*60*24*7, path="/")
338
+ return resp
339
+
340
+ # ========== CLEANUP ==========
341
+ def cleanup_sessions(max_age_hours=48):
342
+ now = datetime.datetime.utcnow()
343
+ for sid in os.listdir(SESSION_DIR_BASE):
344
+ d = os.path.join(SESSION_DIR_BASE, sid)
345
+ try:
346
+ state_path = os.path.join(d, "state.json")
347
+ if os.path.exists(state_path):
348
+ with open(state_path, "r") as f:
349
+ st = json.load(f)
350
+ created = st.get("created")
351
+ if created and (now - datetime.datetime.fromisoformat(created)).total_seconds() > max_age_hours * 3600:
352
+ shutil.rmtree(d)
353
+ logger.info(f"Cleaned up session {sid}")
354
+ except Exception as e:
355
+ logger.error(f"Cleanup error for {sid}: {e}")
356
+
357
+ # ========== CUDA/GPU SETUP ==========
358
+ try:
359
+ import torch
360
+ if torch.cuda.is_available():
361
+ torch.set_default_tensor_type(torch.cuda.FloatTensor)
362
+ logger.info("CUDA GPU detected and configured.")
363
+ except Exception as e:
364
+ logger.warning(f"CUDA config failed: {e}")
365
+
366
+ # ========== RUN ==========
367
+ if __name__ == '__main__':
368
+ print("Starting the Dash application...")
369
+ app.run(debug=True, host='0.0.0.0', port=7860, threaded=True)
370
+ print("Dash application has finished running.")
371
+ ```