KhaqanNasir commited on
Commit
7500646
Β·
verified Β·
1 Parent(s): 3b67f3b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -95
app.py CHANGED
@@ -1,98 +1,117 @@
 
1
  import streamlit as st
2
- from streamlit_webrtc import webrtc_streamer, VideoTransformerBase
3
- import cv2
4
- import numpy as np
5
- import requests
6
- from PIL import Image
7
- import io
8
-
9
- # OCR API Key
10
- OCR_API_KEY = "K81127294888957" # Replace with your API key
11
-
12
- # Function to use OCR.space API for text extraction
13
- def ocr_space_image(image):
14
- """OCR.space API to extract text from an image"""
15
- img_byte_arr = io.BytesIO()
16
- image.save(img_byte_arr, format='PNG')
17
- img_byte_arr.seek(0)
18
-
19
- url = "https://api.ocr.space/parse/image"
20
- payload = {
21
- 'apikey': OCR_API_KEY,
22
- 'language': 'eng',
23
- 'filetype': 'PNG'
24
  }
25
- files = {
26
- 'file': ('image.png', img_byte_arr, 'image/png')
27
- }
28
-
29
- response = requests.post(url, data=payload, files=files)
30
- result = response.json()
31
-
32
- if response.status_code == 200 and result["OCRExitCode"] == 1:
33
- return result["ParsedResults"][0]["ParsedText"]
34
- else:
35
- error_message = result.get("ErrorMessage", ["Unknown error"])
36
- return "OCR Error: " + ', '.join(map(str, error_message))
37
-
38
- # Streamlit UI
39
- st.title("Quiz Checker App")
40
- st.header("Upload an Answer Key and Start Webcam for Real-Time Evaluation")
41
-
42
- # Upload answer key
43
- uploaded_file = st.file_uploader("Upload Answer Key Image (JPG/PNG)", type=["jpg", "jpeg", "png"])
44
-
45
- if uploaded_file:
46
- # Process the answer key image
47
- answer_key_img = Image.open(uploaded_file).convert("RGB")
48
- answer_key_text = ocr_space_image(answer_key_img)
49
-
50
- if "OCR Error" in answer_key_text:
51
- st.error("Error extracting text from answer key: " + answer_key_text)
52
  else:
