Update app.py
Browse files
app.py
CHANGED
|
@@ -1,329 +1,520 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import os
|
| 3 |
-
from pathlib import Path
|
| 4 |
-
from pinecone import Pinecone
|
| 5 |
-
from typing import List, Tuple
|
| 6 |
-
import tempfile
|
| 7 |
-
import shutil
|
| 8 |
-
from dotenv import load_dotenv
|
| 9 |
-
import time
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
if
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
}
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
return
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
def
|
| 144 |
-
"""
|
| 145 |
-
if not files:
|
| 146 |
-
return
|
| 147 |
-
|
| 148 |
-
if len(files) > 10:
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from pinecone import Pinecone
|
| 5 |
+
from typing import List, Tuple
|
| 6 |
+
import tempfile
|
| 7 |
+
import shutil
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
import time
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
import json
|
| 12 |
+
|
| 13 |
+
# Load environment variables
|
| 14 |
+
load_dotenv()
|
| 15 |
+
|
| 16 |
+
# Validate required environment variables
|
| 17 |
+
required_env_vars = ["PINECONE_API_KEY"]
|
| 18 |
+
missing_vars = [var for var in required_env_vars if not os.getenv(var)]
|
| 19 |
+
|
| 20 |
+
if missing_vars:
|
| 21 |
+
raise ValueError(f"Missing required environment variables: {', '.join(missing_vars)}")
|
| 22 |
+
|
| 23 |
+
# Initialize Pinecone
|
| 24 |
+
pinecone_api_key = os.getenv("PINECONE_API_KEY")
|
| 25 |
+
pc = Pinecone(api_key=pinecone_api_key)
|
| 26 |
+
|
| 27 |
+
# Create uploads directory
|
| 28 |
+
UPLOAD_FOLDER = "uploads"
|
| 29 |
+
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 30 |
+
|
| 31 |
+
def list_uploaded_files(progress=gr.Progress()):
|
| 32 |
+
"""List all files uploaded to Pinecone Assistant with their metadata and timestamps"""
|
| 33 |
+
try:
|
| 34 |
+
progress(0.1, desc="π Connecting to Pinecone Assistant...")
|
| 35 |
+
assistant_name = os.getenv("PINECONE_ASSISTANT_NAME", "gstminutes")
|
| 36 |
+
assistant = pc.assistant.Assistant(assistant_name=assistant_name)
|
| 37 |
+
|
| 38 |
+
progress(0.3, desc="π Fetching file list...")
|
| 39 |
+
time.sleep(0.5)
|
| 40 |
+
|
| 41 |
+
# List all files in the assistant
|
| 42 |
+
files_response = assistant.list_files()
|
| 43 |
+
|
| 44 |
+
progress(0.7, desc="π Processing file information...")
|
| 45 |
+
time.sleep(0.3)
|
| 46 |
+
|
| 47 |
+
if not files_response or not hasattr(files_response, 'files') or not files_response.files:
|
| 48 |
+
progress(1.0, desc="β
Complete - No files found")
|
| 49 |
+
return "π **No files found in Pinecone Assistant**", ""
|
| 50 |
+
|
| 51 |
+
files_list = files_response.files
|
| 52 |
+
total_files = len(files_list)
|
| 53 |
+
|
| 54 |
+
# Sort files by creation time (most recent first)
|
| 55 |
+
sorted_files = sorted(files_list, key=lambda x: getattr(x, 'created_on', ''), reverse=True)
|
| 56 |
+
|
| 57 |
+
progress(0.9, desc="π Formatting results...")
|
| 58 |
+
|
| 59 |
+
# Create summary
|
| 60 |
+
summary = f"π **Files Summary**\n\n"
|
| 61 |
+
summary += f"π **Total files:** {total_files}\n"
|
| 62 |
+
summary += f"π **Last updated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
|
| 63 |
+
|
| 64 |
+
# Create detailed file list
|
| 65 |
+
detailed_info = "## π **File Details**\n\n"
|
| 66 |
+
|
| 67 |
+
for i, file_obj in enumerate(sorted_files, 1):
|
| 68 |
+
try:
|
| 69 |
+
# Get basic file information
|
| 70 |
+
file_name = getattr(file_obj, 'name', 'Unknown')
|
| 71 |
+
file_id = getattr(file_obj, 'id', 'Unknown')
|
| 72 |
+
file_size = getattr(file_obj, 'size', 0)
|
| 73 |
+
created_on = getattr(file_obj, 'created_on', 'Unknown')
|
| 74 |
+
updated_on = getattr(file_obj, 'updated_on', created_on)
|
| 75 |
+
|
| 76 |
+
# Format file size
|
| 77 |
+
if file_size > 1024 * 1024:
|
| 78 |
+
size_str = f"{file_size / (1024 * 1024):.2f} MB"
|
| 79 |
+
elif file_size > 1024:
|
| 80 |
+
size_str = f"{file_size / 1024:.2f} KB"
|
| 81 |
+
else:
|
| 82 |
+
size_str = f"{file_size} bytes"
|
| 83 |
+
|
| 84 |
+
# Format timestamps
|
| 85 |
+
try:
|
| 86 |
+
if created_on != 'Unknown':
|
| 87 |
+
created_formatted = datetime.fromisoformat(created_on.replace('Z', '+00:00')).strftime('%Y-%m-%d %H:%M:%S UTC')
|
| 88 |
+
else:
|
| 89 |
+
created_formatted = 'Unknown'
|
| 90 |
+
|
| 91 |
+
if updated_on != 'Unknown' and updated_on != created_on:
|
| 92 |
+
updated_formatted = datetime.fromisoformat(updated_on.replace('Z', '+00:00')).strftime('%Y-%m-%d %H:%M:%S UTC')
|
| 93 |
+
else:
|
| 94 |
+
updated_formatted = created_formatted
|
| 95 |
+
except:
|
| 96 |
+
created_formatted = str(created_on)
|
| 97 |
+
updated_formatted = str(updated_on)
|
| 98 |
+
|
| 99 |
+
detailed_info += f"### {i}. π **{file_name}**\n"
|
| 100 |
+
detailed_info += f"- **π File ID:** `{file_id}`\n"
|
| 101 |
+
detailed_info += f"- **π Size:** {size_str}\n"
|
| 102 |
+
detailed_info += f"- **π
Uploaded:** {created_formatted}\n"
|
| 103 |
+
detailed_info += f"- **π Last Updated:** {updated_formatted}\n"
|
| 104 |
+
|
| 105 |
+
# Try to get metadata if available
|
| 106 |
+
try:
|
| 107 |
+
# Get file details for metadata
|
| 108 |
+
file_details = assistant.describe_file(file_id=file_id)
|
| 109 |
+
if hasattr(file_details, 'metadata') and file_details.metadata:
|
| 110 |
+
metadata = file_details.metadata
|
| 111 |
+
detailed_info += f"- **π·οΈ Metadata:**\n"
|
| 112 |
+
|
| 113 |
+
if isinstance(metadata, dict):
|
| 114 |
+
for key, value in metadata.items():
|
| 115 |
+
if isinstance(value, list):
|
| 116 |
+
detailed_info += f" - **{key.title()}:** {', '.join(map(str, value))}\n"
|
| 117 |
+
else:
|
| 118 |
+
detailed_info += f" - **{key.title()}:** {value}\n"
|
| 119 |
+
else:
|
| 120 |
+
detailed_info += f" - {metadata}\n"
|
| 121 |
+
except Exception as metadata_error:
|
| 122 |
+
detailed_info += f"- **π·οΈ Metadata:** Could not retrieve metadata\n"
|
| 123 |
+
|
| 124 |
+
detailed_info += "\n---\n\n"
|
| 125 |
+
|
| 126 |
+
except Exception as file_error:
|
| 127 |
+
detailed_info += f"### {i}. β **Error processing file**\n"
|
| 128 |
+
detailed_info += f"- **Error:** {str(file_error)}\n\n---\n\n"
|
| 129 |
+
|
| 130 |
+
progress(1.0, desc="β
File list retrieved successfully!")
|
| 131 |
+
time.sleep(0.3)
|
| 132 |
+
|
| 133 |
+
return summary, detailed_info
|
| 134 |
+
|
| 135 |
+
except Exception as e:
|
| 136 |
+
error_msg = f"β **Error retrieving file list:** {str(e)}"
|
| 137 |
+
return error_msg, ""
|
| 138 |
+
|
| 139 |
+
def refresh_file_list():
|
| 140 |
+
"""Refresh the file list"""
|
| 141 |
+
return "π **Refreshing file list... Please wait**"
|
| 142 |
+
|
| 143 |
+
def process_files_with_progress(files, *metadata_inputs, progress=gr.Progress()):
|
| 144 |
+
"""Process multiple files with individual metadata and show progress"""
|
| 145 |
+
if not files:
|
| 146 |
+
return "β Error: No files selected", ""
|
| 147 |
+
|
| 148 |
+
if len(files) > 10:
|
| 149 |
+
return "β Error: Maximum 10 files allowed at a time", ""
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
results = []
|
| 153 |
+
errors = []
|
| 154 |
+
total_files = len(files)
|
| 155 |
+
|
| 156 |
+
# Initialize Pinecone Assistant
|
| 157 |
+
progress(0, desc="π§ Initializing Pinecone Assistant...")
|
| 158 |
+
time.sleep(0.5) # Small delay to show the progress
|
| 159 |
+
assistant_name = os.getenv("PINECONE_ASSISTANT_NAME", "gstminutes")
|
| 160 |
+
assistant = pc.assistant.Assistant(assistant_name=assistant_name)
|
| 161 |
+
|
| 162 |
+
# Process each file with its individual metadata
|
| 163 |
+
for i, file_path in enumerate(files):
|
| 164 |
+
try:
|
| 165 |
+
filename = os.path.basename(file_path)
|
| 166 |
+
progress((i / total_files), desc=f"π Processing {filename}... ({i+1}/{total_files})")
|
| 167 |
+
|
| 168 |
+
# Get metadata for this specific file (3 fields per file: sections, keywords, description)
|
| 169 |
+
sections_idx = i * 3
|
| 170 |
+
keywords_idx = i * 3 + 1
|
| 171 |
+
description_idx = i * 3 + 2
|
| 172 |
+
|
| 173 |
+
if sections_idx < len(metadata_inputs):
|
| 174 |
+
sections = metadata_inputs[sections_idx] or ""
|
| 175 |
+
keywords = metadata_inputs[keywords_idx] or ""
|
| 176 |
+
description = metadata_inputs[description_idx] or ""
|
| 177 |
+
else:
|
| 178 |
+
sections = keywords = description = ""
|
| 179 |
+
|
| 180 |
+
# Skip if no metadata provided for this file
|
| 181 |
+
if not sections.strip() and not keywords.strip() and not description.strip():
|
| 182 |
+
errors.append({
|
| 183 |
+
"filename": filename,
|
| 184 |
+
"error": "β Error: No metadata provided"
|
| 185 |
+
})
|
| 186 |
+
continue
|
| 187 |
+
|
| 188 |
+
# Prepare metadata for this file
|
| 189 |
+
progress((i / total_files), desc=f"π·οΈ Preparing metadata for {filename}...")
|
| 190 |
+
metadata = {
|
| 191 |
+
"sections": [s.strip() for s in sections.split(",") if s.strip()],
|
| 192 |
+
"keywords": [k.strip() for k in keywords.split(",") if k.strip()],
|
| 193 |
+
"description": description.strip()
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
# Copy to uploads directory
|
| 197 |
+
progress((i / total_files), desc=f"π Copying {filename} to uploads...")
|
| 198 |
+
destination_path = os.path.join(UPLOAD_FOLDER, filename)
|
| 199 |
+
shutil.copy2(file_path, destination_path)
|
| 200 |
+
|
| 201 |
+
# Upload to Pinecone Assistant
|
| 202 |
+
progress((i / total_files), desc=f"βοΈ Uploading {filename} to Pinecone...")
|
| 203 |
+
response = assistant.upload_file(
|
| 204 |
+
file_path=destination_path,
|
| 205 |
+
metadata=metadata,
|
| 206 |
+
timeout=None
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
results.append({
|
| 210 |
+
"filename": filename,
|
| 211 |
+
"status": "β
Success",
|
| 212 |
+
"metadata": metadata,
|
| 213 |
+
"response": str(response)
|
| 214 |
+
})
|
| 215 |
+
|
| 216 |
+
except Exception as file_error:
|
| 217 |
+
errors.append({
|
| 218 |
+
"filename": os.path.basename(file_path),
|
| 219 |
+
"error": f"β Error: {str(file_error)}"
|
| 220 |
+
})
|
| 221 |
+
|
| 222 |
+
# Final progress update
|
| 223 |
+
progress(1.0, desc="β
Processing complete!")
|
| 224 |
+
time.sleep(0.5)
|
| 225 |
+
|
| 226 |
+
# Format results for display
|
| 227 |
+
success_count = len(results)
|
| 228 |
+
error_count = len(errors)
|
| 229 |
+
|
| 230 |
+
status_message = f"π **Processing Complete**\n\n"
|
| 231 |
+
status_message += f"β
**Successful uploads:** {success_count}\n"
|
| 232 |
+
status_message += f"β **Failed uploads:** {error_count}\n"
|
| 233 |
+
status_message += f"π **Total files processed:** {len(files)}\n\n"
|
| 234 |
+
|
| 235 |
+
# Detailed results
|
| 236 |
+
detailed_results = "## π **Detailed Results**\n\n"
|
| 237 |
+
|
| 238 |
+
if results:
|
| 239 |
+
detailed_results += "### β
**Successful Uploads:**\n"
|
| 240 |
+
for result in results:
|
| 241 |
+
detailed_results += f"- **{result['filename']}**\n"
|
| 242 |
+
detailed_results += f" - Sections: {', '.join(result['metadata']['sections'])}\n"
|
| 243 |
+
detailed_results += f" - Keywords: {', '.join(result['metadata']['keywords'])}\n"
|
| 244 |
+
detailed_results += f" - Description: {result['metadata']['description']}\n\n"
|
| 245 |
+
|
| 246 |
+
if errors:
|
| 247 |
+
detailed_results += "### β **Failed Uploads:**\n"
|
| 248 |
+
for error in errors:
|
| 249 |
+
detailed_results += f"- **{error['filename']}** - {error['error']}\n"
|
| 250 |
+
|
| 251 |
+
return status_message, detailed_results, "β
**Processing completed successfully!**"
|
| 252 |
+
|
| 253 |
+
except Exception as e:
|
| 254 |
+
error_msg = f"β **Critical Error:** {str(e)}"
|
| 255 |
+
return error_msg, "", "β **Processing failed with error**"
|
| 256 |
+
|
| 257 |
+
def update_metadata_fields(files):
|
| 258 |
+
"""Update metadata fields based on uploaded files"""
|
| 259 |
+
if not files:
|
| 260 |
+
return [gr.update(visible=False)] * 30 # Hide all fields
|
| 261 |
+
|
| 262 |
+
if len(files) > 10:
|
| 263 |
+
# Show error and hide all fields
|
| 264 |
+
return [gr.update(visible=False)] * 30
|
| 265 |
+
|
| 266 |
+
updates = []
|
| 267 |
+
for i in range(len(files)):
|
| 268 |
+
if i < len(files):
|
| 269 |
+
filename = os.path.basename(files[i])
|
| 270 |
+
# Show 3 fields per file (sections, keywords, description)
|
| 271 |
+
updates.extend([
|
| 272 |
+
gr.update(visible=True, label=f"π Sections for {filename}", placeholder="e.g., Introduction, Financial Data, Compliance"),
|
| 273 |
+
gr.update(visible=True, label=f"π Keywords for {filename}", placeholder="e.g., GST, tax, compliance, revenue"),
|
| 274 |
+
gr.update(visible=True, label=f"π Description for {filename}", placeholder="Brief description of this document")
|
| 275 |
+
])
|
| 276 |
+
|
| 277 |
+
# Hide remaining fields
|
| 278 |
+
while len(updates) < 30:
|
| 279 |
+
updates.append(gr.update(visible=False))
|
| 280 |
+
|
| 281 |
+
return updates[:30]
|
| 282 |
+
|
| 283 |
+
def clear_form():
|
| 284 |
+
"""Clear all form fields"""
|
| 285 |
+
return [None] + [""] * 30 + ["", "", "π’ **Ready to process documents**"]
|
| 286 |
+
|
| 287 |
+
def start_processing():
|
| 288 |
+
"""Show processing started status"""
|
| 289 |
+
return "π **Processing documents... Please wait**"
|
| 290 |
+
|
| 291 |
+
def finish_processing():
|
| 292 |
+
"""Show processing finished status"""
|
| 293 |
+
return "β
**Processing completed successfully!**"
|
| 294 |
+
|
| 295 |
+
# Create Gradio interface
|
| 296 |
+
with gr.Blocks(
|
| 297 |
+
title="π Tax Document Ingestion System",
|
| 298 |
+
theme=gr.themes.Soft(),
|
| 299 |
+
css="""
|
| 300 |
+
.gradio-container {
|
| 301 |
+
max-width: 1400px !important;
|
| 302 |
+
margin: auto;
|
| 303 |
+
}
|
| 304 |
+
.upload-container {
|
| 305 |
+
border: 2px dashed #4CAF50;
|
| 306 |
+
border-radius: 10px;
|
| 307 |
+
padding: 20px;
|
| 308 |
+
text-align: center;
|
| 309 |
+
background-color: #f8f9fa;
|
| 310 |
+
}
|
| 311 |
+
.tab-nav {
|
| 312 |
+
margin-bottom: 20px;
|
| 313 |
+
}
|
| 314 |
+
"""
|
| 315 |
+
) as app:
|
| 316 |
+
|
| 317 |
+
gr.Markdown(
|
| 318 |
+
"""
|
| 319 |
+
# π Tax Document Ingestion System
|
| 320 |
+
|
| 321 |
+
Upload and manage documents in the Pinecone Assistant for GST Minutes processing.
|
| 322 |
+
|
| 323 |
+
## π Features:
|
| 324 |
+
- β
**Multiple file upload** - Select and upload multiple documents at once
|
| 325 |
+
- π·οΈ **Metadata tagging** - Add sections, keywords, and descriptions
|
| 326 |
+
- π **Batch processing** - All files processed with individual metadata
|
| 327 |
+
- π **File management** - View uploaded files with timestamps and metadata
|
| 328 |
+
- π **Detailed reporting** - See success/failure status for each operation
|
| 329 |
+
|
| 330 |
+
---
|
| 331 |
+
"""
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
# Create tabs for different functionalities
|
| 335 |
+
with gr.Tabs() as tabs:
|
| 336 |
+
|
| 337 |
+
# Tab 1: Upload Documents
|
| 338 |
+
with gr.TabItem("π€ Upload Documents", id="upload_tab"):
|
| 339 |
+
with gr.Row():
|
| 340 |
+
with gr.Column(scale=1):
|
| 341 |
+
gr.Markdown("### π **File Upload**")
|
| 342 |
+
files_input = gr.File(
|
| 343 |
+
label="Select Documents (Max 10 files)",
|
| 344 |
+
file_count="multiple",
|
| 345 |
+
file_types=[".pdf", ".doc", ".docx", ".txt"],
|
| 346 |
+
elem_classes=["upload-container"]
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
with gr.Column(scale=1):
|
| 350 |
+
gr.Markdown("### π·οΈ **Document Metadata (Individual for Each File)**")
|
| 351 |
+
gr.Markdown("*Upload files first, then metadata fields will appear for each document*")
|
| 352 |
+
|
| 353 |
+
# Dynamic metadata fields container
|
| 354 |
+
with gr.Column() as metadata_container:
|
| 355 |
+
# Create 30 text fields (enough for 10 files with 3 fields each)
|
| 356 |
+
metadata_fields = []
|
| 357 |
+
for i in range(30):
|
| 358 |
+
field = gr.Textbox(
|
| 359 |
+
label=f"Field {i}",
|
| 360 |
+
placeholder="",
|
| 361 |
+
visible=False,
|
| 362 |
+
lines=2
|
| 363 |
+
)
|
| 364 |
+
metadata_fields.append(field)
|
| 365 |
+
|
| 366 |
+
with gr.Row():
|
| 367 |
+
with gr.Column(scale=1):
|
| 368 |
+
upload_btn = gr.Button(
|
| 369 |
+
"π Upload Documents to Pinecone Assistant",
|
| 370 |
+
variant="primary",
|
| 371 |
+
size="lg"
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
with gr.Column(scale=1):
|
| 375 |
+
clear_btn = gr.Button(
|
| 376 |
+
"ποΈ Clear Form",
|
| 377 |
+
variant="secondary",
|
| 378 |
+
size="lg"
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# Processing status indicator
|
| 382 |
+
with gr.Row():
|
| 383 |
+
processing_status = gr.Markdown(
|
| 384 |
+
value="π’ **Ready to process documents**",
|
| 385 |
+
visible=True
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
gr.Markdown("---")
|
| 389 |
+
|
| 390 |
+
# Results section
|
| 391 |
+
with gr.Row():
|
| 392 |
+
with gr.Column():
|
| 393 |
+
status_output = gr.Markdown(
|
| 394 |
+
label="π Upload Status",
|
| 395 |
+
value="*Ready to upload documents...*"
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
with gr.Row():
|
| 399 |
+
with gr.Column():
|
| 400 |
+
results_output = gr.Markdown(
|
| 401 |
+
label="π Detailed Results",
|
| 402 |
+
value=""
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# Tab 2: View Uploaded Files
|
| 406 |
+
with gr.TabItem("π View Uploaded Files", id="view_tab"):
|
| 407 |
+
gr.Markdown("### π **Uploaded Files Management**")
|
| 408 |
+
gr.Markdown("View all files currently uploaded to the Pinecone Assistant with their metadata and timestamps.")
|
| 409 |
+
|
| 410 |
+
with gr.Row():
|
| 411 |
+
refresh_btn = gr.Button(
|
| 412 |
+
"π Refresh File List",
|
| 413 |
+
variant="primary",
|
| 414 |
+
size="lg"
|
| 415 |
+
)
|
| 416 |
+
auto_refresh_btn = gr.Button(
|
| 417 |
+
"π Load Files on Startup",
|
| 418 |
+
variant="secondary",
|
| 419 |
+
size="lg"
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
# File list status
|
| 423 |
+
with gr.Row():
|
| 424 |
+
file_list_status = gr.Markdown(
|
| 425 |
+
value="π‘ **Click 'Refresh File List' to load uploaded files**",
|
| 426 |
+
visible=True
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
gr.Markdown("---")
|
| 430 |
+
|
| 431 |
+
# File list results
|
| 432 |
+
with gr.Row():
|
| 433 |
+
with gr.Column(scale=1):
|
| 434 |
+
file_summary = gr.Markdown(
|
| 435 |
+
label="π Files Summary",
|
| 436 |
+
value="*Click refresh to load file summary...*"
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
with gr.Row():
|
| 440 |
+
with gr.Column():
|
| 441 |
+
file_details = gr.Markdown(
|
| 442 |
+
label="π File Details",
|
| 443 |
+
value="*Click refresh to load file details...*"
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
# Event handlers for Upload tab
|
| 447 |
+
|
| 448 |
+
# Update metadata fields when files are uploaded
|
| 449 |
+
files_input.change(
|
| 450 |
+
fn=update_metadata_fields,
|
| 451 |
+
inputs=[files_input],
|
| 452 |
+
outputs=metadata_fields
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
# Show processing status when upload starts
|
| 456 |
+
upload_btn.click(
|
| 457 |
+
fn=start_processing,
|
| 458 |
+
outputs=[processing_status]
|
| 459 |
+
).then(
|
| 460 |
+
fn=process_files_with_progress,
|
| 461 |
+
inputs=[files_input] + metadata_fields,
|
| 462 |
+
outputs=[status_output, results_output, processing_status]
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
clear_btn.click(
|
| 466 |
+
fn=clear_form,
|
| 467 |
+
outputs=[files_input] + metadata_fields + [status_output, results_output, processing_status]
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
# Event handlers for View Files tab
|
| 471 |
+
|
| 472 |
+
# Refresh file list
|
| 473 |
+
refresh_btn.click(
|
| 474 |
+
fn=refresh_file_list,
|
| 475 |
+
outputs=[file_list_status]
|
| 476 |
+
).then(
|
| 477 |
+
fn=list_uploaded_files,
|
| 478 |
+
outputs=[file_summary, file_details]
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
# Auto load files on startup
|
| 482 |
+
auto_refresh_btn.click(
|
| 483 |
+
fn=refresh_file_list,
|
| 484 |
+
outputs=[file_list_status]
|
| 485 |
+
).then(
|
| 486 |
+
fn=list_uploaded_files,
|
| 487 |
+
outputs=[file_summary, file_details]
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
# Footer
|
| 491 |
+
gr.Markdown(
|
| 492 |
+
"""
|
| 493 |
+
---
|
| 494 |
+
|
| 495 |
+
### π‘ **Usage Tips:**
|
| 496 |
+
|
| 497 |
+
**Upload Documents:**
|
| 498 |
+
- Select up to 10 PDF, DOC, DOCX, or TXT files at once
|
| 499 |
+
- Upload files first, then fill individual metadata for each document
|
| 500 |
+
- Each file gets its own sections, keywords, and description
|
| 501 |
+
- Check the results section for upload status
|
| 502 |
+
|
| 503 |
+
**View Uploaded Files:**
|
| 504 |
+
- Click 'Refresh File List' to see all uploaded files
|
| 505 |
+
- View file details including upload timestamps and metadata
|
| 506 |
+
- Files are sorted by most recent first
|
| 507 |
+
|
| 508 |
+
### π **Support:**
|
| 509 |
+
For issues or questions, contact the development team.
|
| 510 |
+
"""
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
if __name__ == "__main__":
|
| 514 |
+
app.launch(
|
| 515 |
+
server_name="0.0.0.0",
|
| 516 |
+
server_port=7860,
|
| 517 |
+
share=False,
|
| 518 |
+
debug=True,
|
| 519 |
+
show_error=True
|
| 520 |
+
)
|