File size: 34,015 Bytes
aae2f15
 
 
 
 
61bde96
aae2f15
 
 
 
 
 
 
 
 
 
 
61bde96
aae2f15
 
 
 
 
 
61bde96
 
aae2f15
 
 
 
 
 
 
 
 
 
 
 
61bde96
 
aae2f15
61bde96
 
aae2f15
61bde96
aae2f15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62dd132
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
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
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
from flask import Flask, render_template, request, jsonify, send_file, session
import numpy as np
import speech_recognition as sr
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import together
import json
import re
from dotenv import load_dotenv
import os
import tempfile
from datetime import datetime
import threading
from gtts import gTTS
import uuid
import base64
import io
import requests

load_dotenv()

app = Flask(__name__)
app.secret_key = os.urandom(24)

# Initialize Together API
together.api_key = os.getenv("TOGETHER_API_KEY", "")

def prompt_llm(prompt, show_cost=False):
    """Function to send prompt to an LLM via the Together API."""
    model = "meta-llama/Meta-Llama-3-8B-Instruct-Lite"
    tokens = len(prompt.split())

    if show_cost:
        print(f"\nNumber of tokens: {tokens}")
        cost = (0.1 / 1_000_000) * tokens
        print(f"Estimated cost for {model}: ${cost:.10f}\n")

    try:
        response = together.Complete.create(
            prompt=prompt,
            model=model,
            max_tokens=1024,
            temperature=0.7,
        )
        content = response['output']['choices'][0]['text']
        
        # Safety check for empty responses
        if not content or len(content.strip()) < 10:
            print(f"Warning: LLM returned empty or very short response: '{content}'")
            return "The LLM response was too short or empty. Please try again with more detailed input."
        return content
    except Exception as e:
        print(f"Error calling LLM API: {str(e)}")
        return "An error occurred while generating content. Please check your API key and try again."

class Analyzer:
    def __init__(self):
        self.encoder = SentenceTransformer("all-MiniLM-L6-v2")

    def parse_job_info(self, job_description, company_values):
        """Extracts key insights and fills relevant fields."""
        prompt = f"""
        SYSTEM: You are an expert career coach and interviewer with over 30 years of experience in the tech industry. Your task is to thoroughly analyze the job description and company values to extract and classify all relevant information.

        INSTRUCTIONS:
        1. Analyze the entire text for any skills, requirements, or values, looking for both explicit and implicit mentions.
        2. Classify all found information into these categories:

        Company Values:
        - Look for mentions of culture, principles, mission, values
        - Include both explicit values and implied ones from the company's description
        - Examples: integrity, innovation, customer focus, diversity, sustainability

        Technical Skills:
        - All technical requirements, tools, languages, platforms
        - Both required and preferred technical qualifications
        - Include domain-specific technical knowledge
        - Examples: programming languages, frameworks, methodologies, systems

        Soft Skills:
        - All interpersonal and professional skills
        - Leadership and management capabilities
        - Personal qualities and attributes
        - Examples: communication, leadership, problem-solving, teamwork

        Job Duties:
        - Primary responsibilities and expectations
        - Day-to-day tasks and long-term objectives
        - Project responsibilities and deliverables
        - Team and organizational contributions

        FORMAT YOUR RESPONSE EXACTLY AS FOLLOWS:
        **Key Company Values:**
        - [value 1]
        - [value 2]
        
        **Essential Technical Skills:**
        - [skill 1]
        - [skill 2]
        
        **Necessary Soft Skills:**
        - [skill 1]
        - [skill 2]
        
        **Summary of Key Job Duties:**
        - [duty 1]
        - [duty 2]

        Keep each bullet point concise (under 10 words).

        JOB DESCRIPTION: {job_description}
        COMPANY VALUES: {company_values}
        """
        response = prompt_llm(prompt)
        
        # Use regular expressions to extract the relevant sections
        company_values_match = re.search(r"\*\*Key Company Values:\*\*(.*?)\*\*Essential Technical Skills:\*\*", response, re.DOTALL)
        tech_skills_match = re.search(r"\*\*Essential Technical Skills:\*\*(.*?)\*\*Necessary Soft Skills:\*\*", response, re.DOTALL)
        soft_skills_match = re.search(r"\*\*Necessary Soft Skills:\*\*(.*?)\*\*Summary of Key Job Duties:\*\*", response, re.DOTALL)
        job_duties_match = re.search(r"\*\*Summary of Key Job Duties:\*\*(.*)", response, re.DOTALL)

        company_values = company_values_match.group(1).strip() if company_values_match else "Not found"
        tech_skills = tech_skills_match.group(1).strip() if tech_skills_match else "Not found"
        soft_skills = soft_skills_match.group(1).strip() if soft_skills_match else "Not found"
        job_duties = job_duties_match.group(1).strip() if job_duties_match else "Not found"

        parsed_info = {
            "company_values": company_values,
            "tech_skills": tech_skills,
            "soft_skills": soft_skills,
            "job_duties": job_duties
        }
        return parsed_info

