File size: 14,834 Bytes
42ffbd8
 
ff16161
 
 
42ffbd8
 
 
 
 
 
 
 
 
 
 
e1a57d6
2aa013d
 
42ffbd8
 
379bd80
 
63ac0b2
 
 
 
 
 
 
 
 
 
 
 
 
 
379bd80
 
63ac0b2
 
 
 
 
 
 
2aa013d
 
63ac0b2
42ffbd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fd666f
9a532a0
1e3b610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42ffbd8
1e3b610
42ffbd8
1e3b610
 
 
 
 
 
 
42ffbd8
1e3b610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42ffbd8
1e3b610
 
 
 
 
 
 
 
 
 
 
 
42ffbd8
1e3b610
 
 
 
 
 
 
 
 
 
 
 
42ffbd8
1e3b610
 
 
 
 
42ffbd8
1e3b610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42ffbd8
1e3b610
 
 
 
42ffbd8
 
 
 
 
 
 
 
 
 
 
 
 
94df6e1
 
 
 
 
 
42ffbd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c007c4
06e37bc
be8cbc5
06e37bc
42ffbd8
224f472
42ffbd8
 
 
 
 
 
 
 
 
 
 
beb4390
42ffbd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f495
 
 
 
 
 
 
 
 
 
42ffbd8
 
97b72ac
fb02b80
 
 
 
 
97b72ac
495f495
 
 
 
97b72ac
 
 
 
0e83654
97b72ac
250c0e8
94df6e1
 
250c0e8
94df6e1
f1f73c1
0e83654
42ffbd8
beb4390
42ffbd8
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
138
139
140
141
142
143
144
145
146
147
148
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import os
import json
import requests
import json
import tempfile
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
import openai
from dotenv import load_dotenv, dotenv_values
import io

from openai import OpenAI
openai.api_key = os.getenv('OPENAI_API_KEY')
openai = OpenAI(api_key = openai.api_key)




