HelloLamya1306's picture
Create app.py
5a37189 verified
# βœ… Step 1: Install Required Libraries
# !pip install transformers gradio
# βœ… Step 1: Import Libraries
import gradio as gr
from transformers import pipeline
import random
# βœ… Step 2: Setup Behavioral Analysis Pipeline
qa_classifier = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
def analyze_behavioral_response(response):
result = qa_classifier(response)[0]
label = result['label']
score = result['score']
feedback = "βœ… Good answer!" if label == "POSITIVE" and score > 0.8 else "⚠️ Try being more specific or structured."
return f"Sentiment: {label}, Confidence: {score:.2f}\n\nFeedback: {feedback}"
# βœ… Step 3: Code Evaluation Logic
def evaluate_code(code, expected_keywords_string):
expected_keywords = expected_keywords_string.split(',')
feedback = []
try:
local_env = {}
exec(code, {}, local_env)
feedback.append("βœ… Code executed without errors.")
except Exception as e:
return f"❌ Code Error: {e}"
for keyword in expected_keywords:
keyword = keyword.strip()
if keyword and keyword not in code:
feedback.append(f"⚠️ Missing expected keyword or logic: `{keyword}`")
if len(feedback) == 1:
feedback.append("βœ… Code looks good!")
return "\n".join(feedback)
# βœ… Step 4: Question Banks
technical_questions = {
"frontend": {
"beginner": [
("Create a simple HTML page with a form input and a submit button.", "html,form,input,submit"),
("Write CSS to center a div both vertically and horizontally.", "css,center,flex,justify-content,align-items"),
("Add JavaScript to change a button color on hover.", "javascript,hover,style,backgroundColor"),
("Create a dropdown menu using HTML and CSS.", "select,option,html,css"),
("Implement a click counter using JavaScript.", "javascript,click,addEventListener,counter")
],
"intermediate": [
("Create a responsive navbar using CSS Flexbox.", "nav,flex,media query,css"),
("Build a modal popup using HTML, CSS, and JavaScript.", "modal,html,css,display,show"),
("Create a dark mode toggle using JavaScript.", "toggle,classList,dark,theme"),
("Use JavaScript to validate a user registration form.", "validation,javascript,form,check"),
("Dynamically render a list of items using JavaScript.", "list,forEach,appendChild,createElement")
],
"advanced": [
("Build a simple React component that fetches and displays API data.", "react,useEffect,fetch,setState"),
("Implement a Redux-like state management system in vanilla JS.", "store,dispatch,subscribe,action"),
("Build a React app with routing using React Router.", "react-router,Route,Link,BrowserRouter"),
("Create a drag-and-drop component using plain JavaScript.", "dragstart,dragover,drop,addEventListener"),
("Optimize performance of a React list using memoization.", "memo,useMemo,useCallback,react")
]
},
"backend": {
"beginner": [
("Write a Flask app with one route that returns 'Hello World'.", "flask,route,hello"),
("Create a Python function to hash a password using bcrypt.", "bcrypt,hashpw,password"),
("Set up a SQLite database connection in Flask.", "sqlite3,connect,flask"),
("Return JSON data from a Flask endpoint.", "jsonify,flask,response"),
("Create a POST endpoint in Flask to accept user data.", "POST,request,form,json")
],
"intermediate": [
("Implement JWT-based authentication in Flask.", "jwt,token,authorization,headers"),
("Build a REST API with Flask that supports CRUD for a 'Book' model.", "GET,POST,PUT,DELETE,book"),
("Set up input validation in Flask using Marshmallow.", "Schema,fields,validate,load"),
("Write a middleware to log all incoming requests in Flask.", "before_request,logging"),
("Implement pagination in a Flask REST API.", "limit,offset,page")
],
"advanced": [
("Build a Flask app with role-based user authentication.", "roles,login_required,admin"),
("Integrate OAuth 2.0 login in a Flask app.", "oauth,redirect,authorize"),
("Implement rate limiting for an API endpoint.", "rate limit,requests,time"),
("Secure a Flask app against SQL injection and XSS.", "escape,parameterized,security"),
("Build a background task queue using Celery with Flask.", "celery,task,delay")
]
},
"fullstack": {
"beginner": [
("Build a simple HTML form and process the data using Flask.", "form,action,flask,request"),
("Create a frontend app that fetches data from a local Flask API.", "fetch,api,flask,json"),
("Make a contact form that stores submissions to a backend database.", "form,submit,db,flask"),
("Style a Flask app template using Bootstrap.", "bootstrap,template,link"),
("Build a user login page (frontend + backend).", "login,form,flask,validation")
],
"intermediate": [
("Build a fullstack app with a frontend form and backend data processing.", "form,flask,submit,backend"),
("Create a RESTful API in Flask and connect it with a React frontend.", "fetch,react,flask,route"),
("Implement session management in Flask and use it on the frontend.", "session,cookies,login"),
("Build a to-do app with persistent data storage (frontend + backend).", "todo,add,delete,db"),
("Add error handling on both frontend and backend for a data submission app.", "try,catch,error,except")
],
"advanced": [
("Deploy a fullstack Flask + React app with Docker.", "dockerfile,compose,react,flask"),
("Add real-time updates with WebSockets.", "websocket,emit,socketio"),
("Secure your app using HTTPS and Content Security Policy headers.", "https,csp,headers"),
("Build a multi-user app with different access levels.", "roles,auth,permissions"),
("Optimize frontend-backend performance using caching and batching.", "cache,batch,api")
]
},
"ai engineer": {
"beginner": [
("Write a Python function to tokenize and clean a text string.", "tokenize,lower,strip"),
("Use Hugging Face Transformers to load a sentiment analysis model.", "pipeline,sentiment-analysis,transformers"),
("Load and process a CSV dataset using pandas.", "pandas,read_csv,head"),
("Write a function to compute TF-IDF of a list of documents.", "TfidfVectorizer,fit_transform"),
("Plot a confusion matrix from predicted and true labels.", "confusion_matrix,seaborn,heatmap")
],
"intermediate": [
("Build a sentiment classifier using logistic regression on text data.", "LogisticRegression,fit,predict"),
("Fine-tune a pre-trained transformer model on a custom dataset.", "Trainer,training_args,model"),
("Train and evaluate a simple neural network using PyTorch.", "nn.Module,forward,loss"),
("Implement a spam classifier using scikit-learn.", "CountVectorizer,MultinomialNB"),
("Visualize word embeddings using t-SNE or PCA.", "TSNE,PCA,scatter")
],
"advanced": [
("Create a custom Hugging Face dataset loader.", "datasets,load_dataset"),
("Implement a transformer architecture from scratch.", "attention,layernorm,embedding"),
("Use RLHF to fine-tune a language model for a specific task.", "reinforcement learning,human feedback"),
("Build a QA system using Haystack or LangChain.", "haystack,pipeline,Retriever"),
("Implement multi-GPU training in PyTorch.", "DataParallel,nn,model")
]
},
"data scientist": {
"beginner": [
("Load and summarize a CSV dataset using pandas.", "pandas,read_csv,describe"),
("Plot a histogram and boxplot using seaborn.", "histplot,boxplot,seaborn"),
("Clean missing values in a DataFrame.", "fillna,dropna"),
("Create a correlation heatmap of numeric columns.", "corr,heatmap,seaborn"),
("Group data and calculate mean using pandas groupby.", "groupby,mean")
],
"intermediate": [
("Build and evaluate a linear regression model.", "LinearRegression,fit,score"),
("Apply feature scaling and normalization using scikit-learn.", "StandardScaler,transform"),
("Train a decision tree and plot its structure.", "DecisionTreeClassifier,plot_tree"),
("Perform K-means clustering on a dataset.", "KMeans,fit,predict"),
("Use cross-validation to evaluate a model.", "cross_val_score,KFold")
],
"advanced": [
("Build an end-to-end pipeline with feature engineering and model selection.", "Pipeline,FeatureUnion,GridSearchCV"),
("Apply grid search for hyperparameter tuning.", "GridSearchCV,param_grid"),
("Detect and handle outliers in a dataset.", "zscore,IQR"),
("Use XGBoost for a classification task.", "XGBClassifier,fit,predict"),
("Deploy a model using Flask and expose it as an API.", "Flask,route,predict")
]
},
"devops": {
"beginner": [
("Write a Dockerfile for a simple Python app.", "FROM,WORKDIR,COPY,CMD"),
("Create a GitHub Actions workflow to run tests.", "yaml,actions,run"),
("Set up a local development environment using Docker Compose.", "docker-compose,services"),
("Write a shell script to install dependencies.", "bash,apt-get,yum"),
("Configure environment variables securely.", ".env,os.environ")
],
"intermediate": [
("Deploy a Python web app using Docker and NGINX.", "nginx,docker,proxy"),
("Set up CI/CD pipeline using GitHub Actions.", "jobs,workflow,deploy"),
("Monitor server logs and system metrics.", "logging,metrics,monitoring"),
("Write an Ansible playbook to install and start a service.", "ansible,playbook,task"),
("Implement blue-green deployment in a staging environment.", "blue,green,switch,rollback")
],
"advanced": [
("Configure autoscaling for a cloud-based service.", "autoscale,cloudwatch,asg"),
("Secure infrastructure using IAM roles and policies.", "iam,policy,role"),
("Use Terraform to provision cloud infrastructure.", "terraform,resource,provider"),
("Set up Prometheus and Grafana for monitoring.", "prometheus,grafana,metrics"),
("Implement centralized logging using ELK stack.", "elasticsearch,logstash,kibana")
]
}
}
behavioral_questions = [
"Tell me about a time you had a conflict in a team.",
"Describe a situation where you missed a deadline.",
"How do you handle receiving negative feedback?",
"Share a moment you led a team under pressure.",
"Tell me about a mistake you made and what you learned."
]
# βœ… Step 6: App Logic for Question Navigation
session = {
"role": None,
"tech_index": 0,
"behavior_index": 0,
"tech_qs": [],
}
def start_session(selected_role):
session["role"] = selected_role
session["tech_index"] = 0
session["behavior_index"] = 0
# Get exactly 5 beginner, 5 intermediate, 5 advanced in order
beginner_qs = technical_questions[selected_role]["beginner"][:5]
intermediate_qs = technical_questions[selected_role]["intermediate"][:5]
advanced_qs = technical_questions[selected_role]["advanced"][:5]
session["tech_qs"] = beginner_qs + intermediate_qs + advanced_qs
first_q, hints = session["tech_qs"][0]
session["tech_index"] = 1
return f"Ready for your {selected_role.upper()} interview!\nStarting with Beginner Level Questions.", first_q, hints, "", ""
def next_tech_question():
if session["tech_index"] < 15:
q, hints = session["tech_qs"][session["tech_index"]]
session["tech_index"] += 1
return q, hints, "", ""
else:
return "πŸŽ‰ All technical questions completed!", "", "", ""
def next_behavioral_question():
if session["behavior_index"] < 5:
q = behavioral_questions[session["behavior_index"]]
session["behavior_index"] += 1
return q, ""
else:
return "πŸŽ‰ All behavioral questions completed!", ""
# βœ… Step 6: Gradio Interface
with gr.Blocks() as demo:
gr.Markdown("# πŸ‘©β€πŸ’» Tech Interview Practice")
gr.Markdown("Choose a developer role and get 15 technical + 5 behavioral interview questions with instant AI feedback.")
role = gr.Dropdown(choices=list(technical_questions.keys()), label="Select Developer Role")
start_btn = gr.Button("Start Interview")
start_msg = gr.Textbox(label="Session Status")
with gr.Tab("πŸ’» Technical Interview"):
tech_q = gr.Textbox(label="Technical Question", interactive=False)
tech_hint = gr.Textbox(label="Expected Keywords (For Feedback)", interactive=False)
tech_code = gr.Code(label="Your Code")
tech_submit = gr.Button("Submit Code")
tech_feedback = gr.Textbox(label="AI Feedback")
tech_next = gr.Button("Next Question")
with gr.Tab("🧠 Behavioral Interview"):
beh_q = gr.Textbox(label="Behavioral Question", interactive=False)
beh_answer = gr.Textbox(label="Your Answer", lines=5)
beh_submit = gr.Button("Submit Answer")
beh_feedback = gr.Textbox(label="AI Feedback")
beh_next = gr.Button("Next Question")
# Bind Events
start_btn.click(fn=start_session, inputs=role, outputs=[start_msg, tech_q, tech_hint, tech_code, tech_feedback])
tech_next.click(fn=next_tech_question, outputs=[tech_q, tech_hint, tech_code, tech_feedback])
tech_submit.click(fn=evaluate_code, inputs=[tech_code, tech_hint], outputs=tech_feedback)
beh_next.click(fn=next_behavioral_question, outputs=[beh_q, beh_feedback])
beh_submit.click(fn=analyze_behavioral_response, inputs=beh_answer, outputs=beh_feedback)
demo.launch(share=True)