class Drafter:
    def generate_answer(self, question, company_info, job_description, resume, voice_answer):
        """Drafts a model answer based on user inputs."""
        prompt = f"""
        SYSTEM: You are a professional interview coach and writer with over 30 years of experience in the tech industry. Draft a strong, structured answer to get this user hired by a top tech company, based on the following inputs:
        
        INSTRUCTIONS:
        - Ensure clarity and logical flow.
        - Incorporate company values where relevant.
        - Highlight technical and soft skills from the job description.
        - Use Amazon Leadership Principles to guide the answer.
        - Use user's voice answer, experience and skills in the resume to answer the question.
        - Use the situation, task, action, and result (STAR) method to structure the answer.
        - Improve conciseness while maintaining completeness.
        - Maintain a confident and positive tone.
        - Keep the answer in 90 seconds to 2 minutes long.
        - If possible, use the same language as the user's voice answer.
        - If there is no information, just output "Not found".
        
        QUESTION: {question}
        COMPANY INFO: {company_info}
        JOB DESCRIPTION: {job_description}
        USER RESUME: {resume}
        USER VOICE ANSWER: {voice_answer}
        """
        return prompt_llm(prompt)

class Evaluator:
    def evaluate_answer(self, voice_answer, job_description, company_values):
        """Evaluates the user's voice answer based on clarity, relevance, and confidence."""
        prompt = f"""
        SYSTEM: You are an experienced interviewer in the tech industry for over 30 years. Also you are an expert evaluator for interview responses. Assess the answer based on the following criteria:
        
        INSTRUCTIONS:
        - Clarity: Is the response structured and easy to understand?
        - Relevance: Does it address the job's required skills and reflect company values?
        - Confidence: Does the tone convey certainty and professionalism?
        - Consider that the user could be nervous, so don't be too strict.
        - Consider that the user is not a native English speaker, so don't be too strict.
        - Provide constructive feedback and a score out of 10 for each category.
        - Always give some positive feedback at the begining, then give some feedback on what to improve.
        - Use a friendly and professional tone and encourage the user to do better.
        - Keep the feedback concise and to the point.
        - Keep the feedback in 150 words to 250 words.

        USER VOICE ANSWER: {voice_answer}
        JOB DESCRIPTION: {job_description}
        COMPANY VALUES: {company_values}
        """
        response = prompt_llm(prompt)
        
        clarity_match = re.search(r"Clarity: (\d+)/10", response)
        relevance_match = re.search(r"Relevance: (\d+)/10", response)
        confidence_match = re.search(r"Confidence: (\d+)/10", response)
        
        clarity_score = int(clarity_match.group(1)) if clarity_match else 0
        relevance_score = int(relevance_match.group(1)) if relevance_match else 0
        confidence_score = int(confidence_match.group(1)) if confidence_match else 0
        feedback = response
        
        scores = {
            "clarity": clarity_score,
            "relevance": relevance_score,
            "confidence": confidence_score
        }
        
        return scores, feedback

class InterviewAgentManager:
    def __init__(self):
        self.analyzer = Analyzer()
        self.drafter = Drafter()
        self.evaluator = Evaluator()
    
    def process_interview(self, job_description, company_values, question, company_info, resume, voice_answer):
        """Manages the full process from analysis to evaluation."""
        parsed_info = self.analyzer.parse_job_info(job_description, company_values)
        model_answer = self.drafter.generate_answer(question, company_info, job_description, resume, voice_answer)
        evaluation = self.evaluator.evaluate_answer(voice_answer, job_description, company_values)
        
        return {
            "parsed_info": parsed_info,
            "model_answer": model_answer,
            "evaluation": evaluation
        }

