HelloLamya1306 commited on
Commit
5a37189
Β·
verified Β·
1 Parent(s): 7384fc8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +262 -0
app.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # βœ… Step 1: Install Required Libraries
2
+ # !pip install transformers gradio
3
+
4
+ # βœ… Step 1: Import Libraries
5
+ import gradio as gr
6
+ from transformers import pipeline
7
+ import random
8
+
9
+ # βœ… Step 2: Setup Behavioral Analysis Pipeline
10
+ qa_classifier = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
11
+
12
+ def analyze_behavioral_response(response):
13
+ result = qa_classifier(response)[0]
14
+ label = result['label']
15
+ score = result['score']
16
+ feedback = "βœ… Good answer!" if label == "POSITIVE" and score > 0.8 else "⚠️ Try being more specific or structured."
17
+ return f"Sentiment: {label}, Confidence: {score:.2f}\n\nFeedback: {feedback}"
18
+
19
+ # βœ… Step 3: Code Evaluation Logic
20
+ def evaluate_code(code, expected_keywords_string):
21
+ expected_keywords = expected_keywords_string.split(',')
22
+ feedback = []
23
+
24
+ try:
25
+ local_env = {}
26
+ exec(code, {}, local_env)
27
+ feedback.append("βœ… Code executed without errors.")
28
+ except Exception as e:
29
+ return f"❌ Code Error: {e}"
30
+
31
+ for keyword in expected_keywords:
32
+ keyword = keyword.strip()
33
+ if keyword and keyword not in code:
34
+ feedback.append(f"⚠️ Missing expected keyword or logic: `{keyword}`")
35
+
36
+ if len(feedback) == 1:
37
+ feedback.append("βœ… Code looks good!")
38
+
39
+ return "\n".join(feedback)
40
+
41
+ # βœ… Step 4: Question Banks
42
+ technical_questions = {
43
+ "frontend": {
44
+ "beginner": [
45
+ ("Create a simple HTML page with a form input and a submit button.", "html,form,input,submit"),
46
+ ("Write CSS to center a div both vertically and horizontally.", "css,center,flex,justify-content,align-items"),
47
+ ("Add JavaScript to change a button color on hover.", "javascript,hover,style,backgroundColor"),
48
+ ("Create a dropdown menu using HTML and CSS.", "select,option,html,css"),
49
+ ("Implement a click counter using JavaScript.", "javascript,click,addEventListener,counter")
50
+ ],
51
+ "intermediate": [
52
+ ("Create a responsive navbar using CSS Flexbox.", "nav,flex,media query,css"),
53
+ ("Build a modal popup using HTML, CSS, and JavaScript.", "modal,html,css,display,show"),
54
+ ("Create a dark mode toggle using JavaScript.", "toggle,classList,dark,theme"),
55
+ ("Use JavaScript to validate a user registration form.", "validation,javascript,form,check"),
56
+ ("Dynamically render a list of items using JavaScript.", "list,forEach,appendChild,createElement")
57
+ ],
58
+ "advanced": [
59
+ ("Build a simple React component that fetches and displays API data.", "react,useEffect,fetch,setState"),
60
+ ("Implement a Redux-like state management system in vanilla JS.", "store,dispatch,subscribe,action"),
61
+ ("Build a React app with routing using React Router.", "react-router,Route,Link,BrowserRouter"),
62
+ ("Create a drag-and-drop component using plain JavaScript.", "dragstart,dragover,drop,addEventListener"),
63
+ ("Optimize performance of a React list using memoization.", "memo,useMemo,useCallback,react")
64
+ ]
65
+ },
66
+ "backend": {
67
+ "beginner": [
68
+ ("Write a Flask app with one route that returns 'Hello World'.", "flask,route,hello"),
69
+ ("Create a Python function to hash a password using bcrypt.", "bcrypt,hashpw,password"),
70
+ ("Set up a SQLite database connection in Flask.", "sqlite3,connect,flask"),
71
+ ("Return JSON data from a Flask endpoint.", "jsonify,flask,response"),
72
+ ("Create a POST endpoint in Flask to accept user data.", "POST,request,form,json")
73
+ ],
74
+ "intermediate": [
75
+ ("Implement JWT-based authentication in Flask.", "jwt,token,authorization,headers"),
76
+ ("Build a REST API with Flask that supports CRUD for a 'Book' model.", "GET,POST,PUT,DELETE,book"),
77
+ ("Set up input validation in Flask using Marshmallow.", "Schema,fields,validate,load"),
78
+ ("Write a middleware to log all incoming requests in Flask.", "before_request,logging"),
79
+ ("Implement pagination in a Flask REST API.", "limit,offset,page")
80
+ ],
81
+ "advanced": [
82
+ ("Build a Flask app with role-based user authentication.", "roles,login_required,admin"),
83
+ ("Integrate OAuth 2.0 login in a Flask app.", "oauth,redirect,authorize"),
84
+ ("Implement rate limiting for an API endpoint.", "rate limit,requests,time"),
85
+ ("Secure a Flask app against SQL injection and XSS.", "escape,parameterized,security"),
86
+ ("Build a background task queue using Celery with Flask.", "celery,task,delay")
87
+ ]
88
+ },
89
+ "fullstack": {
90
+ "beginner": [
91
+ ("Build a simple HTML form and process the data using Flask.", "form,action,flask,request"),
92
+ ("Create a frontend app that fetches data from a local Flask API.", "fetch,api,flask,json"),
93
+ ("Make a contact form that stores submissions to a backend database.", "form,submit,db,flask"),
94
+ ("Style a Flask app template using Bootstrap.", "bootstrap,template,link"),
95
+ ("Build a user login page (frontend + backend).", "login,form,flask,validation")
96
+ ],
97
+ "intermediate": [
98
+ ("Build a fullstack app with a frontend form and backend data processing.", "form,flask,submit,backend"),
99
+ ("Create a RESTful API in Flask and connect it with a React frontend.", "fetch,react,flask,route"),
100
+ ("Implement session management in Flask and use it on the frontend.", "session,cookies,login"),
101
+ ("Build a to-do app with persistent data storage (frontend + backend).", "todo,add,delete,db"),
102
+ ("Add error handling on both frontend and backend for a data submission app.", "try,catch,error,except")
103
+ ],
104
+ "advanced": [
105
+ ("Deploy a fullstack Flask + React app with Docker.", "dockerfile,compose,react,flask"),
106
+ ("Add real-time updates with WebSockets.", "websocket,emit,socketio"),
107
+ ("Secure your app using HTTPS and Content Security Policy headers.", "https,csp,headers"),
108
+ ("Build a multi-user app with different access levels.", "roles,auth,permissions"),
109
+ ("Optimize frontend-backend performance using caching and batching.", "cache,batch,api")
110
+ ]
111
+ },
112
+ "ai engineer": {
113
+ "beginner": [
114
+ ("Write a Python function to tokenize and clean a text string.", "tokenize,lower,strip"),
115
+ ("Use Hugging Face Transformers to load a sentiment analysis model.", "pipeline,sentiment-analysis,transformers"),
116
+ ("Load and process a CSV dataset using pandas.", "pandas,read_csv,head"),
117
+ ("Write a function to compute TF-IDF of a list of documents.", "TfidfVectorizer,fit_transform"),
118
+ ("Plot a confusion matrix from predicted and true labels.", "confusion_matrix,seaborn,heatmap")
119
+ ],
120
+ "intermediate": [
121
+ ("Build a sentiment classifier using logistic regression on text data.", "LogisticRegression,fit,predict"),
122
+ ("Fine-tune a pre-trained transformer model on a custom dataset.", "Trainer,training_args,model"),
123
+ ("Train and evaluate a simple neural network using PyTorch.", "nn.Module,forward,loss"),
124
+ ("Implement a spam classifier using scikit-learn.", "CountVectorizer,MultinomialNB"),
125
+ ("Visualize word embeddings using t-SNE or PCA.", "TSNE,PCA,scatter")
126
+ ],
127
+ "advanced": [
128
+ ("Create a custom Hugging Face dataset loader.", "datasets,load_dataset"),
129
+ ("Implement a transformer architecture from scratch.", "attention,layernorm,embedding"),
130
+ ("Use RLHF to fine-tune a language model for a specific task.", "reinforcement learning,human feedback"),
131
+ ("Build a QA system using Haystack or LangChain.", "haystack,pipeline,Retriever"),
132
+ ("Implement multi-GPU training in PyTorch.", "DataParallel,nn,model")
133
+ ]
134
+ },
135
+ "data scientist": {
136
+ "beginner": [
137
+ ("Load and summarize a CSV dataset using pandas.", "pandas,read_csv,describe"),
138
+ ("Plot a histogram and boxplot using seaborn.", "histplot,boxplot,seaborn"),
139
+ ("Clean missing values in a DataFrame.", "fillna,dropna"),
140
+ ("Create a correlation heatmap of numeric columns.", "corr,heatmap,seaborn"),
141
+ ("Group data and calculate mean using pandas groupby.", "groupby,mean")
142
+ ],
143
+ "intermediate": [
144
+ ("Build and evaluate a linear regression model.", "LinearRegression,fit,score"),
145
+ ("Apply feature scaling and normalization using scikit-learn.", "StandardScaler,transform"),
146
+ ("Train a decision tree and plot its structure.", "DecisionTreeClassifier,plot_tree"),
147
+ ("Perform K-means clustering on a dataset.", "KMeans,fit,predict"),
148
+ ("Use cross-validation to evaluate a model.", "cross_val_score,KFold")
149
+ ],
150
+ "advanced": [
151
+ ("Build an end-to-end pipeline with feature engineering and model selection.", "Pipeline,FeatureUnion,GridSearchCV"),
152
+ ("Apply grid search for hyperparameter tuning.", "GridSearchCV,param_grid"),
153
+ ("Detect and handle outliers in a dataset.", "zscore,IQR"),
154
+ ("Use XGBoost for a classification task.", "XGBClassifier,fit,predict"),
155
+ ("Deploy a model using Flask and expose it as an API.", "Flask,route,predict")
156
+ ]
157
+ },
158
+ "devops": {
159
+ "beginner": [
160
+ ("Write a Dockerfile for a simple Python app.", "FROM,WORKDIR,COPY,CMD"),
161
+ ("Create a GitHub Actions workflow to run tests.", "yaml,actions,run"),
162
+ ("Set up a local development environment using Docker Compose.", "docker-compose,services"),
163
+ ("Write a shell script to install dependencies.", "bash,apt-get,yum"),
164
+ ("Configure environment variables securely.", ".env,os.environ")
165
+ ],
166
+ "intermediate": [
167
+ ("Deploy a Python web app using Docker and NGINX.", "nginx,docker,proxy"),
168
+ ("Set up CI/CD pipeline using GitHub Actions.", "jobs,workflow,deploy"),
169
+ ("Monitor server logs and system metrics.", "logging,metrics,monitoring"),
170
+ ("Write an Ansible playbook to install and start a service.", "ansible,playbook,task"),
171
+ ("Implement blue-green deployment in a staging environment.", "blue,green,switch,rollback")
172
+ ],
173
+ "advanced": [
174
+ ("Configure autoscaling for a cloud-based service.", "autoscale,cloudwatch,asg"),
175
+ ("Secure infrastructure using IAM roles and policies.", "iam,policy,role"),
176
+ ("Use Terraform to provision cloud infrastructure.", "terraform,resource,provider"),
177
+ ("Set up Prometheus and Grafana for monitoring.", "prometheus,grafana,metrics"),
178
+ ("Implement centralized logging using ELK stack.", "elasticsearch,logstash,kibana")
179
+ ]
180
+ }
181
+ }
182
+
183
+ behavioral_questions = [
184
+ "Tell me about a time you had a conflict in a team.",
185
+ "Describe a situation where you missed a deadline.",
186
+ "How do you handle receiving negative feedback?",
187
+ "Share a moment you led a team under pressure.",
188
+ "Tell me about a mistake you made and what you learned."
189
+ ]
190
+
191
+ # βœ… Step 6: App Logic for Question Navigation
192
+ session = {
193
+ "role": None,
194
+ "tech_index": 0,
195
+ "behavior_index": 0,
196
+ "tech_qs": [],
197
+ }
198
+
199
+ def start_session(selected_role):
200
+ session["role"] = selected_role
201
+ session["tech_index"] = 0
202
+ session["behavior_index"] = 0
203
+
204
+ # Get exactly 5 beginner, 5 intermediate, 5 advanced in order
205
+ beginner_qs = technical_questions[selected_role]["beginner"][:5]
206
+ intermediate_qs = technical_questions[selected_role]["intermediate"][:5]
207
+ advanced_qs = technical_questions[selected_role]["advanced"][:5]
208
+
209
+ session["tech_qs"] = beginner_qs + intermediate_qs + advanced_qs
210
+
211
+ first_q, hints = session["tech_qs"][0]
212
+ session["tech_index"] = 1
213
+ return f"Ready for your {selected_role.upper()} interview!\nStarting with Beginner Level Questions.", first_q, hints, "", ""
214
+
215
+ def next_tech_question():
216
+ if session["tech_index"] < 15:
217
+ q, hints = session["tech_qs"][session["tech_index"]]
218
+ session["tech_index"] += 1
219
+ return q, hints, "", ""
220
+ else:
221
+ return "πŸŽ‰ All technical questions completed!", "", "", ""
222
+
223
+ def next_behavioral_question():
224
+ if session["behavior_index"] < 5:
225
+ q = behavioral_questions[session["behavior_index"]]
226
+ session["behavior_index"] += 1
227
+ return q, ""
228
+ else:
229
+ return "πŸŽ‰ All behavioral questions completed!", ""
230
+
231
+ # βœ… Step 6: Gradio Interface
232
+ with gr.Blocks() as demo:
233
+ gr.Markdown("# πŸ‘©β€πŸ’» Tech Interview Practice")
234
+ gr.Markdown("Choose a developer role and get 15 technical + 5 behavioral interview questions with instant AI feedback.")
235
+
236
+ role = gr.Dropdown(choices=list(technical_questions.keys()), label="Select Developer Role")
237
+ start_btn = gr.Button("Start Interview")
238
+ start_msg = gr.Textbox(label="Session Status")
239
+
240
+ with gr.Tab("πŸ’» Technical Interview"):
241
+ tech_q = gr.Textbox(label="Technical Question", interactive=False)
242
+ tech_hint = gr.Textbox(label="Expected Keywords (For Feedback)", interactive=False)
243
+ tech_code = gr.Code(label="Your Code")
244
+ tech_submit = gr.Button("Submit Code")
245
+ tech_feedback = gr.Textbox(label="AI Feedback")
246
+ tech_next = gr.Button("Next Question")
247
+
248
+ with gr.Tab("🧠 Behavioral Interview"):
249
+ beh_q = gr.Textbox(label="Behavioral Question", interactive=False)
250
+ beh_answer = gr.Textbox(label="Your Answer", lines=5)
251
+ beh_submit = gr.Button("Submit Answer")
252
+ beh_feedback = gr.Textbox(label="AI Feedback")
253
+ beh_next = gr.Button("Next Question")
254
+
255
+ # Bind Events
256
+ start_btn.click(fn=start_session, inputs=role, outputs=[start_msg, tech_q, tech_hint, tech_code, tech_feedback])
257
+ tech_next.click(fn=next_tech_question, outputs=[tech_q, tech_hint, tech_code, tech_feedback])
258
+ tech_submit.click(fn=evaluate_code, inputs=[tech_code, tech_hint], outputs=tech_feedback)
259
+ beh_next.click(fn=next_behavioral_question, outputs=[beh_q, beh_feedback])
260
+ beh_submit.click(fn=analyze_behavioral_response, inputs=beh_answer, outputs=beh_feedback)
261
+
262
+ demo.launch(share=True)