datafreak commited on
Commit
c41ebc7
Β·
verified Β·
1 Parent(s): 9942a12

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -29
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import gradio as gr
2
  import os
3
  from pathlib import Path
4
- from pinecone import Pinecone, ApiException
5
  from typing import List, Tuple
6
  import tempfile
7
  import shutil
@@ -24,41 +24,29 @@ if missing_vars:
24
  pinecone_api_key = os.getenv("PINECONE_API_KEY")
25
  pc = Pinecone(api_key=pinecone_api_key)
26
 
27
- # Get the Pinecone Assistant name from environment variables
28
- PINE_ASSISTANT_NAME = os.getenv("PINECONE_ASSISTANT_NAME", "gstminutes")
29
-
30
- # Initialize Pinecone Assistant (make this a global object for re-use)
31
- try:
32
- pinecone_assistant = pc.assistant.Assistant(assistant_name=PINE_ASSISTANT_NAME)
33
- except Exception as e:
34
- print(f"Error initializing Pinecone Assistant: {e}")
35
- pinecone_assistant = None
36
-
37
  # Create uploads directory
38
  UPLOAD_FOLDER = "uploads"
39
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
40
 
41
  def list_uploaded_files(progress=gr.Progress()):
42
  """List all files uploaded to Pinecone Assistant with their metadata and timestamps"""
43
- if not pinecone_assistant:
44
- error_msg = f"❌ **Error:** Pinecone Assistant not initialized. Check your API key and assistant name."
45
- return error_msg, ""
46
-
47
  try:
48
  progress(0.1, desc="πŸ” Connecting to Pinecone Assistant...")
 
 
49
 
50
  progress(0.3, desc="πŸ“‹ Fetching file list...")
51
  time.sleep(0.5)
52
 
53
  # List all files in the assistant
54
- files_response = pinecone_assistant.list_files()
55
 
56
  progress(0.7, desc="πŸ“Š Processing file information...")
57
  time.sleep(0.3)
58
 
59
  if not files_response or not hasattr(files_response, 'files') or not files_response.files:
60
  progress(1.0, desc="βœ… Complete - No files found")
61
- return f"πŸ“‹ **No files found in Pinecone Assistant '{PINE_ASSISTANT_NAME}'**", ""
62
 
63
  files_list = files_response.files
64
  total_files = len(files_list)
@@ -69,7 +57,7 @@ def list_uploaded_files(progress=gr.Progress()):
69
  progress(0.9, desc="πŸ“ Formatting results...")
70
 
71
  # Create summary
72
- summary = f"πŸ“Š **Files Summary for Assistant '{PINE_ASSISTANT_NAME}'**\n\n"
73
  summary += f"πŸ“ **Total files:** {total_files}\n"
74
  summary += f"πŸ• **Last updated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
75
 
@@ -117,7 +105,7 @@ def list_uploaded_files(progress=gr.Progress()):
117
  # Try to get metadata if available
118
  try:
119
  # Get file details for metadata
120
- file_details = pinecone_assistant.describe_file(file_id=file_id)
121
  if hasattr(file_details, 'metadata') and file_details.metadata:
122
  metadata = file_details.metadata
123
  detailed_info += f"- **🏷️ Metadata:**\n"
@@ -144,9 +132,6 @@ def list_uploaded_files(progress=gr.Progress()):
144
 
145
  return summary, detailed_info
146
 
147
- except ApiException as e:
148
- error_msg = f"❌ **Pinecone API Error:** {e.body.decode('utf-8')}"
149
- return error_msg, ""
150
  except Exception as e:
151
  error_msg = f"❌ **Error retrieving file list:** {str(e)}"
152
  return error_msg, ""
@@ -157,20 +142,23 @@ def refresh_file_list():
157
 
158
  def process_files_with_progress(files, *metadata_inputs, progress=gr.Progress()):
159
  """Process multiple files with individual metadata and show progress"""
160
- if not pinecone_assistant:
161
- return f"❌ Error: Pinecone Assistant not initialized. Check your environment variables.", "", "❌ **Processing failed**"
162
-
163
  if not files:
164
- return "❌ Error: No files selected", "", "❌ **Processing failed**"
165
 
166
  if len(files) > 10:
167
- return "❌ Error: Maximum 10 files allowed at a time", "", "❌ **Processing failed**"
168
 
169
  try:
170
  results = []
171
  errors = []
172
  total_files = len(files)
173
 
 
 
 
 
 
 
174
  # Process each file with its individual metadata
175
  for i, file_path in enumerate(files):
176
  try:
@@ -212,7 +200,7 @@ def process_files_with_progress(files, *metadata_inputs, progress=gr.Progress())
212
 
213
  # Upload to Pinecone Assistant
214
  progress((i / total_files), desc=f"☁️ Uploading {filename} to Pinecone...")
215
- response = pinecone_assistant.upload_file(
216
  file_path=destination_path,
217
  metadata=metadata,
218
  timeout=None
@@ -417,7 +405,7 @@ with gr.Blocks(
417
  # Tab 2: View Uploaded Files
418
  with gr.TabItem("πŸ“‹ View Uploaded Files", id="view_tab"):
419
  gr.Markdown("### πŸ“‹ **Uploaded Files Management**")
420
- gr.Markdown(f"Viewing files in Pinecone Assistant: **`{PINE_ASSISTANT_NAME}`**")
421
 
422
  with gr.Row():
423
  refresh_btn = gr.Button(
 
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
 
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)
 
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
 
 
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"
 
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, ""
 
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:
 
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
 
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(