interview_manager = InterviewAgentManager()

def get_question_hints():
    """Return a dictionary of questions and their hints"""
    return {
        "Tell me about yourself": 
            "Focus on your professional background, key achievements, and why you're a good fit for this role.",
        "What's your greatest strength?": 
            "Choose a strength relevant to the job. Provide specific examples that demonstrate this strength.",
        "Why do you want this job?": 
            "Connect your skills and career goals to the role and company. Show you've done your research.",
        "Where do you see yourself in 5 years?": 
            "Discuss your career goals and how they align with the company's growth trajectory.",
        "Why do you want to work at our company?": 
            "Demonstrate your knowledge of the company's values, culture, and mission.",
        "Tell me about your most relevant experience for this role": 
            "Focus on experience that directly relates to the job requirements. Use the STAR method.",
        "Describe a time you led/motivated others. How were you able to?":
            "Describe a time when you led a team finishing a challenging task, tailor your approach to the people involved, and were positive and persuasive",
        "What's your greatest weakness?":
            "Choose a weakness that is not a deal breaker for the job, and show how you are working to improve it.",
        "What's your biggest accomplishment?":
            "Focus on a significant achievement that showcases your skills and dedication.",
        "What's your biggest failure?":
            "Share a failure that taught you a valuable lesson, emphasizing what you learned and how you overcame it.",
        "How do you motivate team members?":
            "Focus on your ability to inspire and guide others, using your own experiences as examples.",
        "Tell me about a time you worked in a team. How did you contribute?":
            "Describe your specific role and responsibilities within the team. Highlight a successful outcome that resulted from your teamwork.",
        "Can you describe a time when you faced a conflict in a team setting? How did you handle the situation, and what was the outcome?":
            "Highlight the positive outcome and lessons learned. Empathy, communication, negotiation, emotional intelligence",
        "Can you describe a situation where you had to work with a difficult colleague or client?":
            "Describe the specific challenges faced in the situation. Highlight the positive outcome from the experience.",
        "Describe a time you experienced a major change at work. How did you adapt?":
            "Pick an example where you were impacted by a big change and adapted efficiently; extra credit if you got others to do the same",
        "Can you share an example of a time when you used creativity to solve a challenging problem? What approach did you take, and what was the result?":
            "Analyze, creativity, optimization. Create your own opportunities.",
        "Can you share an example of a time when you took initiative? What was the situation, and what impact did your actions have?":
            "Creativity, proactive, positive changes, impact",
        "How do you tackle challenges? Name a difficult challenge you faced while working on a project, how you overcame it, and what you learned.":
            "Perseverance, resilience, resourcefulness, problem-solving",
        "How do you handle ambiguity or uncertainty in your work?":
            "Emphasize the strategies used to approach uncertain situations. Ownership. Adaptability"
    }

def generate_sample_questions(job_desc, company_info, resume):
    """Generate categorized interview questions based on all inputs"""
    # Organize questions by category
    categorized_questions = {
        "Introduction": [
            "Tell me about yourself",
            "Tell me about your most relevant experience for this role"
        ],
        "Strengths & Weaknesses": [
            "What's your greatest strength?",
            "What's your greatest weakness?",
            "What's your biggest accomplishment?", 
            "What's your biggest failure?"
        ],
        "Career Goals": [
            "Why do you want this job?",
            "Where do you see yourself in 5 years?",
            "Why do you want to work at our company?"
        ],
        "Teamwork & Collaboration": [
            "Tell me about a time you worked in a team. How did you contribute?",
            "Can you describe a time when you faced a conflict in a team setting? How did you handle the situation, and what was the outcome?",
            "Can you describe a situation where you had to work with a difficult colleague or client?"
        ],
        "Leadership & Initiative": [
            "Describe a time you led/motivated others. How were you able to?",
            "How do you motivate team members?",
            "Can you share an example of a time when you took initiative? What was the situation, and what impact did your actions have?"
        ],
        "Problem Solving & Adaptability": [
            "How do you tackle challenges? Name a difficult challenge you faced while working on a project, how you overcame it, and what you learned.",
            "Describe a time you experienced a major change at work. How did you adapt?",
            "Can you share an example of a time when you used creativity to solve a challenging problem? What approach did you take, and what was the result?",
            "How do you handle ambiguity or uncertainty in your work?"
        ]
    }
    
    # Add company-specific question if company info is provided
    if company_info.strip() and "Why do you want to work at our company?" not in categorized_questions["Career Goals"]:
        categorized_questions["Career Goals"].append("Why do you want to work at our company?")
    
    # Add experience-related question if resume is provided
    if resume.strip() and "Tell me about your most relevant experience for this role" not in categorized_questions["Introduction"]:
        categorized_questions["Introduction"].append("Tell me about your most relevant experience for this role")
    
    return categorized_questions

