Turbiling commited on
Commit
3a785ad
·
verified ·
1 Parent(s): 1dc6ad8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +770 -334
app.py CHANGED
@@ -1,340 +1,776 @@
1
- # ⚡ Quick Start Guide
2
-
3
- Get the AI Graduate Job-Matching Platform running in 5 minutes!
4
-
5
- ## 🎯 Prerequisites
6
-
7
- - Python 3.8+ installed
8
- - Groq API key ([Get one here](https://console.groq.com/))
9
- - 2GB free disk space
10
- - Internet connection
11
-
12
- ## 🚀 Option 1: Automated Setup (Recommended)
13
-
14
- ### For Linux/Mac:
15
-
16
- ```bash
17
- # 1. Clone or download the project
18
- git clone <repository-url>
19
- cd ai-job-matcher
20
-
21
- # 2. Make setup script executable
22
- chmod +x setup.sh
23
-
24
- # 3. Run setup
25
- ./setup.sh
26
-
27
- # 4. Edit .env file with your API key
28
- nano .env # or use your favorite editor
29
-
30
- # 5. Run the application
31
- python app.py
32
- ```
33
-
34
- ### For Windows:
35
-
36
- ```powershell
37
- # 1. Clone or download the project
38
- git clone <repository-url>
39
- cd ai-job-matcher
40
-
41
- # 2. Create virtual environment
42
- python -m venv venv
43
-
44
- # 3. Activate virtual environment
45
- .\venv\Scripts\activate
46
-
47
- # 4. Install dependencies
48
- pip install -r requirements.txt
49
-
50
- # 5. Create .env file
51
- echo GROQ_API_KEY=your_key_here > .env
52
-
53
- # 6. Run the application
54
- python app.py
55
- ```
56
-
57
- ## 🛠️ Option 2: Manual Setup
58
-
59
- ### Step 1: Install Dependencies
60
-
61
- ```bash
62
- pip install groq==0.11.0 gradio==4.44.0 moviepy==1.0.3
63
- ```
64
-
65
- ### Step 2: Set Environment Variable
66
-
67
- **Linux/Mac:**
68
- ```bash
69
- export GROQ_API_KEY="your_groq_api_key_here"
70
- ```
71
-
72
- **Windows:**
73
- ```powershell
74
- $env:GROQ_API_KEY="your_groq_api_key_here"
75
- ```
76
-
77
- ### Step 3: Create File Structure
78
-
79
- ```
80
- ai-job-matcher/
81
- ├── app.py
82
- ├── requirements.txt
83
- ├── utils/
84
- │ ├── __init__.py
85
- │ ├── transcription.py
86
- │ ├── analysis.py
87
- │ └── job_match.py
88
- └── ui/
89
- ├── __init__.py
90
- └── layout.py
91
- ```
92
-
93
- ### Step 4: Run Application
94
-
95
- ```bash
96
- python app.py
97
- ```
98
-
99
- ### Step 5: Open Browser
100
-
101
- Navigate to: `http://localhost:7860`
102
-
103
- ## 🎬 First Test
104
-
105
- ### 1. Record a Test Video (1-2 minutes)
106
-
107
- Sample script:
108
- ```
109
- "Hello, my name is [Your Name]. I recently graduated with a degree in [Your Field].
110
- I have skills in [Skill 1], [Skill 2], and [Skill 3]. I'm passionate about [Interest]
111
- and looking to start my career in [Industry]. Thank you!"
112
- ```
113
-
114
- ### 2. Upload Video
115
-
116
- - Click the upload box
117
- - Select your video file
118
- - Choose language (English or Urdu)
119
-
120
- ### 3. Generate Report
121
-
122
- - Click "Generate Job Match Report"
123
- - Wait 30-60 seconds
124
- - Review results in different tabs
125
-
126
- ## 📱 Access from Mobile
127
-
128
- 1. Find your local IP:
129
- ```bash
130
- # Linux/Mac
131
- ifconfig | grep inet
132
-
133
- # Windows
134
- ipconfig
135
- ```
136
-
137
- 2. Share the app:
138
- ```python
139
- # In app.py, change:
140
- demo.launch(share=True)
141
- ```
142
-
143
- 3. Use the generated public URL
144
-
145
- ## 🐛 Troubleshooting
146
-
147
- ### "GROQ_API_KEY not found"
148
-
149
- **Solution:**
150
- ```bash
151
- # Check if key is set
152
- echo $GROQ_API_KEY # Linux/Mac
153
- echo %GROQ_API_KEY% # Windows
154
-
155
- # Set it again
156
- export GROQ_API_KEY="your_key" # Linux/Mac
157
- set GROQ_API_KEY=your_key # Windows
158
- ```
159
-
160
- ### "Module not found"
161
-
162
- **Solution:**
163
- ```bash
164
- # Reinstall requirements
165
- pip install -r requirements.txt --force-reinstall
166
- ```
167
-
168
- ### "Port 7860 already in use"
169
-
170
- **Solution:**
171
- ```python
172
- # In app.py, change port:
173
- demo.launch(server_port=7861)
174
- ```
175
-
176
- ### Video upload fails
177
-
178
- **Solution:**
179
- - Check video format (MP4, WebM, MOV)
180
- - Check file size (< 100MB)
181
- - Check duration (< 2 minutes)
182
-
183
- ## ☁️ Deploy to Hugging Face (5 minutes)
184
-
185
- ### Quick Deploy:
186
-
187
- 1. **Create Space:**
188
- - Go to [HF Spaces](https://huggingface.co/spaces)
189
- - Click "Create new Space"
190
- - Choose Gradio SDK
191
-
192
- 2. **Upload Files:**
193
- ```bash
194
- git clone https://huggingface.co/spaces/USERNAME/SPACE_NAME
195
- cd SPACE_NAME
196
- cp -r /path/to/your/project/* .
197
- git add .
198
- git commit -m "Initial commit"
199
- git push
200
- ```
201
-
202
- 3. **Add Secret:**
203
- - Go to Space Settings
204
- - Add secret: `GROQ_API_KEY`
205
-
206
- 4. **Access:**
207
- - URL: `https://huggingface.co/spaces/USERNAME/SPACE_NAME`
208
-
209
- ## 📊 What to Expect
210
-
211
- ### Processing Time:
212
- - Upload: < 5 seconds
213
- - Transcription: 10-20 seconds
214
- - Analysis: 15-25 seconds
215
- - Total: 30-60 seconds
216
-
217
- ### Output Quality:
218
- - Transcription accuracy: > 95%
219
- - Job matches: 10 recommendations
220
- - Report length: 2000+ words
221
-
222
- ## 🎓 Example Use Cases
223
-
224
- ### Computer Science Graduate:
225
- ```
226
- Skills: Python, JavaScript, React
227
- Expected Jobs: Software Developer, Web Developer, Full-Stack Engineer
228
- Match Scores: 75-90%
229
- ```
230
-
231
- ### Business Graduate:
232
- ```
233
- Skills: Marketing, Excel, Communication
234
- Expected Jobs: Marketing Coordinator, Business Analyst, Sales Associate
235
- Match Scores: 70-85%
236
- ```
237
-
238
- ### Engineering Graduate:
239
- ```
240
- Skills: CAD, Project Management, Problem-solving
241
- Expected Jobs: Project Engineer, Design Engineer, Technical Coordinator
242
- Match Scores: 72-88%
243
- ```
244
-
245
- ## 📚 Next Steps
246
-
247
- 1. **Read Full Documentation:**
248
- - `README.md` - Complete guide
249
- - `DEPLOYMENT.md` - Deploy to production
250
- - `TESTING.md` - Testing strategies
251
-
252
- 2. **Customize:**
253
- - Modify UI colors/layout
254
- - Add your company logo
255
- - Adjust scoring weights
256
-
257
- 3. **Extend:**
258
- - Add PDF generation
259
- - Integrate with job boards
260
- - Add authentication
261
-
262
- ## 💡 Pro Tips
263
-
264
- ### Tip 1: Better Videos = Better Results
265
- - Use good lighting
266
- - Speak clearly
267
- - Minimize background noise
268
- - Stay under 2 minutes
269
-
270
- ### Tip 2: Test with Various Profiles
271
- - IT/Tech graduates
272
- - Business graduates
273
- - Engineering graduates
274
- - Different experience levels
275
-
276
- ### Tip 3: Monitor Performance
277
- ```python
278
- import time
279
-
280
- start = time.time()
281
- result = process_video(video, language)
282
- print(f"Processing took {time.time() - start:.2f} seconds")
283
- ```
284
-
285
- ### Tip 4: Customize Job Weights
286
- ```python
287
- # In utils/job_match.py
288
  SCORING_WEIGHTS = {
289
- "technical_skills": 0.35, # Increase technical importance
290
  "soft_skills": 0.20,
291
  "communication_clarity": 0.15,
292
- "personality_fit": 0.10,
293
  "domain_relevance": 0.20
294
  }
295
- ```
296
-
297
- ## 🔥 Common Commands
298
-
299
- ```bash
300
- # Start application
301
- python app.py
302
-
303
- # Run tests
304
- pytest tests/
305
-
306
- # Check code style
307
- pylint utils/ ui/
308
-
309
- # Generate coverage report
310
- pytest --cov=. --cov-report=html
311
-
312
- # Update dependencies
313
- pip install -r requirements.txt --upgrade
314
-
315
- # Create production build
316
- pip freeze > requirements.txt
317
-
318
- # Clean cache
319
- find . -type d -name "__pycache__" -exec rm -r {} +
320
- ```
321
-
322
- ## 📞 Get Help
323
-
324
- - 📖 Documentation: See `README.md`
325
- - 🐛 Issues: [GitHub Issues](link)
326
- - 💬 Discussion: [GitHub Discussions](link)
327
- - 📧 Email: support@example.com
328
-
329
- ## ✅ Success Checklist
330
-
331
- - [ ] Python 3.8+ installed
332
- - [ ] Dependencies installed
333
- - [ ] GROQ_API_KEY configured
334
- - [ ] Application starts without errors
335
- - [ ] Test video processed successfully
336
- - [ ] All outputs display correctly
337
- - [ ] Both languages work
338
- - [ ] Ready for deployment!
339
 
340
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI Graduate Job-Matching Platform
3
+ Complete Hugging Face Spaces Deployment Version
4
+ """
5
+
6
+ import os
7
+ import gradio as gr
8
+ import tempfile
9
+ import traceback
10
+ from groq import Groq
11
+ from moviepy.editor import VideoFileClip
12
+ import json
13
+
14
+ # ============================================================================
15
+ # CONFIGURATION
16
+ # ============================================================================
17
+
18
+ # Initialize Groq client
19
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
20
+
21
+ # Model Configuration
22
+ TRANSCRIPTION_MODEL = "whisper-large-v3-turbo"
23
+ CHAT_MODEL = "llama-3.3-70b-versatile"
24
+
25
+ # Constraints
26
+ MAX_VIDEO_DURATION = 120 # 2 minutes in seconds
27
+
28
+ # Job Matching Weights
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  SCORING_WEIGHTS = {
30
+ "technical_skills": 0.30,
31
  "soft_skills": 0.20,
32
  "communication_clarity": 0.15,
33
+ "personality_fit": 0.15,
34
  "domain_relevance": 0.20
35
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ # ============================================================================
38
+ # TRANSCRIPTION MODULE
39
+ # ============================================================================
40
+
41
+ def extract_audio_from_video(video_path):
42
+ """Extract audio from video file"""
43
+ try:
44
+ video = VideoFileClip(video_path)
45
+ duration = video.duration
46
+
47
+ temp_audio = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False)
48
+ audio_path = temp_audio.name
49
+ temp_audio.close()
50
+
51
+ video.audio.write_audiofile(audio_path, logger=None, verbose=False)
52
+ video.close()
53
+
54
+ return audio_path, duration
55
+ except Exception as e:
56
+ print(f"Error extracting audio: {str(e)}")
57
+ raise
58
+
59
+
60
+ def transcribe_video(video_file_path, output_language="English"):
61
+ """Transcribe video using Groq Whisper API"""
62
+ audio_path = None
63
+
64
+ try:
65
+ print("Extracting audio from video...")
66
+ audio_path, duration = extract_audio_from_video(video_file_path)
67
+
68
+ print("Transcribing audio...")
69
+ with open(audio_path, "rb") as audio_file:
70
+ transcription = client.audio.transcriptions.create(
71
+ file=(os.path.basename(audio_path), audio_file.read()),
72
+ model=TRANSCRIPTION_MODEL,
73
+ temperature=0,
74
+ response_format="verbose_json",
75
+ language="en"
76
+ )
77
+
78
+ transcript_text = transcription.text
79
+ confidence = 0.95
80
+
81
+ if hasattr(transcription, 'segments') and transcription.segments:
82
+ confidences = []
83
+ for segment in transcription.segments:
84
+ if hasattr(segment, 'confidence'):
85
+ confidences.append(segment.confidence)
86
+ elif hasattr(segment, 'avg_logprob'):
87
+ confidences.append(min(1.0, max(0.0, 1.0 + segment.avg_logprob)))
88
+
89
+ if confidences:
90
+ confidence = sum(confidences) / len(confidences)
91
+
92
+ segments = []
93
+ if hasattr(transcription, 'segments') and transcription.segments:
94
+ for seg in transcription.segments:
95
+ segments.append({
96
+ "start": seg.start if hasattr(seg, 'start') else 0,
97
+ "end": seg.end if hasattr(seg, 'end') else 0,
98
+ "text": seg.text if hasattr(seg, 'text') else ""
99
+ })
100
+
101
+ return {
102
+ "transcript": transcript_text,
103
+ "confidence": confidence,
104
+ "duration": duration,
105
+ "segments": segments,
106
+ "language": getattr(transcription, 'language', 'en')
107
+ }
108
+
109
+ except Exception as e:
110
+ error_msg = (f"Transcription failed: {str(e)}"
111
+ if output_language == "English"
112
+ else f"ٹرانسکرپشن ناکام: {str(e)}")
113
+ print(f"Transcription error: {str(e)}\n{traceback.format_exc()}")
114
+ return {"error": error_msg}
115
+
116
+ finally:
117
+ if audio_path and os.path.exists(audio_path):
118
+ try:
119
+ os.unlink(audio_path)
120
+ except:
121
+ pass
122
+
123
+
124
+ # ============================================================================
125
+ # ANALYSIS MODULE
126
+ # ============================================================================
127
+
128
+ def get_system_prompt(language):
129
+ """Get system prompt for AI analysis"""
130
+ if language == "English":
131
+ return """You are an expert HR professional and career counselor specializing in graduate recruitment.
132
+ Your task is to analyze candidate profiles from video transcripts and provide comprehensive, actionable insights.
133
+ Focus on extracting skills, personality traits, communication style, and career fit.
134
+ Provide structured, JSON-formatted output for easy parsing."""
135
+ else:
136
+ return """آپ گریجویٹ بھرتی میں مہارت رکھنے والے ایک ماہر HR پروفیشنل اور کیریئر کونسلر ہیں۔
137
+ آپ کا کام ویڈیو ٹرانسکرپٹ سے امیدوار کی پروفائل کا تجزیہ کرنا اور جامع، قابل عمل بصیرت فراہم کرنا ہے۔
138
+ مہارتوں، شخصیت کی خصوصیات، بات چیت کے انداز، اور کیریئر کی مطابقت نکالنے پر توجہ دیں۔
139
+ آسان پارسنگ کے لیے منظم، JSON فارمیٹ آؤٹ پٹ فراہم کریں۔"""
140
+
141
+
142
+ def create_analysis_prompt(transcript, language):
143
+ """Create detailed analysis prompt"""
144
+ if language == "English":
145
+ return f"""Analyze the following graduate candidate's video transcript and extract comprehensive information.
146
+
147
+ TRANSCRIPT:
148
+ {transcript}
149
+
150
+ Please provide a detailed analysis in JSON format with the following structure:
151
+ {{
152
+ "technical_skills": ["skill1", "skill2", ...],
153
+ "soft_skills": ["skill1", "skill2", ...],
154
+ "communication_quality": "Excellent/Good/Fair/Poor - with brief explanation",
155
+ "personality_traits": ["trait1", "trait2", ...],
156
+ "confidence_level": "High/Medium/Low - with reasoning",
157
+ "delivery_style": "Description of speaking style and presentation",
158
+ "domain_hints": ["IT", "Business", "Engineering", etc.],
159
+ "strengths": ["strength1", "strength2", ...],
160
+ "areas_for_improvement": ["area1", "area2", ...],
161
+ "candidate_summary": "2-3 paragraph professional summary of the candidate",
162
+ "career_trajectory": "Suggested career path and growth potential",
163
+ "interview_advice": "Specific tips for interview preparation",
164
+ "resume_improvements": "Suggestions for resume enhancement"
165
+ }}
166
+
167
+ Be specific, actionable, and supportive in your analysis."""
168
+ else:
169
+ return f"""مندرجہ ذیل گریجویٹ امیدوار کے ویڈیو ٹرانسکرپٹ کا تجزیہ کریں اور جامع معلومات نکالیں۔
170
+
171
+ ٹرانسکرپٹ:
172
+ {transcript}
173
+
174
+ براہ کرم JSON فارمیٹ میں تفصیلی تجزیہ فراہم کریں۔"""
175
+
176
+
177
+ def analyze_candidate(transcript, output_language="English"):
178
+ """Analyze candidate profile from transcript"""
179
+ try:
180
+ prompt = create_analysis_prompt(transcript, output_language)
181
+
182
+ completion = client.chat.completions.create(
183
+ model=CHAT_MODEL,
184
+ messages=[
185
+ {
186
+ "role": "system",
187
+ "content": get_system_prompt(output_language)
188
+ },
189
+ {
190
+ "role": "user",
191
+ "content": prompt
192
+ }
193
+ ],
194
+ temperature=0.4,
195
+ max_completion_tokens=2048,
196
+ stream=False
197
+ )
198
+
199
+ response_text = completion.choices[0].message.content
200
+ analysis = parse_analysis_response(response_text, output_language)
201
+
202
+ return analysis
203
+
204
+ except Exception as e:
205
+ error_msg = (f"Analysis failed: {str(e)}"
206
+ if output_language == "English"
207
+ else f"تجزیہ ناکام: {str(e)}")
208
+ print(f"Analysis error: {str(e)}\n{traceback.format_exc()}")
209
+ return {"error": error_msg}
210
+
211
+
212
+ def parse_analysis_response(response_text, language):
213
+ """Parse AI response into structured format"""
214
+ try:
215
+ start_idx = response_text.find('{')
216
+ end_idx = response_text.rfind('}') + 1
217
+
218
+ if start_idx != -1 and end_idx > start_idx:
219
+ json_str = response_text[start_idx:end_idx]
220
+ analysis = json.loads(json_str)
221
+ return analysis
222
+ else:
223
+ return create_fallback_analysis(response_text, language)
224
+
225
+ except json.JSONDecodeError:
226
+ return create_fallback_analysis(response_text, language)
227
+ except Exception as e:
228
+ print(f"Parse error: {str(e)}")
229
+ return create_fallback_analysis(response_text, language)
230
+
231
+
232
+ def create_fallback_analysis(text, language):
233
+ """Create basic analysis when parsing fails"""
234
+ if language == "English":
235
+ return {
236
+ "technical_skills": ["Communication", "Presentation"],
237
+ "soft_skills": ["Articulate", "Professional"],
238
+ "communication_quality": "Good - Clear articulation observed",
239
+ "personality_traits": ["Motivated", "Eager to learn"],
240
+ "confidence_level": "Medium - Professional demeanor",
241
+ "delivery_style": "Professional and articulate",
242
+ "domain_hints": ["General"],
243
+ "strengths": ["Good communication", "Professional attitude"],
244
+ "areas_for_improvement": ["Continue skill development"],
245
+ "candidate_summary": text[:500] if len(text) > 500 else text,
246
+ "career_trajectory": "Multiple career paths available based on interests",
247
+ "interview_advice": "Practice common interview questions and research target companies",
248
+ "resume_improvements": "Highlight specific achievements and quantify results"
249
+ }
250
+ else:
251
+ return {
252
+ "technical_skills": ["بات چیت", "پیشکش"],
253
+ "soft_skills": ["فصیح", "پیشہ ورانہ"],
254
+ "communication_quality": "اچھا - واضح اظہار",
255
+ "personality_traits": ["حوصلہ مند", "سیکھنے کا خواہش مند"],
256
+ "confidence_level": "درمیانہ - پیشہ ورانہ رویہ",
257
+ "delivery_style": "پیشہ ورانہ اور فصیح",
258
+ "domain_hints": ["عمومی"],
259
+ "strengths": ["اچھی بات چیت", "پیشہ ورانہ رویہ"],
260
+ "areas_for_improvement": ["مہارتوں کی ترقی جاری رکھیں"],
261
+ "candidate_summary": text[:500] if len(text) > 500 else text,
262
+ "career_trajectory": "دلچسپیوں کی بنیاد پر متعدد کیریئر کے راستے دستیاب ہیں",
263
+ "interview_advice": "عام انٹرویو سوالات کی مشق کریں",
264
+ "resume_improvements": "مخصوص کامیابیوں کو نمایاں کریں"
265
+ }
266
+
267
+
268
+ # ============================================================================
269
+ # JOB MATCHING MODULE
270
+ # ============================================================================
271
+
272
+ def match_jobs(analysis_result, output_language="English"):
273
+ """Match candidate with top 10 job roles"""
274
+ try:
275
+ prompt = create_job_matching_prompt(analysis_result, output_language)
276
+
277
+ completion = client.chat.completions.create(
278
+ model=CHAT_MODEL,
279
+ messages=[
280
+ {
281
+ "role": "system",
282
+ "content": get_job_matching_system_prompt(output_language)
283
+ },
284
+ {
285
+ "role": "user",
286
+ "content": prompt
287
+ }
288
+ ],
289
+ temperature=0.4,
290
+ max_completion_tokens=2048,
291
+ stream=False
292
+ )
293
+
294
+ response_text = completion.choices[0].message.content
295
+ job_matches = parse_job_matches(response_text, output_language)
296
+
297
+ return job_matches
298
+
299
+ except Exception as e:
300
+ print(f"Job matching error: {str(e)}\n{traceback.format_exc()}")
301
+ return get_fallback_jobs(analysis_result, output_language)
302
+
303
+
304
+ def get_job_matching_system_prompt(language):
305
+ """Get system prompt for job matching"""
306
+ if language == "English":
307
+ return """You are an expert career counselor and job market analyst.
308
+ Your task is to recommend the top 10 most suitable job roles for graduate candidates based on their profile analysis.
309
+ Consider technical skills, soft skills, personality fit, and domain expertise.
310
+ Provide realistic, entry-level to mid-level positions suitable for recent graduates."""
311
+ else:
312
+ return """آپ ایک ماہر کیریئر کونسلر اور جاب مارکیٹ تجزیہ کار ہیں۔
313
+ آپ کا کام گریجویٹ امیدواروں کے لیے سب سے موزوں 10 ملازمت کے کرداروں کی سفارش کرنا ہے۔"""
314
+
315
+
316
+ def create_job_matching_prompt(analysis, language):
317
+ """Create job matching prompt"""
318
+ if language == "English":
319
+ return f"""Based on the following candidate analysis, recommend the top 10 most suitable job roles.
320
+
321
+ CANDIDATE PROFILE:
322
+ - Technical Skills: {', '.join(analysis.get('technical_skills', []))}
323
+ - Soft Skills: {', '.join(analysis.get('soft_skills', []))}
324
+ - Communication Quality: {analysis.get('communication_quality', 'N/A')}
325
+ - Domain Hints: {', '.join(analysis.get('domain_hints', []))}
326
+
327
+ Provide 10 job recommendations with scores and explanations in JSON format."""
328
+ else:
329
+ return f"""امیدوار کے تجزیے کی بنیاد پر 10 موزوں ملازمتوں کی سفارش کریں۔"""
330
+
331
+
332
+ def parse_job_matches(response_text, language):
333
+ """Parse job matching response"""
334
+ try:
335
+ start_idx = response_text.find('{')
336
+ end_idx = response_text.rfind('}') + 1
337
+
338
+ if start_idx != -1 and end_idx > start_idx:
339
+ json_str = response_text[start_idx:end_idx]
340
+ data = json.loads(json_str)
341
+
342
+ if "job_matches" in data:
343
+ matches = data["job_matches"]
344
+ formatted_matches = []
345
+ for match in matches[:10]:
346
+ formatted_matches.append({
347
+ "title": match.get("title", "Unknown Position"),
348
+ "score": match.get("score", 75.0),
349
+ "explanation": match.get("explanation", "Good fit"),
350
+ "responsibilities": match.get("key_responsibilities", []),
351
+ "growth": match.get("growth_potential", "")
352
+ })
353
+ return formatted_matches
354
+
355
+ return get_fallback_jobs({}, language)
356
+
357
+ except Exception as e:
358
+ print(f"Parse job matches error: {str(e)}")
359
+ return get_fallback_jobs({}, language)
360
+
361
+
362
+ def get_fallback_jobs(analysis, language):
363
+ """Provide fallback job recommendations"""
364
+ if language == "English":
365
+ return [
366
+ {"title": "Business Analyst", "score": 78.0, "explanation": "Strong analytical skills", "responsibilities": ["Analysis", "Reports"], "growth": "Senior Analyst"},
367
+ {"title": "Customer Success Associate", "score": 76.0, "explanation": "Good communication", "responsibilities": ["Support", "Training"], "growth": "Manager"},
368
+ {"title": "Marketing Coordinator", "score": 74.0, "explanation": "Creative and organized", "responsibilities": ["Campaigns", "Content"], "growth": "Marketing Manager"},
369
+ {"title": "Project Coordinator", "score": 72.0, "explanation": "Organizational skills", "responsibilities": ["Coordination", "Documentation"], "growth": "Project Manager"},
370
+ {"title": "Sales Associate", "score": 70.0, "explanation": "Interpersonal skills", "responsibilities": ["Sales", "Client relations"], "growth": "Sales Manager"},
371
+ {"title": "HR Assistant", "score": 68.0, "explanation": "People skills", "responsibilities": ["Recruitment", "Onboarding"], "growth": "HR Specialist"},
372
+ {"title": "Content Writer", "score": 66.0, "explanation": "Communication skills", "responsibilities": ["Writing", "Editing"], "growth": "Content Manager"},
373
+ {"title": "Operations Associate", "score": 64.0, "explanation": "Process-oriented", "responsibilities": ["Operations", "Analysis"], "growth": "Operations Manager"},
374
+ {"title": "Administrative Officer", "score": 62.0, "explanation": "Organizational ability", "responsibilities": ["Administration", "Coordination"], "growth": "Office Manager"},
375
+ {"title": "Research Assistant", "score": 60.0, "explanation": "Analytical thinking", "responsibilities": ["Research", "Analysis"], "growth": "Senior Researcher"}
376
+ ]
377
+ else:
378
+ return [
379
+ {"title": "بزنس تجزیہ کار", "score": 78.0, "explanation": "مضبوط تجزیاتی مہارتیں", "responsibilities": ["تجزیہ", "رپورٹس"], "growth": "سینئر تجزیہ کار"},
380
+ {"title": "کسٹمر سکسیس ایسوسی ایٹ", "score": 76.0, "explanation": "اچھی مواصلات", "responsibilities": ["سپورٹ", "ٹریننگ"], "growth": "مینیجر"},
381
+ {"title": "مارکیٹنگ کوآرڈینیٹر", "score": 74.0, "explanation": "تخلیقی اور منظم", "responsibilities": ["مہمات", "مواد"], "growth": "مارکیٹنگ مینیجر"},
382
+ {"title": "پراجیکٹ کوآرڈینیٹر", "score": 72.0, "explanation": "تنظیمی مہارتیں", "responsibilities": ["ہم آہنگی", "دستاویزات"], "growth": "پراجیکٹ مینیجر"},
383
+ {"title": "سیلز ایسوسی ایٹ", "score": 70.0, "explanation": "باہمی مہارتیں", "responsibilities": ["سیلز", "کلائنٹ تعلقات"], "growth": "سیلز مینیجر"},
384
+ {"title": "HR اسسٹنٹ", "score": 68.0, "explanation": "لوگوں کی مہارتیں", "responsibilities": ["بھرتی", "آن بورڈنگ"], "growth": "HR ماہر"},
385
+ {"title": "مواد نگار", "score": 66.0, "explanation": "مواصلاتی مہارتیں", "responsibilities": ["لکھنا", "ایڈیٹنگ"], "growth": "مواد مینیجر"},
386
+ {"title": "آپریشنز ایسوسی ایٹ", "score": 64.0, "explanation": "عمل پر مبنی", "responsibilities": ["آپریشنز", "تجزیہ"], "growth": "آپریشنز مینیجر"},
387
+ {"title": "انتظامی افسر", "score": 62.0, "explanation": "تنظیمی صلاحیت", "responsibilities": ["انتظامیہ", "ہم آہنگی"], "growth": "آفس مینیجر"},
388
+ {"title": "تحقیقی اسسٹنٹ", "score": 60.0, "explanation": "تجزیاتی سوچ", "responsibilities": ["تحقیق", "تجزیہ"], "growth": "سینئر محقق"}
389
+ ]
390
+
391
+
392
+ def generate_report(transcript, analysis, job_matches, confidence, language):
393
+ """Generate comprehensive final report"""
394
+ if language == "English":
395
+ report = f"""
396
+ {'='*80}
397
+ AI GRADUATE JOB-MATCHING PLATFORM - COMPREHENSIVE REPORT
398
+ {'='*80}
399
+
400
+ Transcription Confidence: {confidence:.2%}
401
+
402
+ {'='*80}
403
+ CANDIDATE PROFILE
404
+ {'='*80}
405
+
406
+ Technical Skills: {', '.join(analysis.get('technical_skills', []))}
407
+ Soft Skills: {', '.join(analysis.get('soft_skills', []))}
408
+ Communication Quality: {analysis.get('communication_quality', 'N/A')}
409
+ Domain: {', '.join(analysis.get('domain_hints', ['General']))}
410
+
411
+ {'='*80}
412
+ TOP 10 JOB RECOMMENDATIONS
413
+ {'='*80}
414
+
415
+ """
416
+ for idx, job in enumerate(job_matches[:10], 1):
417
+ report += f"{idx}. {job['title']} - Score: {job['score']:.1f}%\n"
418
+ report += f" {job['explanation']}\n\n"
419
+
420
+ report += f"""
421
+ {'='*80}
422
+ CAREER RECOMMENDATIONS
423
+ {'='*80}
424
+
425
+ {analysis.get('career_trajectory', 'Focus on continuous learning')}
426
+
427
+ Interview Advice: {analysis.get('interview_advice', 'Practice and prepare')}
428
+
429
+ {'='*80}
430
+ TRANSCRIPT
431
+ {'='*80}
432
+ {transcript}
433
+
434
+ {'='*80}
435
+ END OF REPORT
436
+ {'='*80}
437
+ """
438
+ else:
439
+ report = f"""
440
+ {'='*80}
441
+ AI گریجویٹ جاب میچنگ پلیٹ فارم - جامع رپورٹ
442
+ {'='*80}
443
+
444
+ ٹرانسکرپشن کا اعتماد: {confidence:.2%}
445
+
446
+ {'='*80}
447
+ امیدوار کی پروفائل
448
+ {'='*80}
449
+
450
+ تکنیکی مہارتیں: {', '.join(analysis.get('technical_skills', []))}
451
+ نرم مہارتیں: {', '.join(analysis.get('soft_skills', []))}
452
+
453
+ {'='*80}
454
+ سرفہرست 10 ملازمت کی سفارشات
455
+ {'='*80}
456
+
457
+ """
458
+ for idx, job in enumerate(job_matches[:10], 1):
459
+ report += f"{idx}. {job['title']} - سکور: {job['score']:.1f}%\n"
460
+ report += f" {job['explanation']}\n\n"
461
+
462
+ report += f"""
463
+ {'='*80}
464
+ ٹرانسکرپٹ
465
+ {'='*80}
466
+ {transcript}
467
+
468
+ {'='*80}
469
+ رپورٹ کا اختتام
470
+ {'='*80}
471
+ """
472
+
473
+ return report
474
+
475
+
476
+ # ============================================================================
477
+ # MAIN PROCESSING PIPELINE
478
+ # ============================================================================
479
+
480
+ def process_video(video_file, output_language):
481
+ """Main processing pipeline for graduate job matching"""
482
+ try:
483
+ if video_file is None:
484
+ error_msg = "Please upload a video file." if output_language == "English" else "براہ کرم ایک ویڈیو فائل اپ لوڈ کریں۔"
485
+ return "", "", "", "", "", error_msg
486
+
487
+ print(f"Processing video: {video_file}")
488
+ transcription_result = transcribe_video(video_file, output_language)
489
+
490
+ if "error" in transcription_result:
491
+ return "", "", "", "", "", transcription_result["error"]
492
+
493
+ transcript_text = transcription_result.get("transcript", "")
494
+ confidence = transcription_result.get("confidence", 0)
495
+ duration = transcription_result.get("duration", 0)
496
+
497
+ if duration > MAX_VIDEO_DURATION:
498
+ warning = (f"⚠️ Video duration ({duration:.1f}s) exceeds 2 minutes."
499
+ if output_language == "English"
500
+ else f"⚠️ ویڈیو کی مدت ({duration:.1f}s) 2 منٹ سے زیادہ ہے۔")
501
+ transcript_text = warning + "\n\n" + transcript_text
502
+
503
+ if not transcript_text or len(transcript_text.strip()) < 20:
504
+ error_msg = ("Transcript too short. Please ensure clear audio."
505
+ if output_language == "English"
506
+ else "ٹرانسکرپٹ بہت چھوٹا ہے۔")
507
+ return transcript_text, "", "", "", "", error_msg
508
+
509
+ print("Analyzing candidate profile...")
510
+ analysis_result = analyze_candidate(transcript_text, output_language)
511
+
512
+ if "error" in analysis_result:
513
+ return transcript_text, "", "", "", "", analysis_result["error"]
514
+
515
+ print("Matching job roles...")
516
+ job_matches = match_jobs(analysis_result, output_language)
517
+
518
+ print("Generating final report...")
519
+ final_report = generate_report(
520
+ transcript_text,
521
+ analysis_result,
522
+ job_matches,
523
+ confidence,
524
+ output_language
525
+ )
526
+
527
+ transcript_display = format_transcript(transcript_text, confidence, duration, output_language)
528
+ skills_display = format_skills(analysis_result, output_language)
529
+ summary_display = format_summary(analysis_result, output_language)
530
+ jobs_display = format_jobs(job_matches, output_language)
531
+
532
+ return (
533
+ transcript_display,
534
+ skills_display,
535
+ summary_display,
536
+ jobs_display,
537
+ final_report,
538
+ ""
539
+ )
540
+
541
+ except Exception as e:
542
+ error_message = f"Error: {str(e)}\n{traceback.format_exc()}"
543
+ print(error_message)
544
+ return "", "", "", "", "", "System error occurred. Please try again."
545
+
546
+
547
+ # ============================================================================
548
+ # FORMATTING FUNCTIONS
549
+ # ============================================================================
550
+
551
+ def format_transcript(text, confidence, duration, language):
552
+ if language == "English":
553
+ return f"""📝 TRANSCRIPT
554
+ {'='*50}
555
+ Confidence: {confidence:.2%}
556
+ Duration: {duration:.1f}s
557
+
558
+ {text}
559
+ """
560
+ else:
561
+ return f"""📝 ٹرانسکرپٹ
562
+ {'='*50}
563
+ اعتماد: {confidence:.2%}
564
+ مدت: {duration:.1f}s
565
+
566
+ {text}
567
+ """
568
+
569
+
570
+ def format_skills(analysis, language):
571
+ if language == "English":
572
+ output = "🎯 SKILLS EXTRACTION\n" + "="*50 + "\n\n"
573
+ output += f"**Technical Skills:**\n{', '.join(analysis.get('technical_skills', ['None']))}\n\n"
574
+ output += f"**Soft Skills:**\n{', '.join(analysis.get('soft_skills', ['None']))}\n\n"
575
+ output += f"**Communication:** {analysis.get('communication_quality', 'N/A')}\n\n"
576
+ output += f"**Domain:** {', '.join(analysis.get('domain_hints', ['General']))}\n"
577
+ else:
578
+ output = "🎯 مہارتوں کی شناخت\n" + "="*50 + "\n\n"
579
+ output += f"**تکنیکی مہارتیں:**\n{', '.join(analysis.get('technical_skills', ['کوئی نہیں']))}\n\n"
580
+ output += f"**نرم مہارتیں:**\n{', '.join(analysis.get('soft_skills', ['کوئی نہیں']))}\n\n"
581
+ output += f"**بات چیت:** {analysis.get('communication_quality', 'دستیاب نہیں')}\n"
582
+
583
+ return output
584
+
585
+
586
+ def format_summary(analysis, language):
587
+ if language == "English":
588
+ output = "👤 CANDIDATE SUMMARY\n" + "="*50 + "\n\n"
589
+ output += analysis.get('candidate_summary', 'No summary available')
590
+ output += f"\n\n**Career Path:**\n{analysis.get('career_trajectory', 'N/A')}"
591
+ else:
592
+ output = "👤 امیدوار کا خلاصہ\n" + "="*50 + "\n\n"
593
+ output += analysis.get('candidate_summary', 'کوئی خلاصہ دستیاب نہیں')
594
+ output += f"\n\n**کیریئر کی سمت:**\n{analysis.get('career_trajectory', 'دستیاب نہیں')}"
595
+
596
+ return output
597
+
598
+
599
+ def format_jobs(job_matches, language):
600
+ if language == "English":
601
+ output = "💼 TOP 10 JOB RECOMMENDATIONS\n" + "="*50 + "\n\n"
602
+ for idx, job in enumerate(job_matches[:10], 1):
603
+ output += f"**{idx}. {job['title']}** - Match: {job['score']:.1f}%\n"
604
+ output += f" {job['explanation']}\n\n"
605
+ else:
606
+ output = "💼 سرفہرست 10 ملازمت کی سفارشات\n" + "="*50 + "\n\n"
607
+ for idx, job in enumerate(job_matches[:10], 1):
608
+ output += f"**{idx}. {job['title']}** - میچ: {job['score']:.1f}%\n"
609
+ output += f" {job['explanation']}\n\n"
610
+
611
+ return output
612
+
613
+
614
+ # ============================================================================
615
+ # GRADIO UI
616
+ # ============================================================================
617
+
618
+ def create_ui():
619
+ """Create Gradio interface"""
620
+
621
+ custom_css = """
622
+ .main-header {
623
+ text-align: center;
624
+ padding: 20px;
625
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
626
+ color: white;
627
+ border-radius: 10px;
628
+ margin-bottom: 20px;
629
+ }
630
+ """
631
+
632
+ with gr.Blocks(css=custom_css, title="AI Graduate Job Matcher") as demo:
633
+
634
+ gr.HTML("""
635
+ <div class="main-header">
636
+ <h1>🎓 AI Graduate Job-Matching Platform</h1>
637
+ <h2>AI گریجویٹ جاب میچنگ پلیٹ فارم</h2>
638
+ <p>Powered by Groq AI • GROQ AI کے ذریعے تقویت یافتہ</p>
639
+ </div>
640
+ """)
641
+
642
+ gr.HTML("<hr>")
643
+
644
+ with gr.Row():
645
+ with gr.Column(scale=2):
646
+ video_input = gr.Video(
647
+ label="Upload Video / ویڈیو اپ لوڈ کریں",
648
+ sources=["upload"]
649
+ )
650
+
651
+ with gr.Column(scale=1):
652
+ language_dropdown = gr.Dropdown(
653
+ choices=["English", "Urdu / اردو"],
654
+ value="English",
655
+ label="Output Language / آؤٹ پٹ زبان"
656
+ )
657
+
658
+ process_btn = gr.Button(
659
+ "🚀 Generate Report / رپورٹ بنائیں",
660
+ variant="primary",
661
+ size="lg"
662
+ )
663
+
664
+ error_output = gr.Textbox(
665
+ label="Status / حیثیت",
666
+ visible=True,
667
+ interactive=False
668
+ )
669
+
670
+ gr.HTML("<hr>")
671
+
672
+ gr.Markdown("## 📊 Results / نتائج")
673
+
674
+ with gr.Tabs():
675
+ with gr.Tab("📝 Transcript"):
676
+ transcript_output = gr.Textbox(
677
+ label="Transcript",
678
+ lines=10,
679
+ interactive=False
680
+ )
681
+
682
+ with gr.Tab("🎯 Skills"):
683
+ skills_output = gr.Textbox(
684
+ label="Skills",
685
+ lines=12,
686
+ interactive=False
687
+ )
688
+
689
+ with gr.Tab("👤 Profile"):
690
+ summary_output = gr.Textbox(
691
+ label="Summary",
692
+ lines=15,
693
+ interactive=False
694
+ )
695
+
696
+ with gr.Tab("💼 Jobs"):
697
+ jobs_output = gr.Textbox(
698
+ label="Job Matches",
699
+ lines=20,
700
+ interactive=False
701
+ )
702
+
703
+ with gr.Tab("📄 Full Report"):
704
+ report_output = gr.Textbox(
705
+ label="Complete Report",
706
+ lines=30,
707
+ interactive=False
708
+ )
709
+
710
+ gr.HTML("""
711
+ <div style="text-align: center; padding: 20px; margin-top: 30px; border-top: 1px solid #ddd;">
712
+ <p><strong>AI Graduate Job-Matching Platform</strong></p>
713
+ <p>Built with Groq API (Whisper + LLaMA) • Deployed on Hugging Face Spaces</p>
714
+ </div>
715
+ """)
716
+
717
+ def process_and_clean(video, language):
718
+ lang = "English" if "English" in language else "Urdu"
719
+ results = process_video(video, lang)
720
+ transcript, skills, summary, jobs, report, error = results
721
+
722
+ status = error if error else "✅ Success! / کامیاب!"
723
+
724
+ return (
725
+ transcript,
726
+ skills,
727
+ summary,
728
+ jobs,
729
+ report,
730
+ status
731
+ )
732
+
733
+ process_btn.click(
734
+ fn=process_and_clean,
735
+ inputs=[video_input, language_dropdown],
736
+ outputs=[
737
+ transcript_output,
738
+ skills_output,
739
+ summary_output,
740
+ jobs_output,
741
+ report_output,
742
+ error_output
743
+ ]
744
+ )
745
+
746
+ return demo
747
+
748
+
749
+ # ============================================================================
750
+ # MAIN ENTRY POINT
751
+ # ============================================================================
752
+
753
+ if __name__ == "__main__":
754
+ if not os.getenv("GROQ_API_KEY"):
755
+ print("⚠️ WARNING: GROQ_API_KEY not found!")
756
+ print("Please set it in Hugging Face Space settings")
757
+
758
+ demo = create_ui()
759
+ demo.launch(
760
+ server_name="0.0.0.0",
761
+ server_port=7860,
762
+ share=False
763
+ )
764
+ gr.Markdown("""
765
+ ### 📹 Instructions / ہدایات
766
+
767
+ **English:**
768
+ 1. Upload a 2-minute video introducing yourself
769
+ 2. Select output language (English/Urdu)
770
+ 3. Click "Generate Job Match Report"
771
+
772
+ **اردو:**
773
+ 1. اپنا تعارف کرواتے ہوئے 2 منٹ کی ویڈیو اپ لوڈ کریں
774
+ 2. آؤٹ پٹ زبان منتخب کریں
775
+ 3. "جاب میچ رپورٹ بنائیں" پر کلک کریں
776
+ """)