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
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
from fastapi import FastAPI, UploadFile, File, HTTPException, Depends, Header
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import google.generativeai as genai
from typing import List
import os
from dotenv import load_dotenv
import io
from datetime import datetime, timedelta
import uuid

import json
import re

# File Format Libraries
import PyPDF2
import docx
import openpyxl
import csv
import io
import pptx
from db import get_db, Chat, ChatMessage, User, Document, SessionLocal
from pyqs import get_q_paper

from fastapi.security import OAuth2PasswordBearer
import requests
from jose import jwt
import random

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

load_dotenv()

GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = os.getenv('GOOGLE_CLIENT_SECRET')
GOOGLE_REDIRECT_URI = os.getenv('GOOGLE_REDIRECT_URI')

api_keys = os.getenv('GEMINI_API_KEYS').split(',')



def parse_json_from_gemini(json_str: str):
    try:
        # Remove potential leading/trailing whitespace
        json_str = json_str.strip()
        # Extract JSON content from triple backticks and "json" language specifier
        json_match = re.search(r"```json\s*(.*?)\s*```", json_str, re.DOTALL)
        if json_match:
            json_str = json_match.group(1)
        return json.loads(json_str)
    except (json.JSONDecodeError, AttributeError):
        return None

load_dotenv()

app = FastAPI(title="EduScope AI")

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/login/google")
async def login_google():
    return {
        "url": f"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={GOOGLE_CLIENT_ID}&redirect_uri={GOOGLE_REDIRECT_URI}&scope=openid%20profile%20email&access_type=offline"
    }

@app.get("/auth/google")
async def auth_google(code: str, db: SessionLocal = Depends(get_db)):
    token_url = "https://accounts.google.com/o/oauth2/token"
    data = {
        "code": code,
        "client_id": GOOGLE_CLIENT_ID,
        "client_secret": GOOGLE_CLIENT_SECRET,
        "redirect_uri": GOOGLE_REDIRECT_URI,
        "grant_type": "authorization_code",
    }
    response = requests.post(token_url, data=data)
    access_token = response.json().get("access_token")
    user_info = requests.get("https://www.googleapis.com/oauth2/v1/userinfo", headers={"Authorization": f"Bearer {access_token}"}).json()
    user = db.query(User).filter(User.id == user_info["id"]).first()
    if not user:
        user = User(id=user_info["id"], email=user_info["email"], name=user_info["name"])
        db.add(user)
        db.commit()

    return {"token": jwt.encode(user_info, GOOGLE_CLIENT_SECRET, algorithm="HS256")}
    # return user_info.json()


async def decode_token(authorization: str = Header(...)):
    if not authorization.startswith("Bearer "):
        raise HTTPException(
            status_code=400,
            detail="Authorization header must start with 'Bearer '"
        )
    
    token = authorization[len("Bearer "):]  # Extract token part

    try:
        # Decode and verify the JWT token
        token_data = jwt.decode(token, GOOGLE_CLIENT_SECRET, algorithms=["HS256"])
        return token_data  # Return decoded token data
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token has expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")
    

@app.get("/token")
async def get_token(user_data: dict = Depends(decode_token)):
    return user_data


@app.post("/chats")
async def create_chat(title: str, user_data: dict = Depends(decode_token), db: SessionLocal = Depends(get_db)):
    user_id = user_data["id"]

    chat = Chat(chat_id=str(uuid.uuid4()), user_id=user_id, title=title)
    db.add(chat)
    db.commit()
    return {"chat_id": chat.chat_id, "title": title, "timestamp": chat.timestamp}


@app.get("/chats")
async def get_chats(user_data: dict = Depends(decode_token), db: SessionLocal = Depends(get_db)):
    user_id = user_data["id"]

    chats = db.query(Chat).filter(Chat.user_id == user_id).all()
    return [{"chat_id": chat.chat_id, "title": chat.title, "timestamp": chat.timestamp} for chat in chats]



class DocumentSchema(BaseModel):
    id: str
    name: str
    timestamp: str

class Query(BaseModel):
    text: str
    selected_docs: List[str]

class ChatMessageSchema(BaseModel):
    id: str
    type: str  # 'user' or 'assistant'
    content: str
    timestamp: str
    referenced_docs: List[str] = []

class Analysis(BaseModel):
    insight: str
    pareto_analysis: dict