class GPTDriveIntegration:
    def __init__(self):
        # Build credentials info from individual environment variables
        credentials_info = {
            "type": "service_account",
            "project_id": os.getenv('GOOGLE_PROJECT_ID'),
            "private_key_id": os.getenv('GOOGLE_PRIVATE_KEY_ID'),
            "private_key": os.getenv('GOOGLE_PRIVATE_KEY').replace('\\n', '\n'),  # Fix line breaks
            "client_email": os.getenv('GOOGLE_CLIENT_EMAIL'),
            "client_id": os.getenv('GOOGLE_CLIENT_ID'),
            "auth_uri": "https://accounts.google.com/o/oauth2/auth",
            "token_uri": "https://oauth2.googleapis.com/token",
            "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
            "client_x509_cert_url": os.getenv('GOOGLE_CLIENT_CERT_URL'),
            "universe_domain": "googleapis.com"
        }
        
        # Check if all required fields are present
        required_fields = ['project_id', 'private_key', 'client_email']
        missing_fields = [field for field in required_fields if not credentials_info[field]]
        
        if missing_fields:
            raise ValueError(f"Missing required environment variables: {missing_fields}")
        
        # Initialize Google Drive API
        self.credentials = service_account.Credentials.from_service_account_info(
            credentials_info,
            scopes=['https://www.googleapis.com/auth/drive.readonly']
        )
        
        self.drive_service = build('drive', 'v3', credentials=self.credentials)
        # Initialize OpenAI
        openai.api_key = os.getenv('OPENAI_API_KEY')
    
    def search_files(self, query, file_types=None):
        """Search for files in Google Drive"""
        search_query = f"name contains '{query}'"
        
        if file_types:
            type_queries = []
            for file_type in file_types:
                if file_type.lower() == 'pdf':
                    type_queries.append("mimeType='application/pdf'")
                elif file_type.lower() in ['doc', 'docx']:
                    type_queries.append("mimeType contains 'document'")
                elif file_type.lower() in ['xls', 'xlsx']:
                    type_queries.append("mimeType contains 'spreadsheet'")
            
            if type_queries:
                search_query += f" and ({' or '.join(type_queries)})"
        
        results = self.drive_service.files().list(
            q=search_query,
            fields="files(id, name, mimeType, size)"
        ).execute()
        
        return results.get('files', [])
    
    def get_file_content(self, file_id, mime_type):
        """Download and extract text content from file"""
        try:
            if 'text' in mime_type or 'document' in mime_type:
                # For Google Docs, export as plain text
                if 'document' in mime_type:
                    request = self.drive_service.files().export_media(
                        fileId=file_id, mimeType='text/plain'
                    )
                else:
                    request = self.drive_service.files().get_media(fileId=file_id)
                
                file_content = io.BytesIO()
                downloader = MediaIoBaseDownload(file_content, request)
                done = False
                while done is False:
                    status, done = downloader.next_chunk()
                
                return file_content.getvalue().decode('utf-8')
            
            elif 'spreadsheet' in mime_type:
                # For Google Sheets, export as CSV
                request = self.drive_service.files().export_media(
                    fileId=file_id, mimeType='text/csv'
                )
                file_content = io.BytesIO()
                downloader = MediaIoBaseDownload(file_content, request)
                done = False
                while done is False:
                    status, done = downloader.next_chunk()
                
                return file_content.getvalue().decode('utf-8')
            
            elif mime_type == 'application/pdf':
                # For PDF files, download binary content and extract text
                request = self.drive_service.files().get_media(fileId=file_id)
                file_content = io.BytesIO()
                downloader = MediaIoBaseDownload(file_content, request)
                done = False
                while done is False:
                    status, done = downloader.next_chunk()
                
                # Extract text from PDF
                file_content.seek(0)
                
                try:
                    import PyPDF2
                    pdf_reader = PyPDF2.PdfReader(file_content)
                    text = ""
                    for page in pdf_reader.pages:
                        text += page.extract_text() + "\n"
                    return text
                except ImportError:
                    return "PDF text extraction requires PyPDF2 library"
            
            else:
                return "File type not supported for text extraction"
                
        except Exception as e:
            return f"Error reading file: {str(e)}"
    
    def query_gpt_with_context(self, user_query, file_contents):
        """Send query to GPT with file context"""
        context = "\n\n".join([
            f"File: {content['name']}\nContent: {content['text'][:2000]}..."
            for content in file_contents
        ])
        
        messages = [
            {
                "role": "system", 
                "content": """
                You are an AI assistant that can analyze documents from Google Drive. 
                Use the provided file contents to answer user questions."""
            },
            {
                "role": "user", 
                "content": f"Context from Google Drive files:\n{context}\n\nUser Question: {user_query}"
            }
        ]
        
        response = openai.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            max_tokens=1000
        )
        
        return response.choices[0].message.content
    
    def process_query(self, user_query, search_terms=None):
        """Main function to process user queries"""
        # Extract search terms from query if not provided
        if not search_terms:
            search_terms = user_query.split()[:3]  # Simple extraction
        
        # Search for relevant files
        files = []
        for term in search_terms:
            files.extend(self.search_files(term))
        
        # Remove duplicates
        unique_files = {f['id']: f for f in files}.values()
        
        # Get content from top 3 most relevant files
        file_contents = []
        for file in list(unique_files)[:3]:
            content = self.get_file_content(file['id'], file['mimeType'])
            file_contents.append({
                'name': file['name'],
                'text': content
            })
        
        # Query GPT with context
        if file_contents:
            response = self.query_gpt_with_context(user_query, file_contents)
            return {
                'answer': response,
                'sources': [f['name'] for f in file_contents]
            }
        else:
            return {
                'answer': "No relevant files found in your Google Drive.",
                'sources': []
            }
    
    def query_gpt_with_context(self, user_query, file_contents):
        """Send query to GPT with file context"""
        context = "\n\n".join([
            f"File: {content['name']}\nContent: {content['text'][:2000]}..."
            for content in file_contents
        ])
        
        messages = [
            {
                "role": "system", 
                "content": """
                You are an AI assistant that can analyze documents from Google Drive. 
                Use the provided file contents to answer user questions.
                Answer directly and add additional suggestions on how to answer questions in the exam
                Always end with  'Is there anything I can hel you with?'
                Your name is Study buddy, happy to help students study more effectively
                
                """
            },
            {
                "role": "user", 
                "content": f"Context from Google Drive files:\n{context}\n\nUser Question: {user_query}"
            }
        ]
        
        response = openai.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            max_tokens=1000
        )
        
        return response.choices[0].message.content
    
    def process_query(self, user_query, search_terms=None):
        """Main function to process user queries"""
        # Extract search terms from query if not provided
        if not search_terms:
            search_terms = user_query.split()[:3]  # Simple extraction
        
        # Search for relevant files
        files = []
        for term in search_terms:
            files.extend(self.search_files(term))
        
        # Remove duplicates
        unique_files = {f['id']: f for f in files}.values()
        
        # Get content from top 3 most relevant files
        file_contents = []
        for file in list(unique_files)[:3]:
            content = self.get_file_content(file['id'], file['mimeType'])
            file_contents.append({
                'name': file['name'],
                'text': content
            })
        
        # Query GPT with context
        if file_contents:
            response = self.query_gpt_with_context(user_query, file_contents)
            return {
                'answer': response,
                'sources': [f['name'] for f in file_contents]
            }
        else:
            return {
                'answer': "No relevant files found in your Google Drive.",
                'sources': []
            }

