NCTCMumbai commited on
Commit
0106a28
Β·
verified Β·
1 Parent(s): 0b1b29e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +414 -0
app.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import random
4
+ import pandas as pd
5
+ import gradio as gr
6
+ from gradio_pdf import PDF
7
+ from googleapiclient.discovery import build
8
+ from googleapiclient.http import MediaIoBaseDownload
9
+ from google.oauth2 import service_account
10
+ from io import BytesIO
11
+ import tempfile
12
+ import markdown
13
+ import numpy as np
14
+ from sklearn.metrics.pairwise import cosine_similarity
15
+ from sentence_transformers import SentenceTransformer
16
+ from supabase import create_client
17
+ from pydantic import BaseModel, Field
18
+ from phi.agent import Agent
19
+ from phi.model.groq import Groq
20
+ import gradio as gr
21
+
22
+ # Environment variables for sensitive data
23
+ SUPABASE_URL = os.getenv("SUPABASE_URL", "https://frtfsbwyywxaokezgvno.supabase.co")
24
+ SUPABASE_KEY = os.getenv("SUPABASE_KEY", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImZydGZzYnd5eXd4YW9rZXpndm5vIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDI0NDAyMjAsImV4cCI6MjA1ODAxNjIyMH0.C0DYMhvJ1oKwBNhq8_WRMITa79EPW4_h2yTI_1LPPAA")
25
+ os.environ["GROQ_API_KEY"] = os.getenv("GROQ_API_KEY", "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")
26
+ VALID_USERNAME=os.getenv("VALID_USERNAME")
27
+ VALID_PASSWORD=os.getenv("VALID_PASSWORD")
28
+ # VALID_USERNAME = "nctcdummy123"
29
+ # VALID_PASSWORD = "Nctcmumbai@ai"
30
+ # Google Drive API credentials
31
+ SCOPES = ["https://www.googleapis.com/auth/drive"]
32
+ SERVICE_ACCOUNT_FILE = os.getenv("SERVICE_ACCOUNT_FILE", "/app/credentials_new.json") # Store in HF Space storage
33
+ creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
34
+ drive_service = build("drive", "v3", credentials=creds)
35
+
36
+ # Pydantic model for column weights
37
+ class ColumnWeights(BaseModel):
38
+ report_no: float = Field(0.0, description="Weight for report number")
39
+ date_of_issue: float = Field(0.0, description="Weight for issue date")
40
+ subject: float = Field(0.0, description="Weight for subject")
41
+ short_summary: float = Field(0.0, description="Weight for short summary")
42
+ report_category: float = Field(0.0, description="Weight for report category")
43
+ subject_classification: float = Field(0.0, description="Weight for subject classification")
44
+ cth_cti: float = Field(0.0, description="Weight for CTH/CTI")
45
+ notification_number: float = Field(0.0, description="Weight for notification number")
46
+ notification_type: float = Field(0.0, description="Weight for notification type")
47
+ issue_year: float = Field(0.0, description="Weight for issue year")
48
+
49
+ def normalize_weights(self):
50
+ total_weight = sum([getattr(self, field) for field in self.__fields__])
51
+ if total_weight == 0:
52
+ raise ValueError("Total weight cannot be zero.")
53
+ factor = 10 / total_weight
54
+ for field in self.__fields__:
55
+ setattr(self, field, round(getattr(self, field) * factor, 2))
56
+
57
+ # Weight Assigner Agent
58
+ weight_assigner = Agent(
59
+ name="Weight Assigner",
60
+ role="Assigns dynamic weights to columns based on the query.",
61
+ instructions=[
62
+ "Analyze the query and assign weights to the relevant columns.",
63
+ "Focus on the keywords in the query to determine which columns are most relevant.",
64
+ "For queries related to Chapter, CTH, CTI, tariff heading give more weightage to cth_cti column",
65
+ "For queries related to product name, item description give more weightage to short_summary",
66
+ "Report category tells the report is related to export or import only",
67
+ "For any queries related to risk types such as overvaluation, misclassification, BCD, IGST, CVD duty evasion etc., give additional weightage to subject_classification",
68
+ "Ensure the total weight sums to approximately 10 (decimal values allowed). Minimum weight value for a column should be 0.5 and round to single decimal place"
69
+ ],
70
+ model=Groq(id="deepseek-r1-distill-llama-70b"),
71
+ response_model=ColumnWeights,
72
+ markdown=True,
73
+ debug_mode=True,
74
+ show_tool_calls=True,
75
+ monitoring=True
76
+ )
77
+
78
+ # Supabase data fetch
79
+ def fetch_data_from_supabase():
80
+ sup supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
81
+ response = supabase.table("risk_report_embeddings").select("*").execute()
82
+ data = response.data
83
+ if not data:
84
+ raise ValueError("No data found in the Supabase table.")
85
+ return pd.DataFrame(data)
86
+
87
+ # Relevant Reports Selector
88
+ class RelevantReports(BaseModel):
89
+ report_numbers: list[str] = Field(..., description="List of report numbers extracted (report_no)")
90
+
91
+ relevant_report_selector = Agent(
92
+ name="Relevant Report Selector",
93
+ role="Selects the reports after dropping not related reports based on the query and provided data.",
94
+ instructions=[
95
+ "Analyze the query and given reports and give more importance to products and CTH/CTI.",
96
+ "Drop the reports that are not fairly related to the query.",
97
+ "Extract Report numbers, generally shown against the field 'report_no' in the given data, not against 'id'"
98
+ ],
99
+ model=Groq(id="deepseek-r1-distill-llama-70b"),
100
+ response_model=RelevantReports,
101
+ markdown=True,
102
+ debug_mode=True,
103
+ show_tool_calls=True,
104
+ monitoring=True
105
+ )
106
+
107
+ # Chatbot Agent
108
+ chat_agent = Agent(
109
+ name="NCTCGpt",
110
+ role="You are a Knowledge Management System Chat Assistant answering questions only based on NCTC Risk Revenue Reports on Revenue Risks.",
111
+ instructions=[
112
+ "Your goal is to provide a professional and detailed answer to the given query based on NCTC risk revenue reports mentioned in the context. If no reports is given in CONTEXT, mention no risk reports found and dont try to give answer on ur own",
113
+ "The report should be in proper markdown and nicely formatted with headings and subheadings.",
114
+ "If more than one report matches the queries, discuss the relevance of each report one by one.",
115
+ "If there are no reports given in the context of the prompt, mention there is no Risk report found related to this query from repository ",
116
+ "Cite the report numbers with the date of issue if risk reports are found .report number are against report_no of format (12/2021-22) ",
117
+ "CTI/CTH refers to WCO HSN codes of 8 digits which follow a system of reference. e.g., 84012000 - first 2 digits indicate Chapter 84, 4 digits - 8401 indicate Heading, 6 digits - 840120 indicate subheading, 8 digits fully indicate an item."
118
+ ],
119
+ model=Groq(id="deepseek-r1-distill-llama-70b"),
120
+ stream=True,
121
+ markdown=True,
122
+ debug_mode=True,
123
+ show_tool_calls=True,
124
+ monitoring=True
125
+ )
126
+
127
+ # Main query processing pipeline
128
+ def process_query(query, model):
129
+ gr.Info('Fetching relevant Risk reports from repository...')
130
+ weights_response = weight_assigner.run(query).content
131
+ weights_response.normalize_weights()
132
+ weights = {field: getattr(weights_response, field) for field in weights_response.__fields__}
133
+
134
+ df = fetch_data_from_supabase()
135
+ metadata_cols = [col for col in df.columns if col != 'embedding']
136
+
137
+ query_embedding = model.encode(query.lower().strip())
138
+ gr.Info('Searching the knowledge base ...')
139
+
140
+ scores = []
141
+ for i in range(len(df)):
142
+ embeddings_dict = df['embedding'][i]
143
+ final_score = 0
144
+ for col, weight in weights.items():
145
+ if col not in embeddings_dict:
146
+ continue
147
+ col_embedding = embeddings_dict[col]
148
+ if np.all(col_embedding == 0):
149
+ continue
150
+ similarity = cosine_similarity([query_embedding], [col_embedding])[0][0]
151
+ final_score += weight * similarity
152
+ scores.append(final_score)
153
+
154
+ df['relevance_score'] = scores
155
+ df = df.sort_values(by='relevance_score', ascending=False)
156
+
157
+ top_n = 15
158
+ prompt_df = df[[col for col in metadata_cols if col != 'id']].copy()
159
+ top_n_rows = prompt_df.head(top_n)
160
+
161
+ markdown_prompt = f"Query: {query}\n\nFind Top Relevant Reports from below reports to answer above query and return list of their report_no:\n\n"
162
+ for row in top_n_rows.to_dict(orient="records"):
163
+ markdown_prompt += f"**Report**:\n"
164
+ for key, value in row.items():
165
+ markdown_prompt += f"- {key}: {value}\n"
166
+ markdown_prompt += "\n"
167
+
168
+ agent_response = relevant_report_selector.run(markdown_prompt)
169
+ relevant_report_numbers = agent_response.content.report_numbers
170
+ gr.Info('Agent analysing Relevancy of fetched reports..')
171
+
172
+ selected_rows = prompt_df[prompt_df['report_no'].isin(relevant_report_numbers)]
173
+ top_n_data = selected_rows.to_dict(orient="records")
174
+ markdown_prompt = f"Query: {query}\n\nUse the below context to answer the question ,\nCONTEXT : \n\n"
175
+ for row in top_n_data:
176
+ markdown_prompt += f"**Report**:\n"
177
+ for key, value in row.items():
178
+ markdown_prompt += f"- {key}: {value}\n"
179
+ markdown_prompt += "\n"
180
+ gr.Info('Almost over..Chatbot Agent pitches in...')
181
+ chatbot_response = chat_agent.run(markdown_prompt)
182
+ return chatbot_response.content, relevant_report_numbers
183
+
184
+ # Google Drive PDF download
185
+ def download_pdf_from_drive(file_id):
186
+ if file_id == "N/A":
187
+ return None
188
+ try:
189
+ request = drive_service.files().get_media(fileId=file_id)
190
+ file_content = BytesIO()
191
+ downloader = MediaIoBaseDownload(file_content, request)
192
+ done = False
193
+ while not done:
194
+ status, done = downloader.next_chunk()
195
+ temp_dir = tempfile.mkdtemp()
196
+ temp_file_path = os.path.join(temp_dir, f"{file_id}.pdf")
197
+ with open(temp_file_path, "wb") as temp_file:
198
+ temp_file.write(file_content.getvalue())
199
+ return temp_file_path
200
+ except Exception as e:
201
+ print(f"Error downloading file: {e}")
202
+ return None
203
+
204
+ # Filtered DataFrame for report details
205
+ def filtered_df(report_no):
206
+ filtered_data = df_filtered[df_filtered['report_no'] == report_no]
207
+ if filtered_data.empty:
208
+ return ("<div style='text-align:center; padding:20px; background-color:#F9FAFB; border:1px solid #E5E7EB; border-radius:8px;'>No data found for the selected Report No.</div>", "N/A")
209
+
210
+ row = filtered_data.iloc[0]
211
+ html_content = """
212
+ <div style='padding:40px; background-color:#FFFFFF; border:1px solid #E5E7EB; border-radius:12px; box-shadow:0 4px 6px rgba(0,0,0,0.1);'>
213
+ <h1 style='color:#1E3A8A; text-align:center; margin-bottom:30px;'>Report Details</h1>
214
+ """
215
+ fields_to_display = {
216
+ "Report Number": "report_no",
217
+ "Report Issue Date": "date_of_issue",
218
+ "Subject": "subject",
219
+ "Short Summary": "short_summary",
220
+ "Total Assessible Value": "total_assessible_value",
221
+ "Total Differential Duty Involved": "total_revenue_difference",
222
+ "Total Transactions (Approx)": "total_transactions",
223
+ "Total Entities Involved": "total_importers",
224
+ "Report Category": "report_category",
225
+ "Report Classification": "subject_classification",
226
+ "CTH/CTI Involved": "cth_cti",
227
+ "Notifications Involved": "notification_number",
228
+ "Notification Type": "notification_type",
229
+ "Notification Date": "notification_date",
230
+ }
231
+ for field_name, column in fields_to_display.items():
232
+ value = row[column] if column in row.index and pd.notna(row[column]) else "N/A"
233
+ html_content += f"""
234
+ <div style='margin-bottom:15px;'>
235
+ <h4 style='color:#0F766E; font-weight:bold; margin-bottom:5px;'>{field_name}</h4>
236
+ <p style='font-size:16px; color:#374151; margin:0;'>{value}</p>
237
+ </div>
238
+ """
239
+ html_content += "</div>"
240
+ file_id = row.get("file_id", "N/A")
241
+ return html_content, file_id
242
+
243
+ def update_report_and_pdf(report_no):
244
+ html_content, file_id = filtered_df(report_no)
245
+ google_drive_link = f"[Open in Google Drive](https://drive.google.com/file/d/{file_id}/view)" if file_id != "N/A" else "File ID not available"
246
+ pdf_path = download_pdf_from_drive(file_id)
247
+ return html_content, google_drive_link, pdf_path
248
+
249
+ # Login authentication
250
+
251
+
252
+ def authenticate_user(username, password):
253
+ return username == VALID_USERNAME and password == VALID_PASSWORD
254
+
255
+ def login_action(username, password):
256
+ if authenticate_user(username, password):
257
+ return gr.update(visible=False), gr.update(visible=True), gr.update(value="", visible=False)
258
+ return gr.update(visible=True), gr.update(visible=False), gr.update(value="❌ Invalid credentials. Try again.", visible=True)
259
+
260
+ # Load data and model
261
+ df = fetch_data_from_supabase()
262
+ model = SentenceTransformer('nomic-ai/nomic-embed-text-v1', trust_remote_code=True)
263
+ df_filtered = df.drop(columns=['full ninety'], errors='ignore')
264
+ df_filtered['total_assessible_value'] = pd.to_numeric(df_filtered['total_assessible_value'], errors='coerce')
265
+ df_filtered['total_revenue_difference'] = pd.to_numeric(df_filtered['total_revenue_difference'], errors='coerce')
266
+ df_filtered['issue_year'] = df_filtered['issue_year'].astype(str).str.split('.').str[0]
267
+ df_filtered = df_filtered[df_filtered["issue_year"] != '0']
268
+ df_filtered = df_filtered[df_filtered["subject_classification"] != "0"]
269
+ df_filtered = df_filtered[df_filtered["report_category"] != "0"]
270
+
271
+ # Gradio interface
272
+ with gr.Blocks(css=".gr-button {background-color: #1E3A8A; color: white;}") as demo:
273
+ with gr.Column(visible=True) as login_section:
274
+ gr.HTML("""
275
+ <div style='text-align:center; padding: 30px 0;'>
276
+ <h1 style='font-size: 2.5em; color:#1E3A8A; font-weight: bold;'>NCTC AI Assisted Knowledge Management System</h1>
277
+ <h3 style='color:#0F766E;'>National Customs Targeting Center – Mumbai</h3>
278
+ <p style='margin-top: 20px; color:#374151;'>Please log in to continue.</p>
279
+ </div>
280
+ """)
281
+ username_input = gr.Textbox(label="Username", placeholder="Enter username")
282
+ password_input = gr.Textbox(label="Password", type="password", placeholder="Enter password")
283
+ login_button = gr.Button("πŸ” Login")
284
+ login_error = gr.Textbox(visible=False, interactive=False)
285
+
286
+ with gr.Column(visible=False) as main_app_section:
287
+ title = gr.Markdown("<h1 style='text-align:center; color:#1E3A8A; font-weight:bold;'>NCTC Risk Report Analytics</h1>")
288
+ subtitle = gr.Markdown("<h2 style='text-align:center; color:#6366F1; font-weight:600;'>Powered by AI Agents</h2>")
289
+ description = gr.Markdown("<h3 style='text-align:center; color:#0F766E; font-weight:bold;'>This application provides interactive visualizations and detailed insights into NCTC risk reports. Users can explore yearly trends, subject classifications, and revenue impacts through dynamic charts and a chatbot to interact with the knowledge repository.</h3>")
290
+
291
+ with gr.TabItem("Risk Report Visualizations"):
292
+ with gr.Row():
293
+ plt1 = gr.BarPlot(
294
+ value=df_filtered.groupby("issue_year")["report_no"].count().reset_index(),
295
+ x="issue_year", y="report_no",
296
+ title="Number of Revenue Risk Reports by Issue Year",
297
+ color="issue_year"
298
+ )
299
+ plt2 = gr.BarPlot(
300
+ value=df_filtered.groupby("issue_year")["total_revenue_difference"].sum().reset_index(),
301
+ x="issue_year", y="total_revenue_difference",
302
+ title="Year-wise Total Differential Revenue Involved"
303
+ )
304
+ with gr.Row():
305
+ plt3 = gr.BarPlot(
306
+ value=df_filtered.groupby("subject_classification")["report_no"].count().reset_index(),
307
+ x="subject_classification", y="report_no",
308
+ title="Risk Type Classification",
309
+ x_label_angle=60,
310
+ x_axis_labels_visible=False
311
+ )
312
+ plt4 = gr.BarPlot(
313
+ value=df_filtered.groupby("report_category")["report_no"].count().reset_index(),
314
+ x="report_category", y="report_no",
315
+ title="Report Category",
316
+ color="report_category"
317
+ )
318
+
319
+ with gr.TabItem("View Report"):
320
+ report_dropdown = gr.Dropdown(choices=df_filtered['report_no'].unique().tolist(), label="Select Report No")
321
+ with gr.Row():
322
+ with gr.Column(scale=1):
323
+ report_output = gr.HTML()
324
+ file_id_link = gr.Markdown()
325
+ with gr.Column(scale=1):
326
+ pdf_viewer = PDF(label="PDF Viewer")
327
+ report_dropdown.change(
328
+ fn=update_report_and_pdf,
329
+ inputs=[report_dropdown],
330
+ outputs=[report_output, file_id_link, pdf_viewer]
331
+ )
332
+
333
+ with gr.Tab("AI ChatBot on RRR"):
334
+ with gr.Row():
335
+ query_input = gr.Textbox(label="Enter your query here", placeholder="e.g., What revenue reports deal with mechanical parts?")
336
+ submit_button = gr.Button("Submit")
337
+ image_urls = [
338
+ "https://example.com/loading1.gif", # Replace with actual URLs or store GIFs in HF Space
339
+ "https://example.com/loading2.gif",
340
+ "https://example.com/loading3.gif",
341
+ "https://example.com/loading4.gif"
342
+ ]
343
+ gif_image = gr.Image(width=100, height=100, value=random.choice(image_urls), visible=False, label="Loading...")
344
+
345
+ with gr.Row():
346
+ with gr.Column(scale=1):
347
+ chatbot_output = gr.HTML(label="ChatBot Response", show_label=True, container=True)
348
+ with gr.Column(scale=1):
349
+ pdf_viewer_chatbot = PDF(label="PDF Viewer")
350
+ report_links = gr.Radio(label="Relevant Reports", choices=[], interactive=True)
351
+ with gr.Row():
352
+ think_tokens_output = gr.HTML(label="Agent Reasoning", show_label=True, container=True)
353
+
354
+ def handle_submit(query):
355
+ gif_update = gr.update(visible=True)
356
+ chatbot_response, relevant_report_numbers = process_query(query, model)
357
+ think_pattern = r"<think>(.*?)</think>"
358
+ think_tokens_match = re.search(think_pattern, chatbot_response, re.DOTALL)
359
+ think_tokens = think_tokens_match.group(1).strip() if think_tokens_match else "No intermediate reasoning provided."
360
+ final_answer = re.sub(think_pattern, "", chatbot_response, flags=re.DOTALL).strip()
361
+ think_tokens_html = markdown.markdown(think_tokens)
362
+ final_answer_html = markdown.markdown(final_answer)
363
+ gif_update = gr.update(visible=False)
364
+ choices = relevant_report_numbers if relevant_report_numbers else []
365
+ value = relevant_report_numbers[0] if relevant_report_numbers else None
366
+ interactive = bool(relevant_report_numbers)
367
+ if not relevant_report_numbers:
368
+ gr.Info("No relevant reports found.")
369
+ return (
370
+ final_answer_html,
371
+ gr.Radio(choices=choices, value=value, interactive=interactive),
372
+ think_tokens_html
373
+ )
374
+
375
+ def handle_report_selection(report_no):
376
+ if not report_no:
377
+ gr.Info("No report selected.")
378
+ return None
379
+ filtered_data = df_filtered[df_filtered['report_no'] == report_no]
380
+ if filtered_data.empty:
381
+ return None
382
+ file_id = filtered_data.iloc[0]['file_id']
383
+ pdf_path = download_pdf_from_drive(file_id)
384
+ if pdf_path:
385
+ return pdf_path
386
+ gr.Info(f"PDF for report {report_no} could not be loaded.")
387
+ return None
388
+
389
+ def show_gif():
390
+ return gr.Image(visible=True)
391
+
392
+ submit_button.click(
393
+ show_gif,
394
+ None,
395
+ gif_image
396
+ ).then(
397
+ fn=handle_submit,
398
+ inputs=[query_input],
399
+ outputs=[chatbot_output, report_links, think_tokens_output]
400
+ )
401
+
402
+ report_links.change(
403
+ fn=handle_report_selection,
404
+ inputs=[report_links],
405
+ outputs=[pdf_viewer_chatbot]
406
+ )
407
+
408
+ login_button.click(
409
+ fn=login_action,
410
+ inputs=[username_input, password_input],
411
+ outputs=[login_section, main_app_section, login_error]
412
+ )
413
+
414
+ demo.launch(debug=True)