ak0601 commited on
Commit
c793218
·
verified ·
1 Parent(s): bf9121d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -160
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
- # cred = credentials.Certificate("/content/ir-502e5-firebase-adminsdk-3der0-0145a61d7a.json")
33
- # firebase_admin.initialize_app(cred)
34
-
35
- app = FastAPI()
36
-
37
- app.add_middleware(
38
- CORSMiddleware,
39
- allow_origins=["*"],
40
- allow_credentials=True,
41
- allow_methods=["*"],
42
- allow_headers=["*"],
43
- )
44
- def generate_df():
45
- data = []
46
- cred = credentials.Certificate("G:/Cognozire/Alguru/Feeback_Api's/fir-502e5-firebase-adminsdk-3der0-0145a61d7a.json")
47
- firebase_admin.initialize_app(cred)
48
- db = firestore.client()
49
- docs = db.collection("test_results").get()
50
- for doc in docs:
51
- doc_data = doc.to_dict()
52
- doc_data['id'] = doc.id
53
- data.append(doc_data)
54
- df = pd.DataFrame(data)
55
- return df
56
-
57
- def generate_feedback(email, test_id):
58
- df = generate_df()
59
- df_email = df[df['email'] == email]
60
- df_test_id = df_email[df_email['id'] == test_id]
61
- if not df_test_id.empty:
62
- response = df_test_id['responses'].values[0]
63
- 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:
64
-
65
- Identify Strengths: Highlight areas where the student performed well, demonstrating a strong understanding of the concepts.
66
-
67
- Identify Weaknesses: Point out areas where the student struggled or made consistent errors, indicating gaps in understanding.
68
-
69
- Provide Actionable Suggestions: Offer specific advice on how the student can improve their performance in future tests.
70
-
71
- Encourage and Motivate: End with positive reinforcement to keep the student motivated.
72
- Test History:{str(response)} """)
73
- return feedback.text
74
- else:
75
- print("No test results found for this id")
76
- def generate_overall_feedback(email):
77
- df = generate_df()
78
- df_email = df[df['email'] == email]
79
- if not df_email.empty:
80
- response = df_email['responses'].values
81
- 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:
82
- Identify Strengths: Highlight areas where the student performed well, demonstrating a strong understanding of the concepts.
83
-
84
- Identify Weaknesses: Point out areas where the student struggled or made consistent errors, indicating gaps in understanding.
85
-
86
- Provide Actionable Suggestions: Offer specific advice on how the student can improve their performance in future tests.
87
-
88
- Encourage and Motivate: End with positive reinforcement to keep the student motivated.
89
-
90
- Test History:{str(response)} """)
91
- return feedback.text
92
- else:
93
- print("Please try again with a valid email")
94
-
95
-
96
-
97
-
98
-
99
- @app.post("/get_single_feedback")
100
- async def get_single_feedback(email: str, test_id: str):
101
- feedback = generate_feedback(email, test_id)
102
- return JSONResponse(content={"feedback": feedback})
103
-
104
- @app.post("/get_overall_feedback")
105
- async def get_overall_feedback(email: str):
106
- feedback = generate_overall_feedback(email)
107
- return JSONResponse(content={"feedback": feedback})
108
-
109
- @app.post("/get_strong_weak_topics")
110
- async def get_strong_weak_topics(email: str):
111
- df = generate_df()
112
- df_email = df[df['email'] == email]
113
- if not df_email.empty:
114
- response = df_email['responses'].values
115
- # Assuming response is a list of responses
116
- formatted_data = str(response) # Convert response to a string format suitable for the API call
117
- section_info = {
118
- 'filename': 'student_performance',
119
- 'schema': {
120
- 'weak_topics': ['Topic#1', 'Topic#2', '...'],
121
- 'strong_topics': ['Topic#1', 'Topic#2', '...']
122
- }
123
- }
124
-
125
- # Generate response using the client
126
- completion = client.chat.completions.create(
127
- model="gpt-4o",
128
- response_format={"type": "json_object"},
129
- messages=[
130
- {
131
- "role": "system",
132
- "content": f"""You are an Educational Performance Analyst focusing on {section_info['filename'].replace('_', ' ')}.
133
- Analyze the provided student responses to identify and categorize topics into 'weak' and 'strong' based on their performance. Try to give
134
- high level topics like algebra, trignometry, geometry etc in your response.
135
- Do not add any explanations, introduction, or comments - return ONLY valid JSON.
136
- """
137
- },
138
- {
139
- "role": "user",
140
- "content": f"""
141
- Here is the raw data for {section_info['filename']}:
142
-
143
- {formatted_data}
144
-
145
- Convert this data into JSON that matches this schema:
146
- {json.dumps(section_info['schema'], indent=2)}
147
- """
148
- }
149
- ],
150
- temperature=0.0
151
- )
152
-
153
- # Extract the JSON content from the completion object
154
- strong_weak_topics = completion.choices[0].message.content # Access the content attribute directly
155
-
156
- return JSONResponse(content=json.loads(strong_weak_topics))
157
- else:
158
- return JSONResponse(content={"error": "No test results found for this email"})
159
-
160
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
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)