Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,161 +1,174 @@
|
|
| 1 |
-
from fastapi import FastAPI, UploadFile, Form, HTTPException
|
| 2 |
-
from pydantic import BaseModel
|
| 3 |
-
import uvicorn
|
| 4 |
-
from fastapi.responses import JSONResponse
|
| 5 |
-
from typing import Dict
|
| 6 |
-
import hashlib
|
| 7 |
-
from openai import OpenAI
|
| 8 |
-
from dotenv import load_dotenv
|
| 9 |
-
import os
|
| 10 |
-
load_dotenv()
|
| 11 |
-
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
|
| 12 |
-
# from pathlib import Path
|
| 13 |
-
# from langchain_community.document_loaders import WebBaseLoade as genai
|
| 14 |
-
import os
|
| 15 |
-
import re
|
| 16 |
-
import pandas as pd
|
| 17 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 18 |
-
from firebase_admin import firestore
|
| 19 |
-
import json
|
| 20 |
-
import google.generativeai as genai
|
| 21 |
-
from google.generativeai import GenerativeModel
|
| 22 |
-
|
| 23 |
-
# Initialize Gemini LLM
|
| 24 |
-
# load_dotenv()
|
| 25 |
-
# Google_key = os.getenv("GOOGLE_API_KEY")
|
| 26 |
-
# print(str(Google_key))
|
| 27 |
-
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
| 28 |
-
model = genai.GenerativeModel("gemini-2.0-flash")
|
| 29 |
-
import firebase_admin
|
| 30 |
-
from firebase_admin import credentials
|
| 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 |
-
def
|
| 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 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, Form, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import uvicorn
|
| 4 |
+
from fastapi.responses import JSONResponse
|
| 5 |
+
from typing import Dict
|
| 6 |
+
import hashlib
|
| 7 |
+
from openai import OpenAI
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
import os
|
| 10 |
+
load_dotenv()
|
| 11 |
+
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
|
| 12 |
+
# from pathlib import Path
|
| 13 |
+
# from langchain_community.document_loaders import WebBaseLoade as genai
|
| 14 |
+
import os
|
| 15 |
+
import re
|
| 16 |
+
import pandas as pd
|
| 17 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 18 |
+
from firebase_admin import firestore
|
| 19 |
+
import json
|
| 20 |
+
import google.generativeai as genai
|
| 21 |
+
from google.generativeai import GenerativeModel
|
| 22 |
+
|
| 23 |
+
# Initialize Gemini LLM
|
| 24 |
+
# load_dotenv()
|
| 25 |
+
# Google_key = os.getenv("GOOGLE_API_KEY")
|
| 26 |
+
# print(str(Google_key))
|
| 27 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
| 28 |
+
model = genai.GenerativeModel("gemini-2.0-flash")
|
| 29 |
+
import firebase_admin
|
| 30 |
+
from firebase_admin import credentials
|
| 31 |
+
|
| 32 |
+
cred_dict = {
|
| 33 |
+
"type": "service_account",
|
| 34 |
+
"project_id": os.environ.get("FIREBASE_PROJECT_ID", "fir-502e5"),
|
| 35 |
+
"private_key_id": os.environ.get("FIREBASE_PRIVATE_KEY_ID"),
|
| 36 |
+
"private_key": os.environ.get("FIREBASE_PRIVATE_KEY", "").replace("\\n", "\n"),
|
| 37 |
+
"client_email": os.environ.get("FIREBASE_CLIENT_EMAIL"),
|
| 38 |
+
"client_id": os.environ.get("FIREBASE_CLIENT_ID"),
|
| 39 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
| 40 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
| 41 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
| 42 |
+
"client_x509_cert_url": os.environ.get("FIREBASE_CLIENT_X509_CERT_URL"),
|
| 43 |
+
"universe_domain": "googleapis.com"
|
| 44 |
+
}
|
| 45 |
+
# cred = credentials.Certificate("/content/ir-502e5-firebase-adminsdk-3der0-0145a61d7a.json")
|
| 46 |
+
# firebase_admin.initialize_app(cred)
|
| 47 |
+
|
| 48 |
+
app = FastAPI()
|
| 49 |
+
|
| 50 |
+
app.add_middleware(
|
| 51 |
+
CORSMiddleware,
|
| 52 |
+
allow_origins=["*"],
|
| 53 |
+
allow_credentials=True,
|
| 54 |
+
allow_methods=["*"],
|
| 55 |
+
allow_headers=["*"],
|
| 56 |
+
)
|
| 57 |
+
def generate_df():
|
| 58 |
+
data = []
|
| 59 |
+
cred = credentials.Certificate(cred_dict)
|
| 60 |
+
firebase_admin.initialize_app(cred)
|
| 61 |
+
db = firestore.client()
|
| 62 |
+
docs = db.collection("test_results").get()
|
| 63 |
+
for doc in docs:
|
| 64 |
+
doc_data = doc.to_dict()
|
| 65 |
+
doc_data['id'] = doc.id
|
| 66 |
+
data.append(doc_data)
|
| 67 |
+
df = pd.DataFrame(data)
|
| 68 |
+
return df
|
| 69 |
+
|
| 70 |
+
def generate_feedback(email, test_id):
|
| 71 |
+
df = generate_df()
|
| 72 |
+
df_email = df[df['email'] == email]
|
| 73 |
+
df_test_id = df_email[df_email['id'] == test_id]
|
| 74 |
+
if not df_test_id.empty:
|
| 75 |
+
response = df_test_id['responses'].values[0]
|
| 76 |
+
feedback = model.generate_content(f"""You are an experienced tutor analyzing a student's test responses to provide constructive feedback. Below is the student's test history in JSON format. Your task is to:
|
| 77 |
+
|
| 78 |
+
Identify Strengths: Highlight areas where the student performed well, demonstrating a strong understanding of the concepts.
|
| 79 |
+
|
| 80 |
+
Identify Weaknesses: Point out areas where the student struggled or made consistent errors, indicating gaps in understanding.
|
| 81 |
+
|
| 82 |
+
Provide Actionable Suggestions: Offer specific advice on how the student can improve their performance in future tests.
|
| 83 |
+
|
| 84 |
+
Encourage and Motivate: End with positive reinforcement to keep the student motivated.
|
| 85 |
+
Test History:{str(response)} """)
|
| 86 |
+
return feedback.text
|
| 87 |
+
else:
|
| 88 |
+
print("No test results found for this id")
|
| 89 |
+
def generate_overall_feedback(email):
|
| 90 |
+
df = generate_df()
|
| 91 |
+
df_email = df[df['email'] == email]
|
| 92 |
+
if not df_email.empty:
|
| 93 |
+
response = df_email['responses'].values
|
| 94 |
+
feedback = model.generate_content(f"""You are an experienced tutor analyzing a student's test responses to provide constructive feedback. Below is the student's test history in list format. Your task is to:
|
| 95 |
+
Identify Strengths: Highlight areas where the student performed well, demonstrating a strong understanding of the concepts.
|
| 96 |
+
|
| 97 |
+
Identify Weaknesses: Point out areas where the student struggled or made consistent errors, indicating gaps in understanding.
|
| 98 |
+
|
| 99 |
+
Provide Actionable Suggestions: Offer specific advice on how the student can improve their performance in future tests.
|
| 100 |
+
|
| 101 |
+
Encourage and Motivate: End with positive reinforcement to keep the student motivated.
|
| 102 |
+
|
| 103 |
+
Test History:{str(response)} """)
|
| 104 |
+
return feedback.text
|
| 105 |
+
else:
|
| 106 |
+
print("Please try again with a valid email")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@app.post("/get_single_feedback")
|
| 113 |
+
async def get_single_feedback(email: str, test_id: str):
|
| 114 |
+
feedback = generate_feedback(email, test_id)
|
| 115 |
+
return JSONResponse(content={"feedback": feedback})
|
| 116 |
+
|
| 117 |
+
@app.post("/get_overall_feedback")
|
| 118 |
+
async def get_overall_feedback(email: str):
|
| 119 |
+
feedback = generate_overall_feedback(email)
|
| 120 |
+
return JSONResponse(content={"feedback": feedback})
|
| 121 |
+
|
| 122 |
+
@app.post("/get_strong_weak_topics")
|
| 123 |
+
async def get_strong_weak_topics(email: str):
|
| 124 |
+
df = generate_df()
|
| 125 |
+
df_email = df[df['email'] == email]
|
| 126 |
+
if not df_email.empty:
|
| 127 |
+
response = df_email['responses'].values
|
| 128 |
+
# Assuming response is a list of responses
|
| 129 |
+
formatted_data = str(response) # Convert response to a string format suitable for the API call
|
| 130 |
+
section_info = {
|
| 131 |
+
'filename': 'student_performance',
|
| 132 |
+
'schema': {
|
| 133 |
+
'weak_topics': ['Topic#1', 'Topic#2', '...'],
|
| 134 |
+
'strong_topics': ['Topic#1', 'Topic#2', '...']
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
# Generate response using the client
|
| 139 |
+
completion = client.chat.completions.create(
|
| 140 |
+
model="gpt-4o",
|
| 141 |
+
response_format={"type": "json_object"},
|
| 142 |
+
messages=[
|
| 143 |
+
{
|
| 144 |
+
"role": "system",
|
| 145 |
+
"content": f"""You are an Educational Performance Analyst focusing on {section_info['filename'].replace('_', ' ')}.
|
| 146 |
+
Analyze the provided student responses to identify and categorize topics into 'weak' and 'strong' based on their performance. Try to give
|
| 147 |
+
high level topics like algebra, trignometry, geometry etc in your response.
|
| 148 |
+
Do not add any explanations, introduction, or comments - return ONLY valid JSON.
|
| 149 |
+
"""
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"role": "user",
|
| 153 |
+
"content": f"""
|
| 154 |
+
Here is the raw data for {section_info['filename']}:
|
| 155 |
+
|
| 156 |
+
{formatted_data}
|
| 157 |
+
|
| 158 |
+
Convert this data into JSON that matches this schema:
|
| 159 |
+
{json.dumps(section_info['schema'], indent=2)}
|
| 160 |
+
"""
|
| 161 |
+
}
|
| 162 |
+
],
|
| 163 |
+
temperature=0.0
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
# Extract the JSON content from the completion object
|
| 167 |
+
strong_weak_topics = completion.choices[0].message.content # Access the content attribute directly
|
| 168 |
+
|
| 169 |
+
return JSONResponse(content=json.loads(strong_weak_topics))
|
| 170 |
+
else:
|
| 171 |
+
return JSONResponse(content={"error": "No test results found for this email"})
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|