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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from google.oauth2 import service_account
|
| 4 |
+
from googleapiclient.discovery import build
|
| 5 |
+
from googleapiclient.http import MediaIoBaseDownload
|
| 6 |
+
import openai
|
| 7 |
+
from dotenv import load_dotenv, dotenv_values
|
| 8 |
+
import io
|
| 9 |
+
|
| 10 |
+
from openai import OpenAI
|
| 11 |
+
openai.api_key = os.getenv('OPENAI_API_KEY')
|
| 12 |
+
openai = OpenAI(api_key = openai.api_key)
|
| 13 |
+
|
| 14 |
+
class GPTDriveIntegration:
|
| 15 |
+
def __init__(self):
|
| 16 |
+
# Initialize Google Drive API
|
| 17 |
+
self.credentials = service_account.Credentials.from_service_account_file(
|
| 18 |
+
os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE'),
|
| 19 |
+
scopes=['https://www.googleapis.com/auth/drive.readonly']
|
| 20 |
+
)
|
| 21 |
+
self.drive_service = build('drive', 'v3', credentials=self.credentials)
|
| 22 |
+
|
| 23 |
+
# Initialize OpenAI
|
| 24 |
+
openai.api_key = os.getenv('OPENAI_API_KEY')
|
| 25 |
+
|
| 26 |
+
def search_files(self, query, file_types=None):
|
| 27 |
+
"""Search for files in Google Drive"""
|
| 28 |
+
search_query = f"name contains '{query}'"
|
| 29 |
+
|
| 30 |
+
if file_types:
|
| 31 |
+
type_queries = []
|
| 32 |
+
for file_type in file_types:
|
| 33 |
+
if file_type.lower() == 'pdf':
|
| 34 |
+
type_queries.append("mimeType='application/pdf'")
|
| 35 |
+
elif file_type.lower() in ['doc', 'docx']:
|
| 36 |
+
type_queries.append("mimeType contains 'document'")
|
| 37 |
+
elif file_type.lower() in ['xls', 'xlsx']:
|
| 38 |
+
type_queries.append("mimeType contains 'spreadsheet'")
|
| 39 |
+
|
| 40 |
+
if type_queries:
|
| 41 |
+
search_query += f" and ({' or '.join(type_queries)})"
|
| 42 |
+
|
| 43 |
+
results = self.drive_service.files().list(
|
| 44 |
+
q=search_query,
|
| 45 |
+
fields="files(id, name, mimeType, size)"
|
| 46 |
+
).execute()
|
| 47 |
+
|
| 48 |
+
return results.get('files', [])
|
| 49 |
+
|
| 50 |
+
def get_file_content(self, file_id, mime_type):
|
| 51 |
+
"""Download and extract text content from file"""
|
| 52 |
+
try:
|
| 53 |
+
if 'text' in mime_type or 'document' in mime_type:
|
| 54 |
+
# For Google Docs, export as plain text
|
| 55 |
+
if 'document' in mime_type:
|
| 56 |
+
request = self.drive_service.files().export_media(
|
| 57 |
+
fileId=file_id, mimeType='text/plain'
|
| 58 |
+
)
|
| 59 |
+
else:
|
| 60 |
+
request = self.drive_service.files().get_media(fileId=file_id)
|
| 61 |
+
|
| 62 |
+
file_content = io.BytesIO()
|
| 63 |
+
downloader = MediaIoBaseDownload(file_content, request)
|
| 64 |
+
done = False
|
| 65 |
+
while done is False:
|
| 66 |
+
status, done = downloader.next_chunk()
|
| 67 |
+
|
| 68 |
+
return file_content.getvalue().decode('utf-8')
|
| 69 |
+
|
| 70 |
+
elif 'spreadsheet' in mime_type:
|
| 71 |
+
# For Google Sheets, export as CSV
|
| 72 |
+
request = self.drive_service.files().export_media(
|
| 73 |
+
fileId=file_id, mimeType='text/csv'
|
| 74 |
+
)
|
| 75 |
+
file_content = io.BytesIO()
|
| 76 |
+
downloader = MediaIoBaseDownload(file_content, request)
|
| 77 |
+
done = False
|
| 78 |
+
while done is False:
|
| 79 |
+
status, done = downloader.next_chunk()
|
| 80 |
+
|
| 81 |
+
return file_content.getvalue().decode('utf-8')
|
| 82 |
+
|
| 83 |
+
elif mime_type == 'application/pdf':
|
| 84 |
+
# For PDF files, download binary content and extract text
|
| 85 |
+
request = self.drive_service.files().get_media(fileId=file_id)
|
| 86 |
+
file_content = io.BytesIO()
|
| 87 |
+
downloader = MediaIoBaseDownload(file_content, request)
|
| 88 |
+
done = False
|
| 89 |
+
while done is False:
|
| 90 |
+
status, done = downloader.next_chunk()
|
| 91 |
+
|
| 92 |
+
# Extract text from PDF using PyPDF2 or pdfplumber
|
| 93 |
+
file_content.seek(0) # Reset buffer position
|
| 94 |
+
|
| 95 |
+
# Option 1: Using PyPDF2
|
| 96 |
+
try:
|
| 97 |
+
import PyPDF2
|
| 98 |
+
pdf_reader = PyPDF2.PdfReader(file_content)
|
| 99 |
+
text = ""
|
| 100 |
+
for page in pdf_reader.pages:
|
| 101 |
+
text += page.extract_text() + "\n"
|
| 102 |
+
return text
|
| 103 |
+
except ImportError:
|
| 104 |
+
pass
|
| 105 |
+
|
| 106 |
+
# Option 2: Using pdfplumber (better for complex PDFs)
|
| 107 |
+
try:
|
| 108 |
+
import pdfplumber
|
| 109 |
+
text = ""
|
| 110 |
+
with pdfplumber.open(file_content) as pdf:
|
| 111 |
+
for page in pdf.pages:
|
| 112 |
+
page_text = page.extract_text()
|
| 113 |
+
if page_text:
|
| 114 |
+
text += page_text + "\n"
|
| 115 |
+
return text
|
| 116 |
+
except ImportError:
|
| 117 |
+
pass
|
| 118 |
+
|
| 119 |
+
# Option 3: Using pymupdf (fitz) - fastest option
|
| 120 |
+
try:
|
| 121 |
+
import fitz # pymupdf
|
| 122 |
+
pdf_document = fitz.open(stream=file_content.read(), filetype="pdf")
|
| 123 |
+
text = ""
|
| 124 |
+
for page_num in range(pdf_document.page_count):
|
| 125 |
+
page = pdf_document[page_num]
|
| 126 |
+
text += page.get_text() + "\n"
|
| 127 |
+
pdf_document.close()
|
| 128 |
+
return text
|
| 129 |
+
except ImportError:
|
| 130 |
+
pass
|
| 131 |
+
|
| 132 |
+
return "PDF text extraction requires PyPDF2, pdfplumber, or pymupdf library"
|
| 133 |
+
|
| 134 |
+
else:
|
| 135 |
+
return "File type not supported for text extraction"
|
| 136 |
+
|
| 137 |
+
except Exception as e:
|
| 138 |
+
return f"Error reading file: {str(e)}"
|
| 139 |
+
|
| 140 |
+
def query_gpt_with_context(self, user_query, file_contents):
|
| 141 |
+
"""Send query to GPT with file context"""
|
| 142 |
+
context = "\n\n".join([
|
| 143 |
+
f"File: {content['name']}\nContent: {content['text'][:2000]}..."
|
| 144 |
+
for content in file_contents
|
| 145 |
+
])
|
| 146 |
+
|
| 147 |
+
messages = [
|
| 148 |
+
{
|
| 149 |
+
"role": "system",
|
| 150 |
+
"content": """
|
| 151 |
+
You are an AI assistant that can analyze documents from Google Drive.
|
| 152 |
+
Use the provided file contents to answer user questions."""
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"role": "user",
|
| 156 |
+
"content": f"Context from Google Drive files:\n{context}\n\nUser Question: {user_query}"
|
| 157 |
+
}
|
| 158 |
+
]
|
| 159 |
+
|
| 160 |
+
response = openai.chat.completions.create(
|
| 161 |
+
model="gpt-4o-mini",
|
| 162 |
+
messages=messages,
|
| 163 |
+
max_tokens=1000
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
return response.choices[0].message.content
|
| 167 |
+
|
| 168 |
+
def process_query(self, user_query, search_terms=None):
|
| 169 |
+
"""Main function to process user queries"""
|
| 170 |
+
# Extract search terms from query if not provided
|
| 171 |
+
if not search_terms:
|
| 172 |
+
search_terms = user_query.split()[:3] # Simple extraction
|
| 173 |
+
|
| 174 |
+
# Search for relevant files
|
| 175 |
+
files = []
|
| 176 |
+
for term in search_terms:
|
| 177 |
+
files.extend(self.search_files(term))
|
| 178 |
+
|
| 179 |
+
# Remove duplicates
|
| 180 |
+
unique_files = {f['id']: f for f in files}.values()
|
| 181 |
+
|
| 182 |
+
# Get content from top 3 most relevant files
|
| 183 |
+
file_contents = []
|
| 184 |
+
for file in list(unique_files)[:3]:
|
| 185 |
+
content = self.get_file_content(file['id'], file['mimeType'])
|
| 186 |
+
file_contents.append({
|
| 187 |
+
'name': file['name'],
|
| 188 |
+
'text': content
|
| 189 |
+
})
|
| 190 |
+
|
| 191 |
+
# Query GPT with context
|
| 192 |
+
if file_contents:
|
| 193 |
+
response = self.query_gpt_with_context(user_query, file_contents)
|
| 194 |
+
return {
|
| 195 |
+
'answer': response,
|
| 196 |
+
'sources': [f['name'] for f in file_contents]
|
| 197 |
+
}
|
| 198 |
+
else:
|
| 199 |
+
return {
|
| 200 |
+
'answer': "No relevant files found in your Google Drive.",
|
| 201 |
+
'sources': []
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
gpt_drive = GPTDriveIntegration()
|
| 205 |
+
|
| 206 |
+
def process_user_query(query, search_terms_input):
|
| 207 |
+
"""Process user query and return formatted response"""
|
| 208 |
+
if not query.strip():
|
| 209 |
+
return "Please enter a question.", ""
|
| 210 |
+
|
| 211 |
+
# Parse search terms if provided
|
| 212 |
+
search_terms = None
|
| 213 |
+
# if search_terms_input.strip():
|
| 214 |
+
# search_terms = [term.strip() for term in search_terms_input.split(',')]
|
| 215 |
+
|
| 216 |
+
# Process the query
|
| 217 |
+
result = gpt_drive.process_query(query, search_terms)
|
| 218 |
+
|
| 219 |
+
# Format the response
|
| 220 |
+
answer = result['answer']
|
| 221 |
+
sources = result['sources']
|
| 222 |
+
|
| 223 |
+
sources_text = ""
|
| 224 |
+
if sources:
|
| 225 |
+
sources_text = "**Sources used:**\n" + "\n".join([f"β’ {source}" for source in sources])
|
| 226 |
+
|
| 227 |
+
return answer, sources_text
|
| 228 |
+
|
| 229 |
+
def check_setup():
|
| 230 |
+
"""Check if the APIs are properly configured"""
|
| 231 |
+
status_messages = []
|
| 232 |
+
|
| 233 |
+
# Check Google Drive API
|
| 234 |
+
if gpt_drive.drive_initialized:
|
| 235 |
+
status_messages.append("β
Google Drive API: Connected")
|
| 236 |
+
else:
|
| 237 |
+
status_messages.append(f"β Google Drive API: {getattr(gpt_drive, 'drive_error', 'Not configured')}")
|
| 238 |
+
|
| 239 |
+
# Check OpenAI API
|
| 240 |
+
if gpt_drive.openai_initialized:
|
| 241 |
+
status_messages.append("β
OpenAI API: Connected")
|
| 242 |
+
else:
|
| 243 |
+
status_messages.append(f"β OpenAI API: {getattr(gpt_drive, 'openai_error', 'Not configured')}")
|
| 244 |
+
|
| 245 |
+
return "\n".join(status_messages)
|
| 246 |
+
|
| 247 |
+
# Create Gradio interface
|
| 248 |
+
with gr.Blocks(title="Augusta's Anatomy Reading Assistant", theme=gr.themes.Soft()) as app:
|
| 249 |
+
gr.Markdown("# π€ Augusta's Anatomy bot")
|
| 250 |
+
gr.Markdown("Ask questions about your anatomy books using AI!")
|
| 251 |
+
|
| 252 |
+
with gr.Row():
|
| 253 |
+
with gr.Column(scale=2):
|
| 254 |
+
# Main query interface
|
| 255 |
+
with gr.Group():
|
| 256 |
+
gr.Markdown("### Ask a Question")
|
| 257 |
+
query_input = gr.Textbox(
|
| 258 |
+
label="Your Question",
|
| 259 |
+
placeholder="Ask me any question about your anatomy books?",
|
| 260 |
+
lines=3
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
search_terms_input = gr.Textbox(
|
| 264 |
+
label="Search Terms (optional)",
|
| 265 |
+
placeholder="Enter comma-separated terms to search for specific files",
|
| 266 |
+
lines=1
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
submit_btn = gr.Button("Search & Ask", variant="primary", size="lg")
|
| 270 |
+
|
| 271 |
+
# Results section
|
| 272 |
+
with gr.Group():
|
| 273 |
+
gr.Markdown("### Answer")
|
| 274 |
+
answer_output = gr.Textbox(
|
| 275 |
+
label="AI Response",
|
| 276 |
+
lines=10,
|
| 277 |
+
interactive=False
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
sources_output = gr.Textbox(
|
| 281 |
+
label="Sources",
|
| 282 |
+
lines=3,
|
| 283 |
+
interactive=False
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
with gr.Column(scale=1):
|
| 287 |
+
# Status and setup info
|
| 288 |
+
with gr.Group():
|
| 289 |
+
gr.Markdown("### System Status")
|
| 290 |
+
status_btn = gr.Button("Check Status", size="sm")
|
| 291 |
+
status_output = gr.Textbox(
|
| 292 |
+
label="API Status",
|
| 293 |
+
lines=4,
|
| 294 |
+
interactive=False
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
with gr.Group():
|
| 298 |
+
gr.Markdown("### Setup Instructions")
|
| 299 |
+
gr.Markdown("""
|
| 300 |
+
**Important Notes:**
|
| 301 |
+
1.Only documents shared with it, it can answer
|
| 302 |
+
|
| 303 |
+
**File Types Supported:**
|
| 304 |
+
- Google Docs
|
| 305 |
+
- Google Sheets
|
| 306 |
+
- PDF files
|
| 307 |
+
- Text files
|
| 308 |
+
|
| 309 |
+
**Tips:**
|
| 310 |
+
- Use specific search terms for better results
|
| 311 |
+
- The system searches the top 3 most relevant files
|
| 312 |
+
- Ask clear, specific questions for better answers
|
| 313 |
+
""")
|
| 314 |
+
|
| 315 |
+
# Event handlers
|
| 316 |
+
submit_btn.click(
|
| 317 |
+
fn=process_user_query,
|
| 318 |
+
inputs=[query_input, search_terms_input],
|
| 319 |
+
outputs=[answer_output, sources_output]
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
status_btn.click(
|
| 323 |
+
fn=check_setup,
|
| 324 |
+
outputs=status_output
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# Example queries
|
| 328 |
+
with gr.Row():
|
| 329 |
+
gr.Examples(
|
| 330 |
+
examples=[
|
| 331 |
+
["What is morbid Anatomy?", "morbid, Anatomy"],
|
| 332 |
+
["The transmission of nerves from one neuron to another is as a result of what?", "neuron, nerves, Dr Clement"],
|
| 333 |
+
],
|
| 334 |
+
inputs=[query_input, search_terms_input],
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
# Launch the app
|
| 338 |
+
if __name__ == "__main__":
|
| 339 |
+
app.launch(
|
| 340 |
+
share=True,debug =True)
|