gpt_drive = GPTDriveIntegration()

def process_user_query(query, search_terms_input):
    """Process user query and return formatted response"""
    if not query.strip():
        return "Please enter a question.", ""
    
    # Parse search terms if provided
    search_terms = None
    # if search_terms_input.strip():
    #     search_terms = [term.strip() for term in search_terms_input.split(',')]
    
    # Process the query
    result = gpt_drive.process_query(query, search_terms)
    
    # Format the response
    answer = result['answer']
    sources = result['sources']
    
    sources_text = ""
    if sources:
        sources_text = "**Sources used:**\n" + "\n".join([f"β€’ {source}" for source in sources])
    
    return answer, sources_text

def check_setup():
    """Check if the APIs are properly configured"""
    status_messages = []
    
    # Check Google Drive API
    if gpt_drive.drive_initialized:
        status_messages.append("βœ… Google Drive API: Connected")
    else:
        status_messages.append(f"❌ Google Drive API: {getattr(gpt_drive, 'drive_error', 'Not configured')}")
    
    # Check OpenAI API
    if gpt_drive.openai_initialized:
        status_messages.append("βœ… OpenAI API: Connected")
    else:
        status_messages.append(f"❌ OpenAI API: {getattr(gpt_drive, 'openai_error', 'Not configured')}")
    
    return "\n".join(status_messages)

# Create Gradio interface
import gradio as gr 
with gr.Blocks(title="Study Buddy", theme=gr.themes.Soft()) as app:
    gr.Markdown("#  Anatomy Study Buddy ")
    gr.Markdown("Study more effectively with study Buddy!")
    
    with gr.Row():
        with gr.Column(scale=2):
            # Main query interface
            with gr.Group():
                gr.Markdown("### Ask a Question")
                query_input = gr.Textbox(
                    label="Your Question",
                    placeholder="Ask me any question about your anatomy books?",
                    lines=3
                )
                
                search_terms_input = gr.Textbox(
                    label="Search Terms",
                    placeholder="Enter comma-separated terms to search for specific files",
                    lines=1
                )
                
                submit_btn = gr.Button("Search & Ask", variant="primary", size="lg")
            
            # Results section
            with gr.Group():
                gr.Markdown("### Answer")
                answer_output = gr.Textbox(
                    label="AI Response",
                    lines=10,
                    interactive=False
                )
                
                sources_output = gr.Textbox(
                    label="Sources",
                    lines=3,
                    interactive=False
                )
        
        # with gr.Column(scale=1):
        #     # Status and setup info
        #     with gr.Group():
        #         gr.Markdown("### System Status")
        #         status_btn = gr.Button("Check Status", size="sm")
        #         status_output = gr.Textbox(
        #             label="API Status",
        #             lines=4,
        #             interactive=False
        #         )
            
    
            # Event handlers
        submit_btn.click(
            fn=process_user_query,
            inputs=[query_input, search_terms_input],
            outputs=[answer_output, sources_output]
            )
            
        # status_btn.click(
        #     fn=check_setup,
        #     outputs=status_output
        #     )
            
            # Example queries
        with gr.Row():
             gr.Examples(
                 examples=[
                    ["What is morbid Anatomy?", "morbid, Anatomy"],
                    ["The transmission of nerves from one neuron to another is as a result of what?", "neuron, nerves, Dr Clement"],
                    ["Explain what the external ear contains of?", "Ear Anatomy, Ear"],
                    ["What are the types of massage?", "massage Lecture, nerves"],
                    ["What is trauma?", "Trauma, pysical trauma and sex Offenders"],
                    ["what is Upper limb prosthetics?", "Upper limb prosthetics"],
                    ],
                    inputs=[query_input, search_terms_input],)


# Launch the app
if __name__ == "__main__":
    app.launch(
        share=True,debug =True)