def speech_to_text(audio_data):
    """Convert speech to text using SpeechRecognition"""
    recognizer = sr.Recognizer()
    
    try:
        # Save base64 audio data to a temporary file
        audio_bytes = base64.b64decode(audio_data.split(',')[1])
        
        # Save as webm file first
        with tempfile.NamedTemporaryFile(delete=False, suffix='.webm') as temp_audio_file:
            temp_audio_file.write(audio_bytes)
            temp_webm_path = temp_audio_file.name
        
        # Convert to WAV using FFmpeg if available, otherwise use a direct approach
        try:
            import subprocess
            wav_path = temp_webm_path.replace('.webm', '.wav')
            subprocess.call(['ffmpeg', '-i', temp_webm_path, '-ar', '16000', '-ac', '1', wav_path])
            os.unlink(temp_webm_path)  # Delete the webm file
            
            with sr.AudioFile(wav_path) as source:
                audio = recognizer.record(source)
            text = recognizer.recognize_google(audio)
            os.unlink(wav_path)  # Delete temp WAV file
            return text
        except (ImportError, FileNotFoundError):
            # If FFmpeg is not available, try direct approach with the webm file
            # Note: This might not work perfectly but worth trying
            with sr.AudioFile(temp_webm_path) as source:
                audio = recognizer.record(source)
            text = recognizer.recognize_google(audio)
            os.unlink(temp_webm_path)  # Delete temp file
            return text
    except Exception as e:
        # If an error occurs, try to delete any temporary files
        try:
            if 'temp_webm_path' in locals():
                os.unlink(temp_webm_path)
            if 'wav_path' in locals():
                os.unlink(wav_path)
        except:
            pass
        
        # Use a different approach as fallback - send directly to Google's API
        try:
            audio_bytes = base64.b64decode(audio_data.split(',')[1])
            audio_data_obj = sr.AudioData(audio_bytes, 16000, 2)  # Using default values
            text = recognizer.recognize_google(audio_data_obj)
            return text
        except Exception as inner_e:
            return f"Speech recognition failed: {str(e)}. Second attempt: {str(inner_e)}"

def get_voice_options():
    return {
        "US English": {"lang": "en", "tld": "com"},
        "UK English": {"lang": "en", "tld": "co.uk"},
        "Australian English": {"lang": "en", "tld": "com.au"},
        "Indian English": {"lang": "en", "tld": "co.in"},
        "French": {"lang": "fr", "tld": "fr"},
        "German": {"lang": "de", "tld": "de"},
        "Spanish": {"lang": "es", "tld": "es"},
        "Italian": {"lang": "it", "tld": "it"},
        "Japanese": {"lang": "ja", "tld": "co.jp"},
        "Korean": {"lang": "ko", "tld": "co.kr"}
    }

def text_to_speech(text, voice_option="US English"):
    """Convert text to speech and return as base64"""
    voice_options = get_voice_options()
    selected_voice = voice_options.get(voice_option, {"lang": "en", "tld": "com"})
    
    try:
        # Create a temporary file for the audio
        with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as fp:
            temp_filename = fp.name
        
        # Generate the speech audio file with the selected voice
        tts = gTTS(text=text, lang=selected_voice["lang"], tld=selected_voice["tld"])
        tts.save(temp_filename)
        
        # Read the file and convert to base64
        with open(temp_filename, 'rb') as audio_file:
            audio_data = base64.b64encode(audio_file.read()).decode('utf-8')
        
        # Clean up the temporary file
        os.unlink(temp_filename)
        
        return f"data:audio/mp3;base64,{audio_data}"
    except Exception as e:
        print(f"TTS Error: {e}")
        return None