53
- answers = [ans.strip() for ans in answer_key_text.splitlines() if ans.strip()]
54
- st.success("Answer key loaded successfully!")
55
- st.write("Extracted Answers:")
56
- st.write(answers)
57
-
58
- # Define VideoTransformer class for real-time evaluation
59
- class QuizChecker(VideoTransformerBase):
60
- def __init__(self):
61
- self.answers = answers
62
-
63
- def transform(self, frame):
64
- frame = frame.to_ndarray(format="bgr24")
65
- gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
66
-
67
- # Convert frame to PIL image for OCR
68
- pil_image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
69
-
70
- # Extract text from the frame
71
- student_text = ocr_space_image(pil_image)
72
- if "OCR Error" in student_text:
73
- cv2.putText(frame, "Error in OCR", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
74
- return frame
75
-
76
- student_answers = [ans.strip() for ans in student_text.splitlines() if ans.strip()]
77
-
78
- # Compare student answers with the answer key
79
- correct_count = 0
80
- for idx, student_answer in enumerate(student_answers):
81
- if idx < len(self.answers) and student_answer == self.answers[idx]:
82
- color = (0, 255, 0) # Green for correct
83
- correct_count += 1
84
- else:
85
- color = (0, 0, 255) # Red for incorrect
86
- cv2.putText(frame, f"Q{idx+1}: {student_answer}", (10, 50 + idx * 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2)
87
-
88
- # Display the score on the frame
89
- cv2.putText(frame, f"Score: {correct_count}/{len(self.answers)}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
90
-
91
- return frame
92
-
93
- # Start webcam with real-time evaluation
94
- st.header("Real-Time Quiz Evaluation")
95
- webrtc_streamer(key="quiz-checker", video_transformer_factory=QuizChecker, media_stream_constraints={"video": True})
96
-
97
- else:
98
- st.info("Please upload an answer key image to proceed.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Save as `interview_copilot.py`
2
  import streamlit as st
3
+ from streamlit_webrtc import webrtc_streamer
4
+ from transformers import pipeline
5
+ from sentence_transformers import SentenceTransformer
6
+ import openai
7
+ import whisper
8
+ import time
9
+ import random
10
+
11
+ # Configuration for Streamlit
12
+ st.set_page_config(page_title="Interview Copilot", layout="wide")
13
+ st.markdown(
14
+ """
15
+ <style>
16
+ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap');
17
+ html, body, [class*="css"] {
18
+ font-family: 'Poppins', sans-serif;
 
 
 
 
 
 
19
  }
20
+ </style>
21
+ """, unsafe_allow_html=True)
22
+
23
+ # Page Title
24
+ st.title("πŸŽ™οΈ Interview Copilot")
25
+ st.write("### Conduct professional mock interviews, receive feedback, and ace your next job opportunity!")
26
+ st.image("https://via.placeholder.com/800x200?text=Interview+Copilot", use_column_width=True)
27
+
28
+ # Step 1: Input Job Title
29
+ st.subheader("Step 1: Enter Job Details")
30
+ job_title = st.text_input("Enter Job Title:", placeholder="e.g., Data Scientist, Software Engineer")
31
+ job_description = st.text_area("Enter Job Description:", placeholder="Provide details about the role")
32
+
33
+ # Step 2: Upload CV
34
+ st.subheader("Step 2: Upload Your CV")
35
+ uploaded_cv = st.file_uploader("Upload Your CV (PDF or Text):", type=["pdf", "txt"])
36
+ if uploaded_cv:
37
+ cv_content = uploaded_cv.read().decode("utf-8") if uploaded_cv.type == "text/plain" else "Uploaded PDF file"
38
+
39
+ # Step 3: Start Interview
40
+ st.subheader("Step 3: Start the Interview")
41
+ if st.button("Start Interview"):
42
+ if not job_title or not job_description or not uploaded_cv:
43
+ st.error("Please fill in all the required fields (Job Title, Description, CV)!")
 
 
 
44
  else:
45
+ # Simulate Interview Start
46
+ st.subheader("πŸŽ₯ Live Interview Simulation")
47
+ st.write("The interview will begin shortly. Prepare yourself!")
48
+ st.write("πŸ‘€ **Bot:** Hello, let’s start the interview!")
49
+
50
+ # Timer
51
+ start_time = time.time()
52
+ duration = 5 * 60 # 5 minutes
53
+ webrtc_streamer(key="camera", rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]})
54
+
55
+ # Predefined questions
56
+ questions = [
57
+ "Introduce yourself.",
58
+ "Why do you want this job?",
59
+ ]
60
+ technical_questions = [
61
+ "Tell me about a challenging project you've worked on.",
62
+ f"What skills do you bring to the role of {job_title}?",
63
+ ]
64
+ non_technical_questions = [
65
+ "How do you handle conflict in a team setting?",
66
+ "What are your strengths and weaknesses?",
67
+ ]
68
+
69
+ # Generate AI-based questions using Hugging Face models
70
+ question_generator = pipeline("text-generation", model="EleutherAI/gpt-neo-2.7B")
71
+ generated_questions = question_generator(
72
+ f"Generate 3 interview questions for the role of {job_title} based on this CV:\n{cv_content}",
73
+ max_length=50, num_return_sequences=3
74
+ )
75
+ ai_questions = [q["generated_text"] for q in generated_questions]
76
+
77
+ # Combine questions
78
+ all_questions = questions + random.sample(technical_questions, 2) + random.sample(non_technical_questions, 2) + ai_questions
79
+
80
+ # Conduct interview
81
+ responses = []
82
+ for idx, question in enumerate(all_questions):
83
+ st.write(f"**Question {idx + 1}: {question}**")
84
+ user_response = st.text_area(f"Your Answer to Question {idx + 1}", key=f"response_{idx}")
85
+ responses.append(user_response)
86
+
87
+ if time.time() - start_time > duration:
88
+ st.warning("⏱️ Interview time is up!")
89
+ break
90
+
91
+ # Step 4: Evaluation
92
+ st.subheader("πŸ“Š Evaluation")
93
+ st.write("Evaluating your performance based on your answers...")
94
+
95
+ # Communication Skills Analysis
96
+ sentiment_analyzer = pipeline("sentiment-analysis")
97
+ sentiment_results = [sentiment_analyzer(response)[0] for response in responses if response]
98
+ positive_count = sum(1 for result in sentiment_results if result["label"] == "POSITIVE")
99
+
100
+ # Feedback
101
+ score = positive_count * 10 # Simplified scoring
102
+ if score >= 70:
103
+ st.success(f"πŸŽ‰ Great job! You scored {score}/100. You're ready to ace the interview!")
104
+ else:
105
+ st.error(f"πŸ™ You scored {score}/100. Here's how you can improve:")
106
+ st.write("- Practice communicating your ideas clearly.")
107
+ st.write("- Provide detailed examples to technical questions.")
108
+ st.write("- Work on your confidence and tone of speech.")
109
+
110
+ # CV Recommendations
111
+ st.subheader("πŸ“„ CV Recommendations")
112
+ st.write("- Add measurable achievements to your CV.")
113
+ st.write("- Tailor your CV to match the job description.")
114
+
115
+ # Add Graphics and Animation
116
+ st.markdown("---")
117
+ st.markdown("#### Powered by AI | Built with πŸ’» and Streamlit")