def extract_text_from_file(file: UploadFile):
    """

    Extract text from various file types

    Supports: PDF, DOCX, XLSX, CSV, TXT, PPTX

    """
    file_extension = os.path.splitext(file.filename)[1].lower()
    content = file.file.read()
    print(file_extension)
    
    try:
        if file_extension == '.pdf':
            pdf_reader = PyPDF2.PdfReader(io.BytesIO(content))
            text = "\n".join([page.extract_text() for page in pdf_reader.pages])
        
        elif file_extension == '.docx':
            doc = docx.Document(io.BytesIO(content))
            text = "\n".join([para.text for para in doc.paragraphs])
        
        elif file_extension == '.xlsx':
            wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True)
            text = ""
            for sheet in wb:
                for row in sheet.iter_rows(values_only=True):
                    text += " ".join(str(cell) for cell in row if cell is not None) + "\n"
        
        elif file_extension == '.csv':
            csv_reader = csv.reader(io.StringIO(content.decode('utf-8')))
            text = "\n".join([" ".join(row) for row in csv_reader])
        
        elif file_extension == '.txt':
            text = content.decode('utf-8')

        elif file_extension in ['.ppt', '.pptx']:
            ppt = pptx.Presentation(io.BytesIO(content))
            text = ""
            for slide in ppt.slides:
                for shape in slide.shapes:
                    if hasattr(shape, "text"):
                        text += shape.text + "\n"
        
        else:
            raise ValueError(f"Unsupported file type: {file_extension}")
        
        return text
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Error processing file: {str(e)}")


@app.get("/searchBySubjectCode")
async def search_by_subject_code(subject_code: str, user_data: dict = Depends(decode_token)):
    codes = requests.get(f"https://cl.thapar.edu/search1.php?term={subject_code}",verify=False).json()
    return codes


@app.get("/chats/{chat_id}/importQPapers")
async def import_q_papers(chat_id: str, subject_code: str, user_data: dict = Depends(decode_token), db: SessionLocal = Depends(get_db)):
    user_id = user_data["id"]

    chat = db.query(Chat).filter(Chat.chat_id == chat_id, Chat.user_id == user_id).first()
    if not chat:
        raise HTTPException(status_code=404, detail="Chat not found")

    q_papers = get_q_paper(subject_code)
    if not q_papers:
        raise HTTPException(status_code=404, detail="No question papers found for the given subject code")
    
    for paper in q_papers:
        download_link = paper["DownloadLink"]
        response = requests.get(download_link, verify=False)
        if response.status_code != 200:
            raise HTTPException(status_code=500, detail=f"Failed to download the paper from {download_link}")

        try:
            pdf_reader = PyPDF2.PdfReader(io.BytesIO(response.content))
            text = "\n".join([page.extract_text() for page in pdf_reader.pages])
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"Failed to process PDF: {str(e)}")
        
        title = f"{paper['CourseName']}_{paper['Year']}_{paper['Semester']}_{paper['ExamType']}..pdf"
        doc_id = str(uuid.uuid4())

        document = Document(
            id=doc_id,
            chat_id=chat_id,
            name=title,
            content=text,
            timestamp=datetime.now()
        )
        db.add(document)
    
    db.commit()
    return {"message": "Question papers imported successfully"}


@app.post("/chats/{chat_id}/upload")
async def upload_document(chat_id: str, file: UploadFile = File(...), user_data: dict = Depends(decode_token), db: SessionLocal = Depends(get_db)):
    user_id = user_data["id"]
    # Check if the chat exists and belongs to the user
    chat = db.query(Chat).filter(Chat.chat_id == chat_id, Chat.user_id == user_id).first()
    if not chat:
        raise HTTPException(status_code=404, detail="Chat not found")
    try:
        text = extract_text_from_file(file)
        doc_id = str(uuid.uuid4())
        document = Document(
            id=doc_id,
            chat_id=chat_id,
            name=file.filename,
            content=text,
            timestamp=datetime.now()
        )
        db.add(document)
        db.commit()
        db.refresh(document)
        return {
            "id": document.id,
            "name": document.name,
            "timestamp": document.timestamp.isoformat()
        }
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")

@app.get("/chats/{chat_id}/documents")
async def get_documents(chat_id: str, user_data: dict = Depends(decode_token), db: SessionLocal = Depends(get_db)):
    user_id = user_data["id"]
    chat = db.query(Chat).filter(Chat.chat_id == chat_id, Chat.user_id == user_id).first()
    if not chat:
        raise HTTPException(status_code=404, detail="Chat not found")
    documents = db.query(Document).filter(Document.chat_id == chat_id).all()
    return [{
        "id": doc.id,
        "name": doc.name,
        "timestamp": doc.timestamp.isoformat()
    } for doc in documents]