def save_to_html(job_desc, company_info, resume, company_values, tech_skills, soft_skills, job_duties, selected_question, answer_text, feedback, model_answer):
    """Generate HTML content for download."""
    # Get current date and time
    current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    file_name = f"interview_summary_{current_time}.html"
    
    html_content = f"""
    <html>
    <head>
        <title>Interview Prep Summary</title>
        <style>
            body {{
                font-family: 'Arial', sans-serif;
                margin: 0;
                padding: 20px;
                background-color: #f4f4f9;
                color: #333;
            }}
            h1 {{
                text-align: center;
                margin-bottom: 40px;
                color: #4f46e5;
                font-size: 36px;
                font-weight: bold;
            }}
            h2 {{
                margin-top: 30px;
                border-bottom: 2px solid #ddd;
                padding-bottom: 10px;
                color: #333;
                font-size: 24px;
                font-weight: bold;
            }}
            p {{
                line-height: 1.6;
                font-size: 16px;
                margin-bottom: 20px;
            }}
            ul {{
                list-style-type: none;
                padding: 0;
            }}
            li {{
                background: #fff;
                margin: 10px 0;
                padding: 15px;
                border-radius: 8px;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                font-size: 16px;
            }}
            .section {{
                margin-bottom: 40px;
                padding: 20px;
                background-color: #fff;
                border-radius: 8px;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            }}
            .section-title {{
                color: #4f46e5;
                font-size: 20px;
                font-weight: bold;
                margin-bottom: 10px;
            }}
            .content {{
                line-height: 1.6;
                font-size: 16px;
            }}
            .info-item {{
                background: #fff;
                margin: 10px 0;
                padding: 15px;
                border-radius: 8px;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                font-size: 16px;
            }}
            .spinner {{
                border: 2px solid rgba(255, 255, 255, 0.3);
                border-radius: 50%;
                border-top: 2px solid white;
                width: 16px;
                height: 16px;
                animation: spin 1s linear infinite;
                display: inline-block;
                vertical-align: middle;
                margin-right: 8px;
            }}
            @keyframes spin {{
                0% {{ transform: rotate(0deg); }}
                100% {{ transform: rotate(360deg); }}
            }}
            button:disabled {{
                opacity: 0.7;
                cursor: not-allowed;
            }}
            .star-1 {{ color: #FF5252; }} /* Red */
            .star-2 {{ color: #FF7F00; }} /* Orange */
            .star-3 {{ color: #FFFF00; }} /* Yellow */
            .star-4 {{ color: #7FFF00; }} /* Chartreuse */
            .star-5 {{ color: #00FF00; }} /* Green */
            .star-6 {{ color: #00FFFF; }} /* Cyan */
            .star-7 {{ color: #007FFF; }} /* Azure */
            .star-8 {{ color: #0000FF; }} /* Blue */
            .star-9 {{ color: #7F00FF; }} /* Violet */
            .star-10 {{ color: #FF00FF; }} /* Magenta */
            .star-empty {{ color: #cccccc; }} /* Gray for empty stars */
        </style>
    </head>
    <body>
        <h1>Interview Prep Summary</h1>
        <div class="section">
            <h2 class="section-title">Job Description</h2>
            <div class="content">{job_desc}</div>
        </div>
        <div class="section">
            <h2 class="section-title">Company Information</h2>
            <div class="content">{company_info}</div>
        </div>
        <div class="section">
            <h2 class="section-title">Your Resume</h2>
            <div class="content">{resume}</div>
        </div>
        <div class="section">
            <h2 class="section-title">Parsed Information</h2>
            <ul>
                <li class="info-item"><strong>Company Values:</strong> {company_values}</li>
                <li class="info-item"><strong>Tech Skills:</strong> {tech_skills}</li>
                <li class="info-item"><strong>Soft Skills:</strong> {soft_skills}</li>
                <li class="info-item"><strong>Job Duties:</strong> {job_duties}</li>
            </ul>
        </div>
        <div class="section">
            <h2 class="section-title">Selected Question</h2>
            <div class="content">{selected_question}</div>
        </div>
        <div class="section">
            <h2 class="section-title">Your Answer (Transcribed)</h2>
            <div class="content">{answer_text}</div>
        </div>
        <div class="section">
            <h2 class="section-title">Feedback</h2>
            <div class="content">{feedback}</div>
        </div>
        <div class="section">
            <h2 class="section-title">Model Answer</h2>
            <div class="content">{model_answer}</div>
        </div>
    </body>
    </html>
    """
    # Use a temporary file to store the HTML content for download
    with tempfile.NamedTemporaryFile(delete=False, suffix=".html") as tmp_file:
        tmp_file.write(html_content.encode('utf-8'))
        tmp_file_path = tmp_file.name
    return tmp_file_path

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/analyze-info', methods=['POST'])
def analyze_info_endpoint():
    data = request.get_json()
    job_desc = data.get('job_desc', '')
    company_info = data.get('company_info', '')
    
    parsed_info = interview_manager.analyzer.parse_job_info(job_desc, company_info)
    
    # Store in session for later use
    session['job_desc'] = job_desc
    session['company_info'] = company_info
    session['parsed_info'] = parsed_info
    
    return jsonify(parsed_info)

