barathm111 commited on
Commit
d29a8b2
1 Parent(s): fb4eb7d

Upload 3 files

Browse files
Files changed (3) hide show
  1. main.py +74 -0
  2. performance_analyzer.py +229 -0
  3. requirements.txt +3 -1
main.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from performance_analyzer import CollegePerformanceAnalyzer
3
+
4
+ def run_performance_analysis(seed: int = None, use_ai_insights: bool = True):
5
+ """
6
+ Main function to orchestrate college performance analysis.
7
+
8
+ Args:
9
+ seed (int, optional): Random seed for reproducible results
10
+ use_ai_insights (bool): Toggle AI-generated strategic insights
11
+
12
+ Returns:
13
+ Comprehensive performance analysis report
14
+ """
15
+ # Initialize performance analyzer
16
+ analyzer = CollegePerformanceAnalyzer()
17
+
18
+ # Generate performance scores
19
+ parameters = analyzer.generate_performance_scores(seed)
20
+
21
+ # Calculate comprehensive metrics
22
+ analysis_results = analyzer.calculate_weighted_metrics(parameters)
23
+
24
+ # Generate feedback based on user preference
25
+ ai_feedback = (
26
+ analyzer.generate_ai_feedback(analysis_results)
27
+ if use_ai_insights
28
+ else analyzer._generate_manual_feedback(analysis_results)
29
+ )
30
+
31
+ # Combine performance report with strategic insights
32
+ report = f"""
33
+ # 🎓 College Performance Analysis Report
34
+
35
+ ## Performance Metrics
36
+
37
+ {' '.join([
38
+ f"**{details['full_name']}**: {details['score']}/100 "
39
+ for param, details in analysis_results['parameters'].items()
40
+ ])}
41
+
42
+ ## Overall Performance
43
+
44
+ - **Total Weighted Score**: {analysis_results['total_weighted_score']:.2f}
45
+ - **Predicted NIRF Rank**: {analysis_results['nirf_rank']}
46
+ - **Institutional Rating**: {analysis_results['overall_rating']}/5
47
+
48
+ ## Strategic Insights
49
+
50
+ {ai_feedback}
51
+ """
52
+
53
+ return report
54
+
55
+ def create_gradio_interface():
56
+ """
57
+ Create interactive Gradio web interface for performance analysis.
58
+ """
59
+ iface = gr.Interface(
60
+ fn=run_performance_analysis,
61
+ inputs=[
62
+ gr.Number(label="Random Seed (Optional)", precision=0, optional=True),
63
+ gr.Checkbox(label="Generate AI Insights", value=True)
64
+ ],
65
+ outputs=gr.Markdown(label="Performance Analysis Report"),
66
+ title="🏫 College Performance Analyzer",
67
+ description="Generate comprehensive performance insights with optional AI-powered strategic analysis.",
68
+ theme="default"
69
+ )
70
+ return iface
71
+
72
+ if __name__ == "__main__":
73
+ interface = create_gradio_interface()
74
+ interface.launch()
performance_analyzer.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ from typing import Dict, Any
4
+ from huggingface_hub import InferenceClient
5
+
6
+ class CollegePerformanceAnalyzer:
7
+ def __init__(self):
8
+ """
9
+ Initialize the College Performance Analyzer with secure token management.
10
+
11
+ This method handles:
12
+ - Retrieving Hugging Face token from environment secrets
13
+ - Initializing the Inference Client
14
+ - Setting up performance parameters
15
+ """
16
+ try:
17
+ # Securely retrieve HF token from environment variables
18
+ hf_token = os.environ.get('HF_TOKEN')
19
+
20
+ if not hf_token:
21
+ raise ValueError("No Hugging Face token found. Please set it as a Space secret.")
22
+
23
+ # Initialize Inference Client with secure token
24
+ self.client = InferenceClient(
25
+ model="mistralai/Mistral-7B-Instruct-v0.1",
26
+ token=hf_token
27
+ )
28
+ except Exception as e:
29
+ print(f"Inference Client Error: {e}")
30
+ self.client = None
31
+
32
+ # Define performance parameters
33
+ self.parameters = self.define_performance_parameters()
34
+
35
+ def define_performance_parameters(self) -> Dict[str, Dict[str, Any]]:
36
+ """
37
+ Define comprehensive college performance parameters with weights.
38
+
39
+ Returns a dictionary of parameters with:
40
+ - Weight in overall performance
41
+ - Full descriptive name
42
+ """
43
+ return {
44
+ "SS": {
45
+ "weight": 0.06,
46
+ "full_name": "Student Strength",
47
+ "description": "Total student population and diversity"
48
+ },
49
+ "FSR": {
50
+ "weight": 0.075,
51
+ "full_name": "Faculty-Student Ratio",
52
+ "description": "Quality of academic interaction and support"
53
+ },
54
+ "FQE": {
55
+ "weight": 0.06,
56
+ "full_name": "Faculty Qualification Efficiency",
57
+ "description": "Academic credentials and expertise of faculty"
58
+ },
59
+ "FRU": {
60
+ "weight": 0.06,
61
+ "full_name": "Faculty Research Utility",
62
+ "description": "Research output and impact"
63
+ },
64
+ "OE+MIR": {
65
+ "weight": 0.03,
66
+ "full_name": "Outreach & Industry Engagement",
67
+ "description": "External collaborations and industry connections"
68
+ },
69
+ "GUE": {
70
+ "weight": 0.12,
71
+ "full_name": "Graduate Unemployment Excellence",
72
+ "description": "Job placement and career success rates"
73
+ },
74
+ "GPHD": {
75
+ "weight": 0.08,
76
+ "full_name": "Graduate PhD Pursuit",
77
+ "description": "Higher education and research career progression"
78
+ },
79
+ "RD": {
80
+ "weight": 0.03,
81
+ "full_name": "Research Development",
82
+ "description": "Research funding and publication quality"
83
+ },
84
+ "WD": {
85
+ "weight": 0.03,
86
+ "full_name": "Worldwide Diversity",
87
+ "description": "International student and faculty representation"
88
+ },
89
+ "ESCS": {
90
+ "weight": 0.02,
91
+ "full_name": "Economic & Social Campus Sustainability",
92
+ "description": "Environmental and social responsibility initiatives"
93
+ },
94
+ "PCS": {
95
+ "weight": 0.02,
96
+ "full_name": "Peer Campus Satisfaction",
97
+ "description": "Student and faculty satisfaction surveys"
98
+ },
99
+ "PR": {
100
+ "weight": 0.10,
101
+ "full_name": "Perception Rating",
102
+ "description": "Reputation and public perception"
103
+ }
104
+ }
105
+
106
+ def generate_performance_scores(self, seed: int = None) -> Dict:
107
+ """
108
+ Generate random performance scores with optional seed for reproducibility.
109
+
110
+ Args:
111
+ seed (int, optional): Random seed for consistent score generation
112
+
113
+ Returns:
114
+ Dict with generated performance scores
115
+ """
116
+ if seed is not None:
117
+ random.seed(seed)
118
+
119
+ parameters = self.parameters.copy()
120
+ for param in parameters:
121
+ parameters[param]["score"] = random.randint(0, 100)
122
+
123
+ return parameters
124
+
125
+ def calculate_weighted_metrics(self, parameters: Dict) -> Dict:
126
+ """
127
+ Calculate comprehensive weighted performance metrics.
128
+
129
+ Computes:
130
+ - Weighted scores
131
+ - Total performance score
132
+ - NIRF ranking
133
+ - Overall rating
134
+ """
135
+ # Calculate weighted scores
136
+ for param, values in parameters.items():
137
+ values["weighted_score"] = values["score"] * values["weight"]
138
+
139
+ # Compute total weighted score
140
+ total_weighted_score = sum(
141
+ values["weighted_score"] for values in parameters.values()
142
+ )
143
+
144
+ # Calculate ranking and rating
145
+ nirf_rank = int((1000 - total_weighted_score) / 10)
146
+ average_score = sum(values["score"] for values in parameters.values()) / len(parameters)
147
+ overall_rating = round(average_score / 20) # Convert to 1-5 scale
148
+
149
+ return {
150
+ "parameters": parameters,
151
+ "total_weighted_score": total_weighted_score,
152
+ "nirf_rank": nirf_rank,
153
+ "overall_rating": overall_rating
154
+ }
155
+
156
+ def generate_ai_feedback(self, analysis_results: Dict) -> str:
157
+ """
158
+ Generate AI-powered strategic insights using Mistral model.
159
+
160
+ Provides comprehensive, actionable feedback on college performance.
161
+ """
162
+ if not self.client:
163
+ return self._generate_manual_feedback(analysis_results)
164
+
165
+ # Construct detailed feedback prompt
166
+ feedback_prompt = self._construct_feedback_prompt(analysis_results)
167
+
168
+ try:
169
+ completion = self.client.text_generation(
170
+ model="mistralai/Mistral-7B-Instruct-v0.1",
171
+ prompt=feedback_prompt,
172
+ max_new_tokens=500,
173
+ temperature=0.7,
174
+ top_p=0.9,
175
+ repetition_penalty=1.1
176
+ )
177
+ return completion
178
+ except Exception as e:
179
+ print(f"AI Feedback Generation Error: {e}")
180
+ return self._generate_manual_feedback(analysis_results)
181
+
182
+ def _construct_feedback_prompt(self, analysis_results: Dict) -> str:
183
+ """
184
+ Create a structured prompt for AI feedback generation.
185
+ """
186
+ parameters = analysis_results['parameters']
187
+ overall_rating = analysis_results['overall_rating']
188
+
189
+ prompt = "Comprehensive College Performance Strategic Analysis:\n\n"
190
+ prompt += "Performance Metrics:\n"
191
+
192
+ for param, details in parameters.items():
193
+ prompt += f"{details['full_name']}: {details['score']}/100\n"
194
+
195
+ prompt += f"\nOverall Rating: {overall_rating}/5\n\n"
196
+ prompt += "Provide a detailed strategic analysis including:\n"
197
+ prompt += "1. Key institutional strengths\n"
198
+ prompt += "2. Critical improvement areas\n"
199
+ prompt += "3. Actionable strategic recommendations\n"
200
+ prompt += "4. Potential long-term impact on rankings\n"
201
+
202
+ return prompt
203
+
204
+ def _generate_manual_feedback(self, analysis_results: Dict) -> str:
205
+ """
206
+ Fallback method to generate manual strategic feedback.
207
+ """
208
+ parameters = analysis_results['parameters']
209
+ overall_rating = analysis_results['overall_rating']
210
+
211
+ feedback = "### Strategic Performance Analysis\n\n"
212
+ feedback += f"**Overall Institutional Rating**: {overall_rating}/5\n\n"
213
+
214
+ # Identify top strengths and improvement areas
215
+ sorted_params = sorted(
216
+ parameters.items(),
217
+ key=lambda x: x[1]['score'],
218
+ reverse=True
219
+ )
220
+
221
+ feedback += "#### Institutional Strengths:\n"
222
+ for param, values in sorted_params[:3]:
223
+ feedback += f"- **{self.parameters[param]['full_name']}**: Strong performance ({values['score']}/100)\n"
224
+
225
+ feedback += "\n#### Areas for Strategic Enhancement:\n"
226
+ for param, values in sorted_params[-3:]:
227
+ feedback += f"- **{self.parameters[param]['full_name']}**: Requires focused improvement (Current: {values['score']}/100)\n"
228
+
229
+ return feedback
requirements.txt CHANGED
@@ -1 +1,3 @@
1
- huggingface_hub==0.25.2
 
 
 
1
+ transformers
2
+ gradio
3
+ huggingface_hub