@app.post("/chats/{chat_id}/analyze", response_model=Analysis)
async def analyze_text(chat_id: str, query: Query, user_data: dict = Depends(decode_token), db: SessionLocal = Depends(get_db)):
    user_id = user_data["id"]
    # Check if the chat exists and belongs to the user
    chat = db.query(Chat).filter(Chat.chat_id == chat_id, Chat.user_id == user_id).first()
    if not chat:
        raise HTTPException(status_code=404, detail="Chat not found")
    # Fetch documents
    docs = db.query(Document).filter(Document.chat_id == chat_id, Document.id.in_(query.selected_docs)).all()
    if not docs:
        raise HTTPException(status_code=400, detail="No documents found for analysis")
    # Combine content from selected documents
    combined_context = "\n\n".join([
        f"Document '{doc.name}':\n{doc.content}" for doc in docs
    ])
    
    prompt = f"""

    Analyze the following text in the context of this query: {query.text}



    Context from multiple documents:

    {combined_context}



    Provide:

    1. Detailed insights and analysis, comparing information across documents when relevant

    2. Apply the Pareto Principle (80/20 rule) to identify the most important aspects



    Format the response as JSON with 'insight' and 'pareto_analysis' keys.



    Example format:

    {{

        "insight": "Key findings and analysis from the documents based on query...",

        "pareto_analysis": {{

            "vital_few": "The 20% of factors that drive 80% of the impact...",

            "trivial_many": "The remaining 80% of factors that contribute 20% of the impact..."

        }}

    }}



    also give a complete html document with a intreactive quiz (minimum 5 questions) using jquery and also a flashcards to help the user understand the content better.

    """
    
    api_key = random.choice(api_keys)
    genai.configure(api_key=api_key)
    print("Selected API Key: ", api_key)
    
    model = genai.GenerativeModel('gemini-1.5-flash')

    response = model.generate_content(prompt)
    response_text = response.text

    # Save user message
    user_message = ChatMessage(
        id=str(uuid.uuid4()),
        chat_id=chat_id,
        type="user",
        content=query.text,
        timestamp=datetime.now(),
        referenced_docs=json.dumps(query.selected_docs)
    )
    db.add(user_message)
    # Parse analysis
    analysis = parse_json_from_gemini(response_text)
    # Save assistant message

    assistant_message = ChatMessage(
        id=str(uuid.uuid4()),
        chat_id=chat_id,
        type="assistant",
        content=json.dumps(analysis, indent=4),
        timestamp=datetime.now() -timedelta(seconds=3),
        referenced_docs=json.dumps(query.selected_docs)
    )

    db.add(assistant_message)

    if '```html' in response_text:
        html = response_text.split('```html')[1]
        html = html.split('```')[0]
        html = html.strip()
        assistant_message_1 = ChatMessage(
            id=str(uuid.uuid4()),
            chat_id=chat_id,
            type="assistant",
            content=html,
            timestamp=datetime.now(),
            referenced_docs=json.dumps(query.selected_docs)
        )

        db.add(assistant_message_1)

    db.commit()
    return analysis

@app.get("/chats/{chat_id}/chat-history")
async def get_chat_history(chat_id: str, user_data: dict = Depends(decode_token), db: SessionLocal = Depends(get_db)):
    user_id = user_data["id"]
    # Check if the chat exists and belongs to the user
    chat = db.query(Chat).filter(Chat.chat_id == chat_id, Chat.user_id == user_id).first()
    if not chat:
        raise HTTPException(status_code=404, detail="Chat not found")
    messages = db.query(ChatMessage).filter(ChatMessage.chat_id == chat_id).order_by(ChatMessage.timestamp).all()
    return [{
        "id": msg.id,
        "type": msg.type,
        "content": msg.content,
        "timestamp": msg.timestamp.isoformat(),
        "referenced_docs": json.loads(msg.referenced_docs) if msg.referenced_docs else []
    } for msg in messages]

@app.delete("/chats/{chat_id}/clear")
async def clear_chat(chat_id: str, user_data: dict = Depends(decode_token), db: SessionLocal = Depends(get_db)):
    user_id = user_data["id"]
    chat = db.query(Chat).filter(Chat.chat_id == chat_id, Chat.user_id == user_id).first()
    if not chat:
        raise HTTPException(status_code=404, detail="Chat not found")
    # Delete documents and messages
    db.query(Document).filter(Document.chat_id == chat_id).delete()
    db.query(ChatMessage).filter(ChatMessage.chat_id == chat_id).delete()
    db.commit()
    return {"message": "Chat cleared successfully"}



if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)