@app.route('/generate-questions', methods=['POST'])
def generate_questions_endpoint():
    data = request.get_json()
    job_desc = data.get('job_desc', '')
    company_info = data.get('company_info', '')
    resume = data.get('resume', '')
    
    # Store in session for later use
    session['job_desc'] = job_desc
    session['company_info'] = company_info
    session['resume'] = resume
    
    categorized_questions = generate_sample_questions(job_desc, company_info, resume)
    question_hints = get_question_hints()
    
    return jsonify({
        'questions': categorized_questions,
        'hints': question_hints
    })

@app.route('/speech-to-text', methods=['POST'])
def speech_to_text_endpoint():
    data = request.get_json()
    audio_data = data.get('audio', '')
    
    if not audio_data:
        return jsonify({'error': 'No audio data provided'}), 400
    
    text = speech_to_text(audio_data)
    return jsonify({'text': text})

@app.route('/analyze-answer', methods=['POST'])
def analyze_answer_endpoint():
    data = request.get_json()
    voice_answer = data.get('answer_text', '')
    job_desc = data.get('job_desc', session.get('job_desc', ''))
    company_values = data.get('company_values', '')
    
    # Input validation
    if not voice_answer:
        default_feedback = "No answer provided to analyze. Please record or type your answer."
        return jsonify({
            'scores': {'clarity': 0, 'relevance': 0, 'confidence': 0},
            'feedback': default_feedback,
            'formatted_output': default_feedback
        })
    
    try:
        scores, feedback = interview_manager.evaluator.evaluate_answer(voice_answer, job_desc, company_values)
        
        # Ensure feedback is not empty
        if not feedback or len(feedback.strip()) < 10:
            feedback = """I couldn't properly evaluate your answer. Here are some general tips:
            
- Structure your response with a clear beginning, middle, and end
- Relate your experience directly to the job requirements
- Use specific examples from your past experience
- Show confidence in your tone and delivery
            
Try recording again with these tips in mind."""
            scores = {'clarity': 5, 'relevance': 5, 'confidence': 5}
        
        # Create formatted output
        stars = lambda score: "⭐" * score + "☆" * (10 - score)
        combined_output = f"""SCORES:
Clarity: {stars(scores['clarity'])}
Relevance: {stars(scores['relevance'])}
Confidence: {stars(scores['confidence'])}

FEEDBACK:
{feedback}"""
        
        return jsonify({
            'scores': scores,
            'feedback': feedback,
            'formatted_output': combined_output
        })
    except Exception as e:
        print(f"Error in analyze_answer_endpoint: {str(e)}")
        default_feedback = "I'm having trouble analyzing your answer right now. This might be due to a connection issue or server load. Please try again in a moment."
        scores = {'clarity': 5, 'relevance': 5, 'confidence': 5}
        stars = lambda score: "⭐" * score + "☆" * (10 - score)
        combined_output = f"""SCORES:
Clarity: {stars(scores['clarity'])}
Relevance: {stars(scores['relevance'])}
Confidence: {stars(scores['confidence'])}

FEEDBACK:
{default_feedback}"""
        
        return jsonify({
            'scores': scores,
            'feedback': default_feedback,
            'formatted_output': combined_output
        })

@app.route('/generate-model-answer', methods=['POST'])
def generate_model_answer_endpoint():
    data = request.get_json()
    question = data.get('question', '')
    company_info = data.get('company_info', session.get('company_info', ''))
    job_desc = data.get('job_desc', session.get('job_desc', ''))
    resume = data.get('resume', session.get('resume', ''))
    voice_answer = data.get('answer_text', '')
    
    # Input validation
    if not question:
        return jsonify({
            'model_answer': 'No question provided. Please select a question first.'
        })
    
    try:
        model_answer = interview_manager.drafter.generate_answer(question, company_info, job_desc, resume, voice_answer)
        
        # Ensure model answer is not empty
        if not model_answer or len(model_answer.strip()) < 10:
            model_answer = f"""I couldn't generate a complete sample answer for this question: "{question}"
            
Here's a general structure you can follow:

1. Begin with a brief introduction relevant to the question
2. Use the STAR method for behavioral questions:
   - Situation: Describe the context
   - Task: Explain your responsibility
   - Action: Detail the steps you took
   - Result: Share the outcome and what you learned

3. Connect your answer to the specific job requirements
4. Keep your answer concise (about 1-2 minutes when spoken)
5. Practice your delivery to sound natural and confident"""
        
        return jsonify({'model_answer': model_answer})
    except Exception as e:
        print(f"Error in generate_model_answer_endpoint: {str(e)}")
        default_answer = f"""I'm having trouble generating a sample answer for the question: "{question}"

Here are some general tips for this type of question:
- Use the STAR method: Situation, Task, Action, Result
- Relate your answer to the job you're applying for
- Be specific and use concrete examples
- Keep your answer concise and to the point
- Practice your delivery to sound confident and prepared"""
        
        return jsonify({'model_answer': default_answer})

@app.route('/text-to-speech', methods=['POST'])
def text_to_speech_endpoint():
    data = request.get_json()
    text = data.get('text', '')
    voice_option = data.get('voice_option', 'US English')
    
    audio_base64 = text_to_speech(text, voice_option)
    
    return jsonify({'audio': audio_base64})

@app.route('/save-to-html', methods=['POST'])
def save_to_html_endpoint():
    data = request.get_json()
    job_desc = data.get('job_desc', session.get('job_desc', ''))
    company_info = data.get('company_info', session.get('company_info', ''))
    resume = data.get('resume', session.get('resume', ''))
    company_values = data.get('company_values', '')
    tech_skills = data.get('tech_skills', '')
    soft_skills = data.get('soft_skills', '')
    job_duties = data.get('job_duties', '')
    selected_question = data.get('selected_question', '')
    answer_text = data.get('answer_text', '')
    feedback = data.get('feedback', '')
    model_answer = data.get('model_answer', '')
    
    html_file_path = save_to_html(
        job_desc, company_info, resume, company_values, tech_skills, 
        soft_skills, job_duties, selected_question, answer_text, feedback, model_answer
    )
    
    # Generate a unique ID for this file for the frontend to request it
    file_id = str(uuid.uuid4())
    session[f'html_file_{file_id}'] = html_file_path
    
    return jsonify({'file_id': file_id})

@app.route('/download-html/<file_id>', methods=['GET'])
def download_html(file_id):
    file_path = session.get(f'html_file_{file_id}')
    if not file_path:
        return "File not found", 404
    
    # Set the name for the downloaded file
    current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    download_name = f"interview_summary_{current_time}.html"
    
    return send_file(file_path, as_attachment=True, download_name=download_name)

if __name__ == "__main__":
    # Create templates folder if it doesn't exist
    if not os.path.exists('templates'):
        os.makedirs('templates')
    
    # Create static folder if it doesn't exist
    if not os.path.exists('static'):
        os.makedirs('static')
    
    # Copy interviewer.png to static folder if it exists
    if os.path.exists('interviewer.png') and not os.path.exists('static/interviewer.png'):
        import shutil
        shutil.copy('interviewer.png', 'static/interviewer.png')
    
    # Use environment variables for host and port, with defaults for local development
    port = int(os.environ.get("PORT", 7860))
    app.run(host="0.0.0.0", port=port, debug=False)