Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
208283304a | ||
|
|
8f171055f9 | ||
|
|
cc900c05e6 |
@@ -1,12 +0,0 @@
|
||||
.git
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
.venv/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
*.db
|
||||
.DS_Store
|
||||
|
||||
TASK4/node_modules/
|
||||
TASK4/dist/
|
||||
+6
-16
@@ -1,19 +1,9 @@
|
||||
# Python
|
||||
cat >> .gitignore <<'EOF'
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Local database
|
||||
users.db
|
||||
|
||||
# Local editor/build files
|
||||
.gradle/
|
||||
.vscode/
|
||||
build/
|
||||
|
||||
# Angular generated files
|
||||
TASK4/.angular/
|
||||
TASK4/dist/
|
||||
TASK4/node_modules/
|
||||
|
||||
# Mac
|
||||
.ipynb_checkpoints/
|
||||
.DS_Store
|
||||
.vscode/
|
||||
.pytest_cache/
|
||||
text-classification-demo/customer_support_tickets.csv
|
||||
EOF
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY main.py .
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -1,60 +0,0 @@
|
||||
# FastAPI CRUD (Simple Task)
|
||||
|
||||
This project is a simple web service for one user entity: `name`, `age`.
|
||||
|
||||
Tech used:
|
||||
- FastAPI
|
||||
- Pydantic
|
||||
- SQLAlchemy
|
||||
- SQLite (`users.db`)
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
pip install fastapi uvicorn sqlalchemy
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
Open:
|
||||
- API root: `http://127.0.0.1:8000/`
|
||||
- Swagger UI: `http://127.0.0.1:8000/docs`
|
||||
|
||||
## Endpoints
|
||||
|
||||
- `POST /users` (Create)
|
||||
- `GET /users` (Read all)
|
||||
- `GET /users/{user_id}` (Read one)
|
||||
- `PUT /users/{user_id}` (Update)
|
||||
- `DELETE /users/{user_id}` (Delete)
|
||||
|
||||
## Quick Test (Swagger)
|
||||
|
||||
1. `POST /users` with:
|
||||
```json
|
||||
{"name":"Sara","age":22}
|
||||
```
|
||||
2. Copy returned `id`
|
||||
3. Test `GET/PUT/DELETE` with that `id`
|
||||
|
||||
## Run With Docker (Backend + Angular Frontend)
|
||||
|
||||
This repo also includes Docker setup for both services:
|
||||
- `api` (FastAPI) on port `8000`
|
||||
- `frontend` (Angular served by Nginx) on port `4200`
|
||||
|
||||
Start everything:
|
||||
|
||||
```bash
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
Open:
|
||||
- Frontend SPA: `http://localhost:4200`
|
||||
- FastAPI directly: `http://localhost:8000`
|
||||
- Swagger UI: `http://localhost:8000/docs`
|
||||
|
||||
### How Angular `HttpClient` reaches FastAPI in Docker
|
||||
|
||||
- Angular service uses `basePath: '/api'`.
|
||||
- Nginx in the frontend container proxies `/api/*` to `http://api:8000/*`.
|
||||
- `api` is the Docker Compose service name, so containers can reach it on the internal network.
|
||||
@@ -0,0 +1,85 @@
|
||||
# Task 1 Complete - Local Environment Setup
|
||||
|
||||
Date completed: April 20, 2026
|
||||
Project folder: `/Users/saraerf/aiis-task1`
|
||||
|
||||
## 1. Conda environment management
|
||||
|
||||
Status: COMPLETE
|
||||
|
||||
- Environment file exists: `environment.yml`
|
||||
- Environment name: `aiis`
|
||||
- Python pinned in env: `3.10.20`
|
||||
|
||||
Commands:
|
||||
```bash
|
||||
conda env create -f environment.yml
|
||||
conda activate aiis
|
||||
conda env list
|
||||
```
|
||||
|
||||
Verified output (this machine):
|
||||
- `aiis` environment exists at `/opt/anaconda3/envs/aiis`
|
||||
|
||||
## 2. Python installation check
|
||||
|
||||
Status: COMPLETE
|
||||
|
||||
Command:
|
||||
```bash
|
||||
python3 --version
|
||||
```
|
||||
|
||||
Verified output:
|
||||
- `Python 3.10.20` (meets 3.10+ requirement)
|
||||
|
||||
## 3. VS Code + productivity setup
|
||||
|
||||
Status: COMPLETE
|
||||
|
||||
Installed extensions verified:
|
||||
- `ms-python.python`
|
||||
- `ms-python.vscode-pylance`
|
||||
- `ms-toolsai.jupyter`
|
||||
- `charliermarsh.ruff`
|
||||
- `postman.postman-for-vscode`
|
||||
|
||||
Workspace settings already set in `.vscode/settings.json`:
|
||||
- `python.defaultInterpreterPath = /opt/anaconda3/envs/aiis/bin/python`
|
||||
- `jupyter.jupyterServerType = local`
|
||||
|
||||
## 4. Hello World sanity check (.py)
|
||||
|
||||
Status: COMPLETE
|
||||
|
||||
Command:
|
||||
```bash
|
||||
conda run -n aiis python hello.py
|
||||
```
|
||||
|
||||
Verified output:
|
||||
- `Hello AIIS`
|
||||
|
||||
## 5. Hello World sanity check (Jupyter notebook)
|
||||
|
||||
Status: COMPLETE
|
||||
|
||||
Notebook file:
|
||||
- `hello.ipynb`
|
||||
|
||||
Kernel metadata verified:
|
||||
- `Python (aiis)`
|
||||
|
||||
Execution check command:
|
||||
```bash
|
||||
conda run -n aiis python -m jupyter nbconvert --to notebook --execute hello.ipynb --output /tmp/hello.task1.executed.ipynb
|
||||
```
|
||||
|
||||
Verified result:
|
||||
- Notebook executed successfully without errors
|
||||
|
||||
---
|
||||
|
||||
## Final result
|
||||
|
||||
Task 1 is fully completed on this machine.
|
||||
@@ -1,3 +0,0 @@
|
||||
node_modules
|
||||
dist
|
||||
.DS_Store
|
||||
@@ -1,17 +0,0 @@
|
||||
# Editor configuration, see https://editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.ts]
|
||||
quote_type = single
|
||||
ij_typescript_use_double_quotes = false
|
||||
|
||||
[*.md]
|
||||
max_line_length = off
|
||||
trim_trailing_whitespace = false
|
||||
@@ -1,10 +0,0 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
users.db
|
||||
.gradle/
|
||||
build/
|
||||
.vscode/
|
||||
TASK4/node_modules/
|
||||
TASK4/dist/
|
||||
TASK4/.angular/
|
||||
.DS_Store
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"singleQuote": true,
|
||||
"overrides": [
|
||||
{
|
||||
"files": "*.html",
|
||||
"options": {
|
||||
"parser": "angular"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
-4
@@ -1,4 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
|
||||
"recommendations": ["angular.ng-template"]
|
||||
}
|
||||
Vendored
-20
@@ -1,20 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "ng serve",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "npm: start",
|
||||
"url": "http://localhost:4200/"
|
||||
},
|
||||
{
|
||||
"name": "ng test",
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "npm: test",
|
||||
"url": "http://localhost:9876/debug.html"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
-9
@@ -1,9 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://angular.dev/ai/mcp
|
||||
"servers": {
|
||||
"angular-cli": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@angular/cli", "mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
-42
@@ -1,42 +0,0 @@
|
||||
{
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "start",
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"owner": "typescript",
|
||||
"pattern": "$tsc",
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": {
|
||||
"regexp": "Changes detected"
|
||||
},
|
||||
"endsPattern": {
|
||||
"regexp": "bundle generation (complete|failed)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "test",
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"owner": "typescript",
|
||||
"pattern": "$tsc",
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": {
|
||||
"regexp": "Changes detected"
|
||||
},
|
||||
"endsPattern": {
|
||||
"regexp": "bundle generation (complete|failed)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
FROM node:22-alpine AS build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:1.27-alpine
|
||||
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/dist/task4-angular-frontend /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -1,96 +0,0 @@
|
||||
{
|
||||
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
|
||||
"version": 1,
|
||||
"cli": {
|
||||
"packageManager": "npm",
|
||||
"analytics": "2b0900be-255e-4f93-bf38-d28b79b712d6"
|
||||
},
|
||||
"newProjectRoot": "projects",
|
||||
"projects": {
|
||||
"task4-angular-frontend": {
|
||||
"projectType": "application",
|
||||
"schematics": {
|
||||
"@schematics/angular:class": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:component": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:directive": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:guard": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:interceptor": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:pipe": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:resolver": {
|
||||
"skipTests": true
|
||||
},
|
||||
"@schematics/angular:service": {
|
||||
"skipTests": true
|
||||
}
|
||||
},
|
||||
"root": "",
|
||||
"sourceRoot": "src",
|
||||
"prefix": "app",
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular/build:application",
|
||||
"options": {
|
||||
"browser": "src/main.ts",
|
||||
"tsConfig": "tsconfig.app.json",
|
||||
"assets": [
|
||||
{
|
||||
"glob": "**/*",
|
||||
"input": "public"
|
||||
}
|
||||
],
|
||||
"styles": [
|
||||
"src/styles.css"
|
||||
]
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"budgets": [
|
||||
{
|
||||
"type": "initial",
|
||||
"maximumWarning": "500kB",
|
||||
"maximumError": "1MB"
|
||||
},
|
||||
{
|
||||
"type": "anyComponentStyle",
|
||||
"maximumWarning": "4kB",
|
||||
"maximumError": "8kB"
|
||||
}
|
||||
],
|
||||
"outputHashing": "all"
|
||||
},
|
||||
"development": {
|
||||
"optimization": false,
|
||||
"extractLicenses": false,
|
||||
"sourceMap": true
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "production"
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular/build:dev-server",
|
||||
"configurations": {
|
||||
"production": {
|
||||
"buildTarget": "task4-angular-frontend:build:production"
|
||||
},
|
||||
"development": {
|
||||
"buildTarget": "task4-angular-frontend:build:development"
|
||||
}
|
||||
},
|
||||
"defaultConfiguration": "development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://api:8000/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
Generated
-7723
File diff suppressed because it is too large
Load Diff
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"name": "task4-angular-frontend",
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve --proxy-config proxy.conf.json",
|
||||
"build": "ng build",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
"test": "ng test"
|
||||
},
|
||||
"private": true,
|
||||
"packageManager": "npm@11.3.0",
|
||||
"dependencies": {
|
||||
"@angular/common": "^21.2.0",
|
||||
"@angular/compiler": "^21.2.0",
|
||||
"@angular/core": "^21.2.0",
|
||||
"@angular/forms": "^21.2.0",
|
||||
"@angular/platform-browser": "^21.2.0",
|
||||
"@angular/router": "^21.2.0",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^21.2.11",
|
||||
"@angular/cli": "^21.2.11",
|
||||
"@angular/compiler-cli": "^21.2.0",
|
||||
"prettier": "^3.8.1",
|
||||
"typescript": "~5.9.2"
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"/api": {
|
||||
"target": "http://127.0.0.1:8000",
|
||||
"secure": false,
|
||||
"changeOrigin": true,
|
||||
"pathRewrite": {
|
||||
"^/api": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB |
@@ -1,10 +0,0 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
provideBrowserGlobalErrorListeners(),
|
||||
// Registers HttpClient globally so services can call the backend API.
|
||||
provideHttpClient()
|
||||
]
|
||||
};
|
||||
@@ -1,52 +0,0 @@
|
||||
:host {
|
||||
display: block;
|
||||
min-height: 100vh;
|
||||
background-color: #f3f5f7;
|
||||
color: #222222;
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
padding: 1.5rem 1rem 2rem;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin-bottom: 0.4rem;
|
||||
font-size: 1.6rem;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
margin-top: 0;
|
||||
color: #555555;
|
||||
}
|
||||
|
||||
.layout {
|
||||
margin-top: 1rem;
|
||||
display: grid;
|
||||
grid-template-columns: 300px 1fr;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.message {
|
||||
border-radius: 6px;
|
||||
padding: 0.65rem 0.8rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.message.error {
|
||||
background-color: #ffe8e8;
|
||||
border: 1px solid #f0a9a9;
|
||||
}
|
||||
|
||||
.message.success {
|
||||
background-color: #e9faec;
|
||||
border: 1px solid #9ed9a8;
|
||||
}
|
||||
|
||||
@media (max-width: 850px) {
|
||||
.layout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
<main class="container">
|
||||
<h1>Task 4: Angular + FastAPI Users</h1>
|
||||
<p class="subtitle">Simple SPA showing Angular</p>
|
||||
|
||||
@if (errorMessage) {
|
||||
<p class="message error">{{ errorMessage }}</p>
|
||||
}
|
||||
|
||||
@if (successMessage) {
|
||||
<p class="message success">{{ successMessage }}</p>
|
||||
}
|
||||
|
||||
<section class="layout">
|
||||
<app-user-form
|
||||
[userToEdit]="selectedUser"
|
||||
(saveUser)="onSaveUser($event)"
|
||||
(cancelEdit)="onCancelEdit()"
|
||||
/>
|
||||
|
||||
<app-user-list
|
||||
[users]="users"
|
||||
[isLoading]="isLoading"
|
||||
(editUser)="onEditUser($event)"
|
||||
(deleteUser)="onDeleteUser($event)"
|
||||
/>
|
||||
</section>
|
||||
</main>
|
||||
@@ -1,4 +0,0 @@
|
||||
import { Routes } from '@angular/router';
|
||||
|
||||
// This app currently keeps everything on one page (single-route SPA).
|
||||
export const routes: Routes = [];
|
||||
@@ -1,98 +0,0 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { UserFormComponent } from './components/user-form/user-form';
|
||||
import { UserListComponent } from './components/user-list/user-list';
|
||||
import { UserFormSubmitEvent, User } from './models/user.model';
|
||||
import { UserService } from './services/user.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
imports: [UserFormComponent, UserListComponent],
|
||||
templateUrl: './app.html',
|
||||
styleUrl: './app.css'
|
||||
})
|
||||
export class App implements OnInit {
|
||||
users: User[] = [];
|
||||
selectedUser: User | null = null;
|
||||
isLoading = false;
|
||||
errorMessage = '';
|
||||
successMessage = '';
|
||||
|
||||
// App component acts as a simple page controller for this SPA.
|
||||
constructor(private readonly userService: UserService) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadUsers();
|
||||
}
|
||||
|
||||
loadUsers(): void {
|
||||
this.isLoading = true;
|
||||
this.errorMessage = '';
|
||||
|
||||
this.userService.getUsers().subscribe({
|
||||
next: (users) => {
|
||||
this.users = users;
|
||||
this.isLoading = false;
|
||||
},
|
||||
error: (error) => this.handleError('load users', error)
|
||||
});
|
||||
}
|
||||
|
||||
onSaveUser(event: UserFormSubmitEvent): void {
|
||||
this.isLoading = true;
|
||||
this.errorMessage = '';
|
||||
this.successMessage = '';
|
||||
|
||||
const request$ = event.id
|
||||
? this.userService.updateUser(event.id, event.payload)
|
||||
: this.userService.createUser(event.payload);
|
||||
|
||||
request$.subscribe({
|
||||
next: () => {
|
||||
this.successMessage = event.id ? 'User updated successfully.' : 'User created successfully.';
|
||||
this.selectedUser = null;
|
||||
this.loadUsers();
|
||||
},
|
||||
error: (error) => this.handleError(event.id ? 'update user' : 'create user', error)
|
||||
});
|
||||
}
|
||||
|
||||
onEditUser(user: User): void {
|
||||
this.selectedUser = { ...user };
|
||||
this.successMessage = '';
|
||||
}
|
||||
|
||||
onCancelEdit(): void {
|
||||
this.selectedUser = null;
|
||||
}
|
||||
|
||||
onDeleteUser(userId: number): void {
|
||||
const shouldDelete = window.confirm('Delete this user?');
|
||||
if (!shouldDelete) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isLoading = true;
|
||||
this.errorMessage = '';
|
||||
this.successMessage = '';
|
||||
|
||||
this.userService.deleteUser(userId).subscribe({
|
||||
next: () => {
|
||||
this.successMessage = 'User deleted successfully.';
|
||||
|
||||
if (this.selectedUser?.id === userId) {
|
||||
this.selectedUser = null;
|
||||
}
|
||||
|
||||
this.loadUsers();
|
||||
},
|
||||
error: (error) => this.handleError('delete user', error)
|
||||
});
|
||||
}
|
||||
|
||||
private handleError(action: string, error: HttpErrorResponse): void {
|
||||
console.error(`Could not ${action}:`, error);
|
||||
this.isLoading = false;
|
||||
this.errorMessage = `Could not ${action}. Please check backend connection and try again.`;
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
.card {
|
||||
background-color: #ffffff;
|
||||
border: 1px solid #d7d7d7;
|
||||
border-radius: 8px;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin-top: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
form {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
label {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
input {
|
||||
padding: 0.5rem;
|
||||
border: 1px solid #c8c8c8;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 0.5rem 0.8rem;
|
||||
border: 1px solid #2f5dff;
|
||||
border-radius: 4px;
|
||||
background-color: #2f5dff;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.secondary {
|
||||
background-color: #ffffff;
|
||||
color: #2f5dff;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.65;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
<section class="card">
|
||||
<h2>{{ isEditMode ? 'Edit user' : 'Create user' }}</h2>
|
||||
|
||||
<form (ngSubmit)="onSubmit()" #userForm="ngForm">
|
||||
<label for="name">Name</label>
|
||||
<input
|
||||
id="name"
|
||||
name="name"
|
||||
type="text"
|
||||
required
|
||||
minlength="1"
|
||||
maxlength="50"
|
||||
[(ngModel)]="name"
|
||||
/>
|
||||
|
||||
<label for="age">Age</label>
|
||||
<input
|
||||
id="age"
|
||||
name="age"
|
||||
type="number"
|
||||
required
|
||||
min="1"
|
||||
[(ngModel)]="age"
|
||||
/>
|
||||
|
||||
<div class="actions">
|
||||
<button type="submit" [disabled]="userForm.invalid">
|
||||
{{ isEditMode ? 'Update user' : 'Create user' }}
|
||||
</button>
|
||||
|
||||
@if (isEditMode) {
|
||||
<button type="button" class="secondary" (click)="onCancel()">Cancel edit</button>
|
||||
}
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
@@ -1,66 +0,0 @@
|
||||
import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { User, UserFormSubmitEvent } from '../../models/user.model';
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-form',
|
||||
imports: [FormsModule],
|
||||
templateUrl: './user-form.html',
|
||||
styleUrl: './user-form.css',
|
||||
})
|
||||
export class UserFormComponent implements OnChanges {
|
||||
// Input lets the parent component pass data into this form component.
|
||||
@Input() userToEdit: User | null = null;
|
||||
|
||||
// Output sends events from child -> parent.
|
||||
@Output() saveUser = new EventEmitter<UserFormSubmitEvent>();
|
||||
@Output() cancelEdit = new EventEmitter<void>();
|
||||
|
||||
name = '';
|
||||
age: number | null = null;
|
||||
isEditMode = false;
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (!changes['userToEdit']) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.userToEdit) {
|
||||
this.name = this.userToEdit.name;
|
||||
this.age = this.userToEdit.age;
|
||||
this.isEditMode = true;
|
||||
return;
|
||||
}
|
||||
|
||||
this.resetForm();
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
if (!this.name.trim() || this.age === null || this.age <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.saveUser.emit({
|
||||
id: this.userToEdit?.id,
|
||||
payload: {
|
||||
name: this.name.trim(),
|
||||
age: this.age
|
||||
}
|
||||
});
|
||||
|
||||
if (!this.isEditMode) {
|
||||
this.resetForm();
|
||||
}
|
||||
}
|
||||
|
||||
onCancel(): void {
|
||||
this.resetForm();
|
||||
this.cancelEdit.emit();
|
||||
}
|
||||
|
||||
private resetForm(): void {
|
||||
this.name = '';
|
||||
this.age = null;
|
||||
this.isEditMode = false;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
.card {
|
||||
background-color: #ffffff;
|
||||
border: 1px solid #d7d7d7;
|
||||
border-radius: 8px;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin-top: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
border-bottom: 1px solid #e4e4e4;
|
||||
padding: 0.6rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
td:last-child {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
button {
|
||||
margin-right: 0.4rem;
|
||||
padding: 0.35rem 0.6rem;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #b8b8b8;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button.secondary {
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
button.danger {
|
||||
background-color: #ffe6e6;
|
||||
border-color: #df8d8d;
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
<section class="card">
|
||||
<h2>Users</h2>
|
||||
|
||||
@if (isLoading) {
|
||||
<p>Loading users...</p>
|
||||
} @else {
|
||||
@if (users.length === 0) {
|
||||
<p>No users found.</p>
|
||||
} @else {
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Name</th>
|
||||
<th>Age</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (user of users; track user.id) {
|
||||
<tr>
|
||||
<td>{{ user.id }}</td>
|
||||
<td>{{ user.name }}</td>
|
||||
<td>{{ user.age }}</td>
|
||||
<td>
|
||||
<button type="button" class="secondary" (click)="editUser.emit(user)">Edit</button>
|
||||
<button type="button" class="danger" (click)="deleteUser.emit(user.id)">Delete</button>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -1,17 +0,0 @@
|
||||
import { Component, EventEmitter, Input, Output } from '@angular/core';
|
||||
import { User } from '../../models/user.model';
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-list',
|
||||
imports: [],
|
||||
templateUrl: './user-list.html',
|
||||
styleUrl: './user-list.css',
|
||||
})
|
||||
export class UserListComponent {
|
||||
@Input() users: User[] = [];
|
||||
@Input() isLoading = false;
|
||||
|
||||
// The parent handles actual CRUD actions; this component only emits user intent.
|
||||
@Output() editUser = new EventEmitter<User>();
|
||||
@Output() deleteUser = new EventEmitter<number>();
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
|
||||
export const API_CONFIG = {
|
||||
|
||||
basePath: '/api'
|
||||
};
|
||||
@@ -1,15 +0,0 @@
|
||||
export interface User {
|
||||
id: number;
|
||||
name: string;
|
||||
age: number;
|
||||
}
|
||||
|
||||
export interface UserPayload {
|
||||
name: string;
|
||||
age: number;
|
||||
}
|
||||
|
||||
export interface UserFormSubmitEvent {
|
||||
id?: number;
|
||||
payload: UserPayload;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { API_CONFIG } from '../core/api.config';
|
||||
import { User, UserPayload } from '../models/user.model';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class UserService {
|
||||
private readonly usersUrl = `${API_CONFIG.basePath}/users`;
|
||||
|
||||
// Services centralize backend communication and can be reused by many components.
|
||||
constructor(private readonly http: HttpClient) {}
|
||||
|
||||
getUsers(): Observable<User[]> {
|
||||
return this.http.get<User[]>(this.usersUrl);
|
||||
}
|
||||
|
||||
createUser(payload: UserPayload): Observable<User> {
|
||||
return this.http.post<User>(this.usersUrl, payload);
|
||||
}
|
||||
|
||||
updateUser(userId: number, payload: UserPayload): Observable<User> {
|
||||
return this.http.put<User>(`${this.usersUrl}/${userId}`, payload);
|
||||
}
|
||||
|
||||
deleteUser(userId: number): Observable<{ message: string }> {
|
||||
return this.http.delete<{ message: string }>(`${this.usersUrl}/${userId}`);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Task4AngularFrontend</title>
|
||||
<base href="/">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico">
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,6 +0,0 @@
|
||||
import { bootstrapApplication } from '@angular/platform-browser';
|
||||
import { appConfig } from './app/app.config';
|
||||
import { App } from './app/app';
|
||||
|
||||
bootstrapApplication(App, appConfig)
|
||||
.catch((err) => console.error(err));
|
||||
@@ -1 +0,0 @@
|
||||
/* You can add global styles to this file, and also import other style files */
|
||||
@@ -1,16 +0,0 @@
|
||||
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
|
||||
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/app",
|
||||
"rootDir": "./src",
|
||||
"types": []
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"src/**/*.spec.ts"
|
||||
]
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
|
||||
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
|
||||
{
|
||||
"compileOnSave": false,
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"experimentalDecorators": true,
|
||||
"importHelpers": true,
|
||||
"target": "ES2022",
|
||||
"module": "preserve"
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"enableI18nLegacyMessageIdFormat": false,
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
},
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
|
||||
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/spec",
|
||||
"types": [
|
||||
"vitest/globals"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.d.ts",
|
||||
"src/**/*.spec.ts"
|
||||
]
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
plugins {
|
||||
id "base"
|
||||
}
|
||||
|
||||
tasks.register("dockerBuild", Exec) {
|
||||
commandLine "docker", "build", "-t", "task2-fastapi", "."
|
||||
}
|
||||
|
||||
tasks.register("dockerRemove", Exec) {
|
||||
ignoreExitValue = true
|
||||
commandLine "docker", "rm", "-f", "task2-fastapi-container"
|
||||
}
|
||||
|
||||
tasks.register("dockerRun", Exec) {
|
||||
dependsOn "dockerBuild", "dockerRemove"
|
||||
commandLine "docker", "run", "-d", "--rm", "--name", "task2-fastapi-container", "-p", "8000:8000", "task2-fastapi"
|
||||
}
|
||||
|
||||
tasks.register("dockerStop", Exec) {
|
||||
commandLine "docker", "stop", "task2-fastapi-container"
|
||||
}
|
||||
|
||||
tasks.register("testAPI", Exec) {
|
||||
commandLine "python", "-m", "pytest", "-v"
|
||||
}
|
||||
|
||||
tasks.named("build") {
|
||||
dependsOn "testAPI", "dockerBuild"
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
services:
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
DATABASE_URL: sqlite:////app/data/users.db
|
||||
volumes:
|
||||
- users_data:/app/data
|
||||
ports:
|
||||
- "8000:8000"
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/users').read()"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./TASK4
|
||||
dockerfile: Dockerfile
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "4200:80"
|
||||
|
||||
volumes:
|
||||
users_data:
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
name: aiis
|
||||
channels:
|
||||
- defaults
|
||||
dependencies:
|
||||
- bzip2=1.0.8=h80987f9_6
|
||||
- ca-certificates=2026.3.19=hca03da5_0
|
||||
- libcxx=22.1.2=hf894667_0
|
||||
- libexpat=2.7.5=h50f4ffc_0
|
||||
- libffi=3.4.4=hca03da5_1
|
||||
- libzlib=1.3.1=h5f15de7_0
|
||||
- ncurses=6.5=hee39554_0
|
||||
- openssl=3.5.6=ha0b305a_0
|
||||
- packaging=26.0=py310hca03da5_0
|
||||
- pip=26.0.1=pyhc872135_1
|
||||
- python=3.10.20=h4f1bc5c_0
|
||||
- readline=8.3=h0b18652_0
|
||||
- setuptools=82.0.1=py310hca03da5_0
|
||||
- sqlite=3.51.2=h67002bf_0
|
||||
- tk=8.6.15=hcd8a7d5_0
|
||||
- wheel=0.46.3=py310hca03da5_0
|
||||
- xz=5.8.2=h8bbcb1d_0
|
||||
- zlib=1.3.1=h5f15de7_0
|
||||
- pip:
|
||||
- anyio==4.13.0
|
||||
- appnope==0.1.4
|
||||
- argon2-cffi==25.1.0
|
||||
- argon2-cffi-bindings==25.1.0
|
||||
- arrow==1.4.0
|
||||
- asttokens==3.0.1
|
||||
- async-lru==2.3.0
|
||||
- attrs==26.1.0
|
||||
- babel==2.18.0
|
||||
- beautifulsoup4==4.14.3
|
||||
- bleach==6.3.0
|
||||
- certifi==2026.2.25
|
||||
- cffi==2.0.0
|
||||
- charset-normalizer==3.4.7
|
||||
- comm==0.2.3
|
||||
- debugpy==1.8.20
|
||||
- decorator==5.2.1
|
||||
- defusedxml==0.7.1
|
||||
- exceptiongroup==1.3.1
|
||||
- executing==2.2.1
|
||||
- fastjsonschema==2.21.2
|
||||
- fqdn==1.5.1
|
||||
- h11==0.16.0
|
||||
- httpcore==1.0.9
|
||||
- httpx==0.28.1
|
||||
- idna==3.11
|
||||
- ipykernel==7.2.0
|
||||
- ipython==8.39.0
|
||||
- ipywidgets==8.1.8
|
||||
- isoduration==20.11.0
|
||||
- jedi==0.19.2
|
||||
- jinja2==3.1.6
|
||||
- json5==0.14.0
|
||||
- jsonpointer==3.1.1
|
||||
- jsonschema==4.26.0
|
||||
- jsonschema-specifications==2025.9.1
|
||||
- jupyter==1.1.1
|
||||
- jupyter-client==8.8.0
|
||||
- jupyter-console==6.6.3
|
||||
- jupyter-core==5.9.1
|
||||
- jupyter-events==0.12.0
|
||||
- jupyter-lsp==2.3.1
|
||||
- jupyter-server==2.17.0
|
||||
- jupyter-server-terminals==0.5.4
|
||||
- jupyterlab==4.5.6
|
||||
- jupyterlab-pygments==0.3.0
|
||||
- jupyterlab-server==2.28.0
|
||||
- jupyterlab-widgets==3.0.16
|
||||
- lark==1.3.1
|
||||
- markupsafe==3.0.3
|
||||
- matplotlib-inline==0.2.1
|
||||
- mistune==3.2.0
|
||||
- nbclient==0.10.4
|
||||
- nbconvert==7.17.1
|
||||
- nbformat==5.10.4
|
||||
- nest-asyncio==1.6.0
|
||||
- notebook==7.5.5
|
||||
- notebook-shim==0.2.4
|
||||
- overrides==7.7.0
|
||||
- pandocfilters==1.5.1
|
||||
- parso==0.8.6
|
||||
- pexpect==4.9.0
|
||||
- platformdirs==4.9.6
|
||||
- prometheus-client==0.25.0
|
||||
- prompt-toolkit==3.0.52
|
||||
- psutil==7.2.2
|
||||
- ptyprocess==0.7.0
|
||||
- pure-eval==0.2.3
|
||||
- pycparser==3.0
|
||||
- pygments==2.20.0
|
||||
- python-dateutil==2.9.0.post0
|
||||
- python-json-logger==4.1.0
|
||||
- pyyaml==6.0.3
|
||||
- pyzmq==27.1.0
|
||||
- referencing==0.37.0
|
||||
- requests==2.33.1
|
||||
- rfc3339-validator==0.1.4
|
||||
- rfc3986-validator==0.1.1
|
||||
- rfc3987-syntax==1.1.0
|
||||
- rpds-py==0.30.0
|
||||
- send2trash==2.1.0
|
||||
- six==1.17.0
|
||||
- soupsieve==2.8.3
|
||||
- stack-data==0.6.3
|
||||
- terminado==0.18.1
|
||||
- tinycss2==1.4.0
|
||||
- tomli==2.4.1
|
||||
- tornado==6.5.5
|
||||
- traitlets==5.14.3
|
||||
- typing-extensions==4.15.0
|
||||
- tzdata==2026.1
|
||||
- uri-template==1.3.0
|
||||
- urllib3==2.6.3
|
||||
- wcwidth==0.6.0
|
||||
- webcolors==25.10.0
|
||||
- webencodings==0.5.1
|
||||
- websocket-client==1.9.0
|
||||
- widgetsnbextension==4.0.15
|
||||
prefix: /opt/anaconda3/envs/aiis
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"id": "1b656a67-e6db-4b6e-82f5-b7183ff40f26",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Hello from Jupyter\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(\"Hello from Jupyter\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"id": "f32ff3e7-5925-4cfb-b88c-7415df95301b",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"sara\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(\"sara\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d1e4e2fb-7874-4837-b3d6-59a6ef1e89a2",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python (aiis)",
|
||||
"language": "python",
|
||||
"name": "aiis"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.20"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
import os
|
||||
|
||||
from fastapi import FastAPI, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import create_engine, Column, Integer, String
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base, Session
|
||||
|
||||
app = FastAPI(title="Task 2 CRUD API")
|
||||
|
||||
# Database setup
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./users.db")
|
||||
|
||||
connect_args = {}
|
||||
if DATABASE_URL.startswith("sqlite"):
|
||||
connect_args = {"check_same_thread": False}
|
||||
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
connect_args=connect_args
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(bind=engine)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
# Database model
|
||||
class UserDB(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String)
|
||||
age = Column(Integer)
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Pydantic model
|
||||
class User(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=50)
|
||||
age: int = Field(..., gt=0)
|
||||
|
||||
|
||||
# Database session
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
yield db
|
||||
db.close()
|
||||
|
||||
# CREATE
|
||||
@app.post("/users")
|
||||
def create_user(user: User, db: Session = Depends(get_db)):
|
||||
new_user = UserDB(name=user.name, age=user.age)
|
||||
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
db.refresh(new_user)
|
||||
|
||||
return new_user
|
||||
|
||||
|
||||
# READ ALL
|
||||
@app.get("/users")
|
||||
def get_users(db: Session = Depends(get_db)):
|
||||
return db.query(UserDB).all()
|
||||
|
||||
# READ ONE
|
||||
@app.get("/users/{user_id}")
|
||||
def get_user(user_id: int, db: Session = Depends(get_db)):
|
||||
user = db.query(UserDB).filter(UserDB.id == user_id).first()
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
return user
|
||||
|
||||
# UPDATE
|
||||
@app.put("/users/{user_id}")
|
||||
def update_user(user_id: int, updated_user: User, db: Session = Depends(get_db)):
|
||||
user = db.query(UserDB).filter(UserDB.id == user_id).first()
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
user.name = updated_user.name
|
||||
user.age = updated_user.age
|
||||
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
return user
|
||||
|
||||
# DELETE
|
||||
@app.delete("/users/{user_id}")
|
||||
def delete_user(user_id: int, db: Session = Depends(get_db)):
|
||||
user = db.query(UserDB).filter(UserDB.id == user_id).first()
|
||||
|
||||
if user is None:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
return {"message": "User deleted"}
|
||||
@@ -1,3 +0,0 @@
|
||||
fastapi
|
||||
uvicorn[standard]
|
||||
sqlalchemy
|
||||
@@ -1,34 +0,0 @@
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_create_user():
|
||||
response = client.post(
|
||||
"/users",
|
||||
json={"name": "Test", "age": 20}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_get_users():
|
||||
response = client.get("/users")
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_update_and_delete():
|
||||
# create
|
||||
res = client.post("/users", json={"name": "Sara", "age": 30})
|
||||
user_id = res.json()["id"]
|
||||
|
||||
# update
|
||||
res = client.put(
|
||||
f"/users/{user_id}",
|
||||
json={"name": "Updated", "age": 31}
|
||||
)
|
||||
assert res.status_code == 200
|
||||
|
||||
# delete
|
||||
res = client.delete(f"/users/{user_id}")
|
||||
assert res.status_code == 200
|
||||
@@ -0,0 +1,54 @@
|
||||
## Demo 1: Spam vs. Ham Detector
|
||||
|
||||
- It uses Hugging Face `pipeline("text-classification")`.
|
||||
- It uses the **Enron Spam Dataset Preprocessed** (`willyard/spam-email-dataset` on Kaggle).
|
||||
- It uses **email subject lines** (`Subject`) as input text, matching the seminar task.
|
||||
- It uses `Spam/Ham` as the expected label from the dataset.
|
||||
- Main file: `demo1.py`.
|
||||
- Notebook files: `demo1_jupyter.ipynb`.
|
||||
|
||||
How results are checked:
|
||||
|
||||
- The script prints simple spam/safe predictions for clear email subject examples.
|
||||
- The output shows expected label, raw model label, mapped prediction, confidence, and correctness.
|
||||
- The model is evaluated on a random subset of real dataset samples.
|
||||
- The evaluation compares the expected labels from the dataset with the predicted labels from the model.
|
||||
|
||||
Limitations:
|
||||
|
||||
- A pretrained model may not perfectly match this specific dataset.
|
||||
- Some models output generic labels (for example `LABEL_0`, `LABEL_1`), so label mapping must be checked.
|
||||
|
||||
## Demo 2: Automated Support Ticket Router
|
||||
|
||||
- Classifies incoming customer messages into `Billing`, `Technical Support`, or `Shipping`.
|
||||
- Uses Hugging Face `pipeline("zero-shot-classification")` with `facebook/bart-large-mnli`.
|
||||
- Uses a Kaggle dataset and maps original ticket types into those three seminar routing buckets.
|
||||
- Uses `Ticket Subject` as input text for classification.
|
||||
- Prints expected label, predicted label, confidence score, and correctness.
|
||||
- Main file: `demo2.py`.
|
||||
- Notebook files: `demo2_jupyter.ipynb`.
|
||||
|
||||
Why zero-shot classification is used:
|
||||
- Labels are defined at prediction time.
|
||||
- No task-specific model retraining is required.
|
||||
- Useful when labeled training data is small or not available yet.
|
||||
- It directly uses the `ZeroShotClassificationPipeline` idea from Hugging Face.
|
||||
- It demonstrates custom labels during inference, which is the key concept of zero-shot classification.
|
||||
|
||||
Candidate labels:
|
||||
- `Billing`
|
||||
- `Technical Support`
|
||||
- `Shipping`
|
||||
|
||||
How results are checked:
|
||||
|
||||
- The original Kaggle ticket types are mapped into the three demo labels.
|
||||
- The model predictions are compared with the expected labels.
|
||||
- The evaluation reports accuracy, classification report, and confusion matrix.
|
||||
|
||||
How to run:
|
||||
```bash
|
||||
conda activate aiis
|
||||
python demo1.py
|
||||
python demo2.py
|
||||
@@ -0,0 +1,265 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
import pandas as pd
|
||||
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
|
||||
from transformers import pipeline
|
||||
|
||||
|
||||
DATASET_FILE = Path(__file__).resolve().parent / "enron_spam_data.csv"
|
||||
MODEL_ID = "mrm8488/bert-tiny-finetuned-enron-spam-detection"
|
||||
REQUIRED_COLUMNS = ["Subject", "Spam/Ham"]
|
||||
|
||||
RANDOM_SEED = 42
|
||||
MAX_EVAL_SAMPLES = 400
|
||||
MAX_CALIBRATION_SAMPLES = 200
|
||||
|
||||
|
||||
def print_section(title: str) -> None:
|
||||
print("\n" + "=" * 90)
|
||||
print(title)
|
||||
print("=" * 90)
|
||||
|
||||
|
||||
def load_dataset(file_path: Path) -> pd.DataFrame:
|
||||
if not file_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Dataset file not found: {file_path.name}. "
|
||||
"Run this script from the project folder."
|
||||
)
|
||||
|
||||
df = pd.read_csv(file_path)
|
||||
|
||||
missing_columns = [column for column in REQUIRED_COLUMNS if column not in df.columns]
|
||||
if missing_columns:
|
||||
raise ValueError(
|
||||
"Dataset is missing required columns: "
|
||||
f"{missing_columns}. Required: {REQUIRED_COLUMNS}"
|
||||
)
|
||||
|
||||
return df
|
||||
|
||||
|
||||
def print_dataset_preview(df: pd.DataFrame) -> None:
|
||||
print_section("Dataset Preview")
|
||||
print(f"File: {DATASET_FILE.name}")
|
||||
print(f"Shape: {df.shape}")
|
||||
print(f"Columns: {list(df.columns)}")
|
||||
|
||||
preview_df = df[REQUIRED_COLUMNS].head(5).copy()
|
||||
preview_df["Subject"] = preview_df["Subject"].astype(str).str.slice(0, 90)
|
||||
|
||||
print("\nFirst rows (Subject shortened to keep output readable):")
|
||||
print(preview_df.to_string(index=False))
|
||||
|
||||
print("\nOriginal label distribution (including missing values):")
|
||||
print(df["Spam/Ham"].value_counts(dropna=False).to_string())
|
||||
|
||||
|
||||
def prepare_dataset(df: pd.DataFrame) -> pd.DataFrame:
|
||||
working_df = df[REQUIRED_COLUMNS].copy()
|
||||
rows_before = len(working_df)
|
||||
|
||||
working_df["text"] = working_df["Subject"].fillna("").astype(str).str.strip()
|
||||
working_df["expected_label"] = (
|
||||
working_df["Spam/Ham"].fillna("").astype(str).str.lower().str.strip()
|
||||
)
|
||||
|
||||
# Keep only valid binary labels
|
||||
working_df = working_df[working_df["expected_label"].isin(["ham", "spam"])].copy()
|
||||
working_df = working_df[working_df["text"] != ""].copy()
|
||||
|
||||
rows_after = len(working_df)
|
||||
|
||||
print_section("Dataset Cleaning")
|
||||
print(f"Rows before cleaning: {rows_before}")
|
||||
print(f"Rows after cleaning: {rows_after}")
|
||||
print(f"Rows removed: {rows_before - rows_after}")
|
||||
print("\nClean label distribution:")
|
||||
print(working_df["expected_label"].value_counts().to_string())
|
||||
|
||||
if working_df.empty:
|
||||
raise ValueError("No usable rows left after cleaning. Check text/label columns.")
|
||||
|
||||
return working_df[["text", "expected_label"]].reset_index(drop=True)
|
||||
|
||||
|
||||
def select_eval_subset(clean_df: pd.DataFrame) -> pd.DataFrame:
|
||||
if len(clean_df) <= MAX_EVAL_SAMPLES:
|
||||
print("\nEvaluation uses all cleaned rows.")
|
||||
return clean_df.copy()
|
||||
|
||||
sampled_df = clean_df.sample(n=MAX_EVAL_SAMPLES, random_state=RANDOM_SEED)
|
||||
|
||||
print(
|
||||
"\nEvaluation uses a random subset for faster live demo: "
|
||||
f"{len(sampled_df)} of {len(clean_df)} cleaned rows "
|
||||
f"(random_seed={RANDOM_SEED})."
|
||||
)
|
||||
|
||||
return sampled_df.reset_index(drop=True)
|
||||
|
||||
|
||||
def create_classifier(model_id: str):
|
||||
try:
|
||||
return pipeline("text-classification", model=model_id, tokenizer=model_id)
|
||||
except Exception as error:
|
||||
raise RuntimeError(f"Could not load model '{model_id}': {error}") from error
|
||||
|
||||
|
||||
def fallback_label(raw_label: str) -> str:
|
||||
label = raw_label.lower()
|
||||
|
||||
if "spam" in label or label.endswith("1"):
|
||||
return "spam"
|
||||
return "ham"
|
||||
|
||||
|
||||
def infer_label_mapping(classifier, calibration_df: pd.DataFrame) -> Dict[str, str]:
|
||||
outputs = classifier(calibration_df["text"].tolist(), truncation=True, batch_size=32)
|
||||
|
||||
votes: Dict[str, Dict[str, int]] = {}
|
||||
for output, expected_label in zip(outputs, calibration_df["expected_label"]):
|
||||
raw_label = output["label"]
|
||||
votes.setdefault(raw_label, {"ham": 0, "spam": 0})
|
||||
votes[raw_label][expected_label] += 1
|
||||
|
||||
mapping: Dict[str, str] = {}
|
||||
for raw_label, counts in votes.items():
|
||||
mapping[raw_label] = "spam" if counts["spam"] >= counts["ham"] else "ham"
|
||||
|
||||
# Safety fallback if a new raw label appears outside calibration sample.
|
||||
for raw_label in votes:
|
||||
mapping.setdefault(raw_label, fallback_label(raw_label))
|
||||
|
||||
return mapping
|
||||
|
||||
|
||||
def predict_texts(classifier, texts: List[str], label_mapping: Dict[str, str]) -> List[Dict[str, float | str]]:
|
||||
outputs = classifier(texts, truncation=True, batch_size=32)
|
||||
|
||||
predictions: List[Dict[str, float | str]] = []
|
||||
for text, output in zip(texts, outputs):
|
||||
raw_label = output["label"]
|
||||
mapped_label = label_mapping.get(raw_label, fallback_label(raw_label))
|
||||
|
||||
predictions.append(
|
||||
{
|
||||
"text": text,
|
||||
"raw_label": raw_label,
|
||||
"mapped_label": mapped_label,
|
||||
"confidence": float(output["score"]),
|
||||
}
|
||||
)
|
||||
|
||||
return predictions
|
||||
|
||||
|
||||
def run_demo_predictions(classifier, label_mapping: Dict[str, str]) -> None:
|
||||
examples = pd.DataFrame(
|
||||
[
|
||||
("free money offer click now", "spam"),
|
||||
("claim your lottery prize today", "spam"),
|
||||
("cheap meds available now", "spam"),
|
||||
("project meeting agenda for tomorrow", "ham"),
|
||||
("please review the budget report", "ham"),
|
||||
("team lunch moved to 1 pm", "ham"),
|
||||
],
|
||||
columns=["text", "expected_label"],
|
||||
)
|
||||
|
||||
results = predict_texts(classifier, examples["text"].tolist(), label_mapping)
|
||||
|
||||
print_section("Demo Predictions")
|
||||
for row, prediction in zip(examples.itertuples(index=False), results):
|
||||
is_correct = prediction["mapped_label"] == row.expected_label
|
||||
|
||||
print(f"\nInput text: {row.text}")
|
||||
print(f"Expected label: {row.expected_label}")
|
||||
print(f"Raw model label: {prediction['raw_label']}")
|
||||
print(f"Mapped label: {prediction['mapped_label']}")
|
||||
print(f"Confidence score: {prediction['confidence']:.4f}")
|
||||
print(f"Correct: {is_correct}")
|
||||
|
||||
|
||||
def run_evaluation(classifier, eval_df: pd.DataFrame, label_mapping: Dict[str, str]) -> None:
|
||||
predictions = predict_texts(classifier, eval_df["text"].tolist(), label_mapping)
|
||||
|
||||
y_true = eval_df["expected_label"].tolist()
|
||||
y_pred = [prediction["mapped_label"] for prediction in predictions]
|
||||
|
||||
print_section("Evaluation Results")
|
||||
print(f"Accuracy: {accuracy_score(y_true, y_pred):.4f}\n")
|
||||
|
||||
print("Classification report:")
|
||||
print(
|
||||
classification_report(
|
||||
y_true,
|
||||
y_pred,
|
||||
labels=["ham", "spam"],
|
||||
zero_division=0,
|
||||
)
|
||||
)
|
||||
|
||||
confusion = confusion_matrix(y_true, y_pred, labels=["ham", "spam"])
|
||||
confusion_df = pd.DataFrame(
|
||||
confusion,
|
||||
index=["true_ham", "true_spam"],
|
||||
columns=["pred_ham", "pred_spam"],
|
||||
)
|
||||
|
||||
print("Confusion matrix:")
|
||||
print(confusion_df.to_string())
|
||||
|
||||
|
||||
def print_limitations() -> None:
|
||||
print_section("Limitations")
|
||||
print("- This is a pretrained model demo and not trained in this script.")
|
||||
print("- Accuracy may change on other email domains or writing styles.")
|
||||
print("- For speed, evaluation may run on a subset of the dataset.")
|
||||
print("- Real production systems need monitoring, retraining, and safety checks.")
|
||||
|
||||
|
||||
def run_demo() -> None:
|
||||
print_section("DEMO 1: Spam vs. Ham Detector")
|
||||
print("Method: Hugging Face pipeline('text-classification')")
|
||||
print(f"Model: {MODEL_ID}")
|
||||
print(f"Random seed: {RANDOM_SEED}")
|
||||
|
||||
try:
|
||||
dataset_df = load_dataset(DATASET_FILE)
|
||||
print_dataset_preview(dataset_df)
|
||||
clean_df = prepare_dataset(dataset_df)
|
||||
eval_df = select_eval_subset(clean_df)
|
||||
except (FileNotFoundError, ValueError, pd.errors.ParserError) as error:
|
||||
print_section("Error")
|
||||
print(error)
|
||||
return
|
||||
|
||||
print_section("Model Information")
|
||||
print(f"Loading model: {MODEL_ID}")
|
||||
|
||||
try:
|
||||
classifier = create_classifier(MODEL_ID)
|
||||
except RuntimeError as error:
|
||||
print_section("Error")
|
||||
print(error)
|
||||
return
|
||||
|
||||
calibration_size = min(MAX_CALIBRATION_SAMPLES, len(eval_df))
|
||||
calibration_df = eval_df.sample(n=calibration_size, random_state=RANDOM_SEED)
|
||||
label_mapping = infer_label_mapping(classifier, calibration_df)
|
||||
|
||||
print("Model label mapping:")
|
||||
for raw_label, mapped_label in sorted(label_mapping.items()):
|
||||
print(f"- {raw_label} -> {mapped_label}")
|
||||
|
||||
run_demo_predictions(classifier, label_mapping)
|
||||
run_evaluation(classifier, eval_df, label_mapping)
|
||||
print_limitations()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_demo()
|
||||
@@ -0,0 +1,538 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"id": "7f9c5c12",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"pandas loaded\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import pandas as pd\n",
|
||||
"print(\"pandas loaded\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"id": "7796a7f6",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"basic imports loaded\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from pathlib import Path\n",
|
||||
"from typing import Dict, List\n",
|
||||
"\n",
|
||||
"from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
|
||||
"\n",
|
||||
"print(\"basic imports loaded\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"id": "d02a1147",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"transformers loaded\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from transformers import pipeline\n",
|
||||
"\n",
|
||||
"print(\"transformers loaded\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"id": "e0db2d53",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Dataset shape: (33716, 5)\n",
|
||||
"Columns: ['Message ID', 'Subject', 'Message', 'Spam/Ham', 'Date']\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<div>\n",
|
||||
"<style scoped>\n",
|
||||
" .dataframe tbody tr th:only-of-type {\n",
|
||||
" vertical-align: middle;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe tbody tr th {\n",
|
||||
" vertical-align: top;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe thead th {\n",
|
||||
" text-align: right;\n",
|
||||
" }\n",
|
||||
"</style>\n",
|
||||
"<table border=\"1\" class=\"dataframe\">\n",
|
||||
" <thead>\n",
|
||||
" <tr style=\"text-align: right;\">\n",
|
||||
" <th></th>\n",
|
||||
" <th>Subject</th>\n",
|
||||
" <th>Spam/Ham</th>\n",
|
||||
" </tr>\n",
|
||||
" </thead>\n",
|
||||
" <tbody>\n",
|
||||
" <tr>\n",
|
||||
" <th>0</th>\n",
|
||||
" <td>christmas tree farm pictures</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>1</th>\n",
|
||||
" <td>vastar resources , inc .</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>2</th>\n",
|
||||
" <td>calpine daily gas nomination</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>3</th>\n",
|
||||
" <td>re : issue</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>4</th>\n",
|
||||
" <td>meter 7268 nov allocation</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" </tbody>\n",
|
||||
"</table>\n",
|
||||
"</div>"
|
||||
],
|
||||
"text/plain": [
|
||||
" Subject Spam/Ham\n",
|
||||
"0 christmas tree farm pictures ham\n",
|
||||
"1 vastar resources , inc . ham\n",
|
||||
"2 calpine daily gas nomination ham\n",
|
||||
"3 re : issue ham\n",
|
||||
"4 meter 7268 nov allocation ham"
|
||||
]
|
||||
},
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"#Dataset\n",
|
||||
"DATASET_FILE = Path(\"enron_spam_data.csv\")\n",
|
||||
"\n",
|
||||
"df = pd.read_csv(DATASET_FILE)\n",
|
||||
"\n",
|
||||
"print(\"Dataset shape:\", df.shape)\n",
|
||||
"print(\"Columns:\", list(df.columns))\n",
|
||||
"\n",
|
||||
"df[[\"Subject\", \"Spam/Ham\"]].head()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"id": "379fcc5f",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Clean dataset shape: (33427, 2)\n",
|
||||
"expected_label\n",
|
||||
"spam 16882\n",
|
||||
"ham 16545\n",
|
||||
"Name: count, dtype: int64\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<div>\n",
|
||||
"<style scoped>\n",
|
||||
" .dataframe tbody tr th:only-of-type {\n",
|
||||
" vertical-align: middle;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe tbody tr th {\n",
|
||||
" vertical-align: top;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe thead th {\n",
|
||||
" text-align: right;\n",
|
||||
" }\n",
|
||||
"</style>\n",
|
||||
"<table border=\"1\" class=\"dataframe\">\n",
|
||||
" <thead>\n",
|
||||
" <tr style=\"text-align: right;\">\n",
|
||||
" <th></th>\n",
|
||||
" <th>text</th>\n",
|
||||
" <th>expected_label</th>\n",
|
||||
" </tr>\n",
|
||||
" </thead>\n",
|
||||
" <tbody>\n",
|
||||
" <tr>\n",
|
||||
" <th>0</th>\n",
|
||||
" <td>christmas tree farm pictures</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>1</th>\n",
|
||||
" <td>vastar resources , inc .</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>2</th>\n",
|
||||
" <td>calpine daily gas nomination</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>3</th>\n",
|
||||
" <td>re : issue</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>4</th>\n",
|
||||
" <td>meter 7268 nov allocation</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" </tbody>\n",
|
||||
"</table>\n",
|
||||
"</div>"
|
||||
],
|
||||
"text/plain": [
|
||||
" text expected_label\n",
|
||||
"0 christmas tree farm pictures ham\n",
|
||||
"1 vastar resources , inc . ham\n",
|
||||
"2 calpine daily gas nomination ham\n",
|
||||
"3 re : issue ham\n",
|
||||
"4 meter 7268 nov allocation ham"
|
||||
]
|
||||
},
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"#clean Data\n",
|
||||
"clean_df = df[[\"Subject\", \"Spam/Ham\"]].copy()\n",
|
||||
"\n",
|
||||
"clean_df[\"text\"] = clean_df[\"Subject\"].fillna(\"\").astype(str).str.strip()\n",
|
||||
"clean_df[\"expected_label\"] = (\n",
|
||||
" clean_df[\"Spam/Ham\"].fillna(\"\").astype(str).str.lower().str.strip()\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"clean_df = clean_df[clean_df[\"expected_label\"].isin([\"ham\", \"spam\"])]\n",
|
||||
"clean_df = clean_df[clean_df[\"text\"] != \"\"]\n",
|
||||
"clean_df = clean_df[[\"text\", \"expected_label\"]].reset_index(drop=True)\n",
|
||||
"\n",
|
||||
"print(\"Clean dataset shape:\", clean_df.shape)\n",
|
||||
"print(clean_df[\"expected_label\"].value_counts())\n",
|
||||
"\n",
|
||||
"clean_df.head()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"id": "a8652e32",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Evaluation samples: 400\n",
|
||||
"expected_label\n",
|
||||
"spam 207\n",
|
||||
"ham 193\n",
|
||||
"Name: count, dtype: int64\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<div>\n",
|
||||
"<style scoped>\n",
|
||||
" .dataframe tbody tr th:only-of-type {\n",
|
||||
" vertical-align: middle;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe tbody tr th {\n",
|
||||
" vertical-align: top;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe thead th {\n",
|
||||
" text-align: right;\n",
|
||||
" }\n",
|
||||
"</style>\n",
|
||||
"<table border=\"1\" class=\"dataframe\">\n",
|
||||
" <thead>\n",
|
||||
" <tr style=\"text-align: right;\">\n",
|
||||
" <th></th>\n",
|
||||
" <th>text</th>\n",
|
||||
" <th>expected_label</th>\n",
|
||||
" </tr>\n",
|
||||
" </thead>\n",
|
||||
" <tbody>\n",
|
||||
" <tr>\n",
|
||||
" <th>0</th>\n",
|
||||
" <td>transportation contract # 25374</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>1</th>\n",
|
||||
" <td>re : lance cunningham</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>2</th>\n",
|
||||
" <td>erd review</td>\n",
|
||||
" <td>ham</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>3</th>\n",
|
||||
" <td>paliourg</td>\n",
|
||||
" <td>spam</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>4</th>\n",
|
||||
" <td>listas free ! ! ! hoy @ superclub presents fee...</td>\n",
|
||||
" <td>spam</td>\n",
|
||||
" </tr>\n",
|
||||
" </tbody>\n",
|
||||
"</table>\n",
|
||||
"</div>"
|
||||
],
|
||||
"text/plain": [
|
||||
" text expected_label\n",
|
||||
"0 transportation contract # 25374 ham\n",
|
||||
"1 re : lance cunningham ham\n",
|
||||
"2 erd review ham\n",
|
||||
"3 paliourg spam\n",
|
||||
"4 listas free ! ! ! hoy @ superclub presents fee... spam"
|
||||
]
|
||||
},
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"#Sample\n",
|
||||
"eval_df = clean_df.sample(n=400, random_state=42).reset_index(drop=True)\n",
|
||||
"\n",
|
||||
"print(\"Evaluation samples:\", len(eval_df))\n",
|
||||
"print(eval_df[\"expected_label\"].value_counts())\n",
|
||||
"\n",
|
||||
"eval_df.head()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"id": "0816d4c6",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"application/vnd.jupyter.widget-view+json": {
|
||||
"model_id": "2c9b56f3d9f543a8b3db875b060926f1",
|
||||
"version_major": 2,
|
||||
"version_minor": 0
|
||||
},
|
||||
"text/plain": [
|
||||
"Loading weights: 0%| | 0/41 [00:00<?, ?it/s]"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Model loaded\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"MODEL_ID = \"mrm8488/bert-tiny-finetuned-enron-spam-detection\"\n",
|
||||
"\n",
|
||||
"classifier = pipeline(\n",
|
||||
" \"text-classification\",\n",
|
||||
" model=MODEL_ID,\n",
|
||||
" tokenizer=MODEL_ID\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"print(\"Model loaded\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"id": "14d554fe",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"[{'label': 'LABEL_1', 'score': 0.9981743097305298}]"
|
||||
]
|
||||
},
|
||||
"execution_count": 8,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"classifier(\"free money offer click now\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"id": "3f171e7c",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Predictions finished\n",
|
||||
"Number of true labels: 400\n",
|
||||
"Number of predictions: 400\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"#Label mapping and prediction\n",
|
||||
"def map_label(raw_label):\n",
|
||||
" raw_label = raw_label.lower()\n",
|
||||
" if \"spam\" in raw_label or raw_label.endswith(\"1\"):\n",
|
||||
" return \"spam\"\n",
|
||||
" return \"ham\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"outputs = classifier(eval_df[\"text\"].tolist(), truncation=True, batch_size=32)\n",
|
||||
"\n",
|
||||
"y_true = eval_df[\"expected_label\"].tolist()\n",
|
||||
"y_pred = [map_label(output[\"label\"]) for output in outputs]\n",
|
||||
"\n",
|
||||
"print(\"Predictions finished\")\n",
|
||||
"print(\"Number of true labels:\", len(y_true))\n",
|
||||
"print(\"Number of predictions:\", len(y_pred))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"id": "871862c8",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Accuracy: 0.8225\n",
|
||||
"Correct predictions: 329 out of 400\n",
|
||||
"\n",
|
||||
"Classification report:\n",
|
||||
" precision recall f1-score support\n",
|
||||
"\n",
|
||||
" ham 0.92 0.69 0.79 193\n",
|
||||
" spam 0.77 0.95 0.85 207\n",
|
||||
"\n",
|
||||
" accuracy 0.82 400\n",
|
||||
" macro avg 0.84 0.82 0.82 400\n",
|
||||
"weighted avg 0.84 0.82 0.82 400\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Confusion matrix:\n",
|
||||
" pred_ham pred_spam\n",
|
||||
"true_ham 133 60\n",
|
||||
"true_spam 11 196\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"#Evaluation\n",
|
||||
"accuracy = accuracy_score(y_true, y_pred)\n",
|
||||
"\n",
|
||||
"print(f\"Accuracy: {accuracy:.4f}\")\n",
|
||||
"print(f\"Correct predictions: {int(accuracy * len(y_true))} out of {len(y_true)}\")\n",
|
||||
"\n",
|
||||
"print(\"\\nClassification report:\")\n",
|
||||
"print(classification_report(y_true, y_pred, labels=[\"ham\", \"spam\"], zero_division=0))\n",
|
||||
"\n",
|
||||
"confusion = confusion_matrix(y_true, y_pred, labels=[\"ham\", \"spam\"])\n",
|
||||
"confusion_df = pd.DataFrame(\n",
|
||||
" confusion,\n",
|
||||
" index=[\"true_ham\", \"true_spam\"],\n",
|
||||
" columns=[\"pred_ham\", \"pred_spam\"],\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"print(\"\\nConfusion matrix:\")\n",
|
||||
"print(confusion_df)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python (aiis)",
|
||||
"language": "python",
|
||||
"name": "aiis"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.20"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
import pandas as pd
|
||||
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
|
||||
from transformers import pipeline
|
||||
|
||||
|
||||
DATASET_FILE = Path(__file__).resolve().parent / "customer_support_tickets.csv"
|
||||
KAGGLE_SOURCE = "suraj520/customer-support-ticket-dataset"
|
||||
MODEL_ID = "facebook/bart-large-mnli"
|
||||
|
||||
REQUIRED_COLUMNS = ["Ticket Type", "Ticket Subject", "Ticket Description"]
|
||||
TARGET_LABELS = ["Billing", "Technical Support", "Shipping"]
|
||||
|
||||
RANDOM_SEED = 42
|
||||
MAX_EVAL_SAMPLES = 120
|
||||
|
||||
|
||||
def print_section(title: str) -> None:
|
||||
print("\n" + "=" * 90)
|
||||
print(title)
|
||||
print("=" * 90)
|
||||
|
||||
|
||||
def load_dataset(file_path: Path) -> pd.DataFrame:
|
||||
if not file_path.exists():
|
||||
raise FileNotFoundError(f"Dataset file not found: {file_path.name}")
|
||||
|
||||
df = pd.read_csv(file_path)
|
||||
|
||||
missing_columns = [col for col in REQUIRED_COLUMNS if col not in df.columns]
|
||||
if missing_columns:
|
||||
raise ValueError(f"Missing required columns: {missing_columns}")
|
||||
|
||||
return df
|
||||
|
||||
|
||||
def print_dataset_preview(df: pd.DataFrame) -> None:
|
||||
print_section("Dataset Preview")
|
||||
print(f"File: {DATASET_FILE.name}")
|
||||
print(f"Source: Kaggle ({KAGGLE_SOURCE})")
|
||||
print(f"Shape: {df.shape}")
|
||||
print(f"Columns: {list(df.columns)}")
|
||||
|
||||
preview_df = df[REQUIRED_COLUMNS].head(5).copy()
|
||||
preview_df["Ticket Subject"] = preview_df["Ticket Subject"].astype(str).str.slice(0, 70)
|
||||
preview_df["Ticket Description"] = preview_df["Ticket Description"].astype(str).str.slice(0, 90)
|
||||
|
||||
print("\nFirst rows:")
|
||||
print(preview_df.to_string(index=False))
|
||||
|
||||
|
||||
def map_to_demo_label(ticket_type: str, subject: str, description: str) -> str | None:
|
||||
ticket_type_clean = ticket_type.strip().lower()
|
||||
subject_clean = subject.strip().lower()
|
||||
|
||||
shipping_keywords = ["delivery", "shipping", "shipment", "tracking", "track", "address"]
|
||||
billing_keywords = ["payment", "refund", "invoice", "billing", "charge", "cancellation"]
|
||||
technical_keywords = [
|
||||
"network",
|
||||
"software",
|
||||
"hardware",
|
||||
"installation",
|
||||
"setup",
|
||||
"display",
|
||||
"data loss",
|
||||
"peripheral",
|
||||
"account access",
|
||||
]
|
||||
|
||||
if any(keyword in subject_clean for keyword in shipping_keywords):
|
||||
return "Shipping"
|
||||
|
||||
if any(keyword in subject_clean for keyword in billing_keywords):
|
||||
return "Billing"
|
||||
|
||||
if ticket_type_clean in {"technical issue", "product inquiry"}:
|
||||
return "Technical Support"
|
||||
|
||||
if ticket_type_clean in {"billing inquiry", "refund request", "cancellation request"}:
|
||||
return "Billing"
|
||||
|
||||
if any(keyword in subject_clean for keyword in technical_keywords):
|
||||
return "Technical Support"
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def prepare_dataset(df: pd.DataFrame) -> pd.DataFrame:
|
||||
working_df = df[REQUIRED_COLUMNS].copy()
|
||||
rows_before = len(working_df)
|
||||
|
||||
working_df["Ticket Type"] = working_df["Ticket Type"].fillna("").astype(str).str.strip()
|
||||
working_df["Ticket Subject"] = working_df["Ticket Subject"].fillna("").astype(str).str.strip()
|
||||
working_df["Ticket Description"] = working_df["Ticket Description"].fillna("").astype(str).str.strip()
|
||||
|
||||
working_df["text"] = working_df["Ticket Subject"]
|
||||
|
||||
working_df["expected_label"] = working_df.apply(
|
||||
lambda row: map_to_demo_label(
|
||||
ticket_type=row["Ticket Type"],
|
||||
subject=row["Ticket Subject"],
|
||||
description=row["Ticket Description"],
|
||||
),
|
||||
axis=1,
|
||||
)
|
||||
|
||||
working_df = working_df[working_df["text"] != ""].copy()
|
||||
working_df = working_df[working_df["expected_label"].isin(TARGET_LABELS)].copy()
|
||||
|
||||
rows_after = len(working_df)
|
||||
|
||||
print_section("Dataset Cleaning")
|
||||
print(f"Rows before cleaning: {rows_before}")
|
||||
print(f"Rows after cleaning: {rows_after}")
|
||||
print(f"Rows removed: {rows_before - rows_after}")
|
||||
|
||||
print("\nOriginal Kaggle label distribution:")
|
||||
print(df["Ticket Type"].value_counts(dropna=False).to_string())
|
||||
|
||||
print("\nClean demo label distribution:")
|
||||
print(working_df["expected_label"].value_counts().to_string())
|
||||
|
||||
print(
|
||||
"\nNote: The original Kaggle labels are mapped into three demo routing labels: "
|
||||
"Billing, Technical Support, and Shipping."
|
||||
)
|
||||
print("Text used for classification: Ticket Subject.")
|
||||
|
||||
if working_df.empty:
|
||||
raise ValueError("No usable rows left after cleaning.")
|
||||
|
||||
return working_df[["text", "expected_label"]].reset_index(drop=True)
|
||||
|
||||
|
||||
def select_eval_subset(clean_df: pd.DataFrame) -> pd.DataFrame:
|
||||
if len(clean_df) <= MAX_EVAL_SAMPLES:
|
||||
print("\nEvaluation uses all cleaned rows.")
|
||||
return clean_df.copy()
|
||||
|
||||
sampled_df = clean_df.sample(n=MAX_EVAL_SAMPLES, random_state=RANDOM_SEED)
|
||||
|
||||
print(
|
||||
"\nEvaluation subset: "
|
||||
f"{len(sampled_df)} of {len(clean_df)} cleaned rows "
|
||||
f"(random_seed={RANDOM_SEED})"
|
||||
)
|
||||
|
||||
return sampled_df.reset_index(drop=True)
|
||||
|
||||
|
||||
def create_classifier(model_id: str):
|
||||
try:
|
||||
return pipeline("zero-shot-classification", model=model_id)
|
||||
except Exception as error:
|
||||
raise RuntimeError(f"Could not load model '{model_id}': {error}") from error
|
||||
|
||||
|
||||
def normalize_prediction_label(value: str) -> str:
|
||||
cleaned = value.strip().lower()
|
||||
|
||||
mapping = {
|
||||
"billing": "Billing",
|
||||
"technical support": "Technical Support",
|
||||
"shipping": "Shipping",
|
||||
}
|
||||
|
||||
return mapping.get(cleaned, value.strip())
|
||||
|
||||
|
||||
def predict_tickets(
|
||||
classifier,
|
||||
texts: List[str],
|
||||
candidate_labels: List[str],
|
||||
) -> List[Dict[str, float | str]]:
|
||||
predictions: List[Dict[str, float | str]] = []
|
||||
|
||||
for text in texts:
|
||||
output = classifier(text, candidate_labels)
|
||||
|
||||
raw_label = output["labels"][0]
|
||||
mapped_label = normalize_prediction_label(raw_label)
|
||||
|
||||
predictions.append(
|
||||
{
|
||||
"text": text,
|
||||
"raw_label": raw_label,
|
||||
"mapped_label": mapped_label,
|
||||
"confidence": float(output["scores"][0]),
|
||||
}
|
||||
)
|
||||
|
||||
return predictions
|
||||
|
||||
|
||||
def run_demo_predictions(
|
||||
classifier,
|
||||
eval_df: pd.DataFrame,
|
||||
candidate_labels: List[str],
|
||||
) -> None:
|
||||
demo_size = min(6, len(eval_df))
|
||||
demo_df = eval_df.sample(n=demo_size, random_state=RANDOM_SEED).reset_index(drop=True)
|
||||
|
||||
predictions = predict_tickets(
|
||||
classifier=classifier,
|
||||
texts=demo_df["text"].tolist(),
|
||||
candidate_labels=candidate_labels,
|
||||
)
|
||||
|
||||
print_section("Demo Predictions")
|
||||
|
||||
for row, prediction in zip(demo_df.itertuples(index=False), predictions):
|
||||
is_correct = prediction["mapped_label"] == row.expected_label
|
||||
|
||||
print(f"\nInput text: {row.text}")
|
||||
print(f"Expected label: {row.expected_label}")
|
||||
print(f"Predicted label: {prediction['mapped_label']}")
|
||||
print(f"Confidence: {prediction['confidence']:.4f}")
|
||||
print(f"Correct: {is_correct}")
|
||||
|
||||
|
||||
def run_evaluation(
|
||||
classifier,
|
||||
eval_df: pd.DataFrame,
|
||||
candidate_labels: List[str],
|
||||
) -> None:
|
||||
predictions = predict_tickets(
|
||||
classifier=classifier,
|
||||
texts=eval_df["text"].tolist(),
|
||||
candidate_labels=candidate_labels,
|
||||
)
|
||||
|
||||
y_true = eval_df["expected_label"].tolist()
|
||||
y_pred = [prediction["mapped_label"] for prediction in predictions]
|
||||
|
||||
print_section("Evaluation Results")
|
||||
print(f"Accuracy: {accuracy_score(y_true, y_pred):.4f}\n")
|
||||
|
||||
print("Classification report:")
|
||||
print(
|
||||
classification_report(
|
||||
y_true,
|
||||
y_pred,
|
||||
labels=candidate_labels,
|
||||
zero_division=0,
|
||||
)
|
||||
)
|
||||
|
||||
confusion = confusion_matrix(y_true, y_pred, labels=candidate_labels)
|
||||
|
||||
confusion_df = pd.DataFrame(
|
||||
confusion,
|
||||
index=[f"true_{label}" for label in candidate_labels],
|
||||
columns=[f"pred_{label}" for label in candidate_labels],
|
||||
)
|
||||
|
||||
print("Confusion matrix:")
|
||||
print(confusion_df.to_string())
|
||||
|
||||
|
||||
def print_limitations() -> None:
|
||||
print_section("Limitations")
|
||||
print("- Zero-shot classification is flexible, but less precise than fine-tuning.")
|
||||
print("- Candidate labels strongly influence the final prediction.")
|
||||
print("- The mapping from original Kaggle ticket types to demo labels is rule-based.")
|
||||
print("- The demo uses only ticket subjects; descriptions could provide more context.")
|
||||
|
||||
|
||||
def run_demo() -> None:
|
||||
print_section("DEMO 2: Automated Support Ticket Router")
|
||||
print("Method: Hugging Face pipeline('zero-shot-classification')")
|
||||
print(f"Model: {MODEL_ID}")
|
||||
print(f"Candidate labels: {TARGET_LABELS}")
|
||||
print(f"Random seed: {RANDOM_SEED}")
|
||||
|
||||
try:
|
||||
dataset_df = load_dataset(DATASET_FILE)
|
||||
print_dataset_preview(dataset_df)
|
||||
clean_df = prepare_dataset(dataset_df)
|
||||
eval_df = select_eval_subset(clean_df)
|
||||
|
||||
except (FileNotFoundError, ValueError, pd.errors.ParserError) as error:
|
||||
print_section("Error")
|
||||
print(error)
|
||||
return
|
||||
|
||||
print_section("Model Information")
|
||||
print(f"Loading model: {MODEL_ID}")
|
||||
|
||||
try:
|
||||
classifier = create_classifier(MODEL_ID)
|
||||
except RuntimeError as error:
|
||||
print_section("Error")
|
||||
print(error)
|
||||
return
|
||||
|
||||
run_demo_predictions(classifier, eval_df, TARGET_LABELS)
|
||||
run_evaluation(classifier, eval_df, TARGET_LABELS)
|
||||
print_limitations()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_demo()
|
||||
@@ -0,0 +1,790 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "cd994071",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Imports _Bib\n",
|
||||
"\n",
|
||||
"from pathlib import Path\n",
|
||||
"\n",
|
||||
"import pandas as pd\n",
|
||||
"from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
|
||||
"from transformers import pipeline\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"DATASET_FILE = Path(\"customer_support_tickets.csv\")\n",
|
||||
"MODEL_ID = \"facebook/bart-large-mnli\"\n",
|
||||
"\n",
|
||||
"REQUIRED_COLUMNS = [\"Ticket Type\", \"Ticket Subject\", \"Ticket Description\"]\n",
|
||||
"TARGET_LABELS = [\"Billing\", \"Technical Support\", \"Shipping\"]\n",
|
||||
"\n",
|
||||
"RANDOM_SEED = 42\n",
|
||||
"MAX_EVAL_SAMPLES = 120"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 19,
|
||||
"id": "6a064b29",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Dataset shape: (8469, 17)\n",
|
||||
"Columns: ['Ticket ID', 'Customer Name', 'Customer Email', 'Customer Age', 'Customer Gender', 'Product Purchased', 'Date of Purchase', 'Ticket Type', 'Ticket Subject', 'Ticket Description', 'Ticket Status', 'Resolution', 'Ticket Priority', 'Ticket Channel', 'First Response Time', 'Time to Resolution', 'Customer Satisfaction Rating']\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Load dataset\n",
|
||||
"\n",
|
||||
"df = pd.read_csv(DATASET_FILE)\n",
|
||||
"\n",
|
||||
"print(\"Dataset shape:\", df.shape)\n",
|
||||
"print(\"Columns:\", list(df.columns))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 20,
|
||||
"id": "659655fb",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<div>\n",
|
||||
"<style scoped>\n",
|
||||
" .dataframe tbody tr th:only-of-type {\n",
|
||||
" vertical-align: middle;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe tbody tr th {\n",
|
||||
" vertical-align: top;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe thead th {\n",
|
||||
" text-align: right;\n",
|
||||
" }\n",
|
||||
"</style>\n",
|
||||
"<table border=\"1\" class=\"dataframe\">\n",
|
||||
" <thead>\n",
|
||||
" <tr style=\"text-align: right;\">\n",
|
||||
" <th></th>\n",
|
||||
" <th>Ticket Type</th>\n",
|
||||
" <th>Ticket Subject</th>\n",
|
||||
" <th>Ticket Description</th>\n",
|
||||
" </tr>\n",
|
||||
" </thead>\n",
|
||||
" <tbody>\n",
|
||||
" <tr>\n",
|
||||
" <th>0</th>\n",
|
||||
" <td>Technical issue</td>\n",
|
||||
" <td>Product setup</td>\n",
|
||||
" <td>I'm having an issue with the {product_purchase...</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>1</th>\n",
|
||||
" <td>Technical issue</td>\n",
|
||||
" <td>Peripheral compatibility</td>\n",
|
||||
" <td>I'm having an issue with the {product_purchase...</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>2</th>\n",
|
||||
" <td>Technical issue</td>\n",
|
||||
" <td>Network problem</td>\n",
|
||||
" <td>I'm facing a problem with my {product_purchase...</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>3</th>\n",
|
||||
" <td>Billing inquiry</td>\n",
|
||||
" <td>Account access</td>\n",
|
||||
" <td>I'm having an issue with the {product_purchase...</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>4</th>\n",
|
||||
" <td>Billing inquiry</td>\n",
|
||||
" <td>Data loss</td>\n",
|
||||
" <td>I'm having an issue with the {product_purchase...</td>\n",
|
||||
" </tr>\n",
|
||||
" </tbody>\n",
|
||||
"</table>\n",
|
||||
"</div>"
|
||||
],
|
||||
"text/plain": [
|
||||
" Ticket Type Ticket Subject \\\n",
|
||||
"0 Technical issue Product setup \n",
|
||||
"1 Technical issue Peripheral compatibility \n",
|
||||
"2 Technical issue Network problem \n",
|
||||
"3 Billing inquiry Account access \n",
|
||||
"4 Billing inquiry Data loss \n",
|
||||
"\n",
|
||||
" Ticket Description \n",
|
||||
"0 I'm having an issue with the {product_purchase... \n",
|
||||
"1 I'm having an issue with the {product_purchase... \n",
|
||||
"2 I'm facing a problem with my {product_purchase... \n",
|
||||
"3 I'm having an issue with the {product_purchase... \n",
|
||||
"4 I'm having an issue with the {product_purchase... "
|
||||
]
|
||||
},
|
||||
"execution_count": 20,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Dataset preview\n",
|
||||
"\n",
|
||||
"preview_df = df[REQUIRED_COLUMNS].head(5).copy()\n",
|
||||
"\n",
|
||||
"preview_df[\"Ticket Subject\"] = preview_df[\"Ticket Subject\"].astype(str).str.slice(0, 70)\n",
|
||||
"preview_df[\"Ticket Description\"] = preview_df[\"Ticket Description\"].astype(str).str.slice(0, 90)\n",
|
||||
"\n",
|
||||
"preview_df"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 21,
|
||||
"id": "e01e6ad8",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"Ticket Type\n",
|
||||
"Refund request 1752\n",
|
||||
"Technical issue 1747\n",
|
||||
"Cancellation request 1695\n",
|
||||
"Product inquiry 1641\n",
|
||||
"Billing inquiry 1634\n",
|
||||
"Name: count, dtype: int64"
|
||||
]
|
||||
},
|
||||
"execution_count": 21,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Original label distribution\n",
|
||||
"\n",
|
||||
"df[\"Ticket Type\"].value_counts(dropna=False)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 24,
|
||||
"id": "aa0d4e9e",
|
||||
"metadata": {
|
||||
"lines_to_next_cell": 2
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Label mapping\n",
|
||||
"\n",
|
||||
"def map_to_demo_label(ticket_type, subject, description):\n",
|
||||
" ticket_type_clean = str(ticket_type).strip().lower()\n",
|
||||
" subject_clean = str(subject).strip().lower()\n",
|
||||
"\n",
|
||||
" shipping_keywords = [\"delivery\", \"shipping\", \"shipment\", \"tracking\", \"track\", \"address\"]\n",
|
||||
" billing_keywords = [\"payment\", \"refund\", \"invoice\", \"billing\", \"charge\", \"cancellation\"]\n",
|
||||
" technical_keywords = [\n",
|
||||
" \"network\",\n",
|
||||
" \"software\",\n",
|
||||
" \"hardware\",\n",
|
||||
" \"installation\",\n",
|
||||
" \"setup\",\n",
|
||||
" \"display\",\n",
|
||||
" \"data loss\",\n",
|
||||
" \"peripheral\",\n",
|
||||
" \"account access\",\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" if any(keyword in subject_clean for keyword in shipping_keywords):\n",
|
||||
" return \"Shipping\"\n",
|
||||
"\n",
|
||||
" if any(keyword in subject_clean for keyword in billing_keywords):\n",
|
||||
" return \"Billing\"\n",
|
||||
"\n",
|
||||
" if ticket_type_clean in {\"technical issue\", \"product inquiry\"}:\n",
|
||||
" return \"Technical Support\"\n",
|
||||
"\n",
|
||||
" if ticket_type_clean in {\"billing inquiry\", \"refund request\", \"cancellation request\"}:\n",
|
||||
" return \"Billing\"\n",
|
||||
"\n",
|
||||
" if any(keyword in subject_clean for keyword in technical_keywords):\n",
|
||||
" return \"Technical Support\"\n",
|
||||
"\n",
|
||||
" return None"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 23,
|
||||
"id": "fccb6295",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Clean dataset shape: (8469, 2)\n",
|
||||
"\n",
|
||||
"Clean label distribution:\n",
|
||||
"expected_label\n",
|
||||
"Billing 5371\n",
|
||||
"Technical Support 2537\n",
|
||||
"Shipping 561\n",
|
||||
"Name: count, dtype: int64\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<div>\n",
|
||||
"<style scoped>\n",
|
||||
" .dataframe tbody tr th:only-of-type {\n",
|
||||
" vertical-align: middle;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe tbody tr th {\n",
|
||||
" vertical-align: top;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe thead th {\n",
|
||||
" text-align: right;\n",
|
||||
" }\n",
|
||||
"</style>\n",
|
||||
"<table border=\"1\" class=\"dataframe\">\n",
|
||||
" <thead>\n",
|
||||
" <tr style=\"text-align: right;\">\n",
|
||||
" <th></th>\n",
|
||||
" <th>text</th>\n",
|
||||
" <th>expected_label</th>\n",
|
||||
" </tr>\n",
|
||||
" </thead>\n",
|
||||
" <tbody>\n",
|
||||
" <tr>\n",
|
||||
" <th>0</th>\n",
|
||||
" <td>Product setup</td>\n",
|
||||
" <td>Technical Support</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>1</th>\n",
|
||||
" <td>Peripheral compatibility</td>\n",
|
||||
" <td>Technical Support</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>2</th>\n",
|
||||
" <td>Network problem</td>\n",
|
||||
" <td>Technical Support</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>3</th>\n",
|
||||
" <td>Account access</td>\n",
|
||||
" <td>Billing</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>4</th>\n",
|
||||
" <td>Data loss</td>\n",
|
||||
" <td>Billing</td>\n",
|
||||
" </tr>\n",
|
||||
" </tbody>\n",
|
||||
"</table>\n",
|
||||
"</div>"
|
||||
],
|
||||
"text/plain": [
|
||||
" text expected_label\n",
|
||||
"0 Product setup Technical Support\n",
|
||||
"1 Peripheral compatibility Technical Support\n",
|
||||
"2 Network problem Technical Support\n",
|
||||
"3 Account access Billing\n",
|
||||
"4 Data loss Billing"
|
||||
]
|
||||
},
|
||||
"execution_count": 23,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Dataset cleaning\n",
|
||||
"\n",
|
||||
"clean_df = df[REQUIRED_COLUMNS].copy()\n",
|
||||
"\n",
|
||||
"clean_df[\"Ticket Type\"] = clean_df[\"Ticket Type\"].fillna(\"\").astype(str).str.strip()\n",
|
||||
"clean_df[\"Ticket Subject\"] = clean_df[\"Ticket Subject\"].fillna(\"\").astype(str).str.strip()\n",
|
||||
"clean_df[\"Ticket Description\"] = clean_df[\"Ticket Description\"].fillna(\"\").astype(str).str.strip()\n",
|
||||
"\n",
|
||||
"clean_df[\"text\"] = clean_df[\"Ticket Subject\"]\n",
|
||||
"\n",
|
||||
"clean_df[\"expected_label\"] = clean_df.apply(\n",
|
||||
" lambda row: map_to_demo_label(\n",
|
||||
" ticket_type=row[\"Ticket Type\"],\n",
|
||||
" subject=row[\"Ticket Subject\"],\n",
|
||||
" description=row[\"Ticket Description\"],\n",
|
||||
" ),\n",
|
||||
" axis=1,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"clean_df = clean_df[clean_df[\"text\"] != \"\"]\n",
|
||||
"clean_df = clean_df[clean_df[\"expected_label\"].isin(TARGET_LABELS)]\n",
|
||||
"clean_df = clean_df[[\"text\", \"expected_label\"]].reset_index(drop=True)\n",
|
||||
"\n",
|
||||
"print(\"Clean dataset shape:\", clean_df.shape)\n",
|
||||
"print(\"\\nClean label distribution:\")\n",
|
||||
"print(clean_df[\"expected_label\"].value_counts())\n",
|
||||
"\n",
|
||||
"clean_df.head()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 25,
|
||||
"id": "467793ff",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Evaluation samples: 120\n",
|
||||
"expected_label\n",
|
||||
"Billing 81\n",
|
||||
"Technical Support 28\n",
|
||||
"Shipping 11\n",
|
||||
"Name: count, dtype: int64\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<div>\n",
|
||||
"<style scoped>\n",
|
||||
" .dataframe tbody tr th:only-of-type {\n",
|
||||
" vertical-align: middle;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe tbody tr th {\n",
|
||||
" vertical-align: top;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe thead th {\n",
|
||||
" text-align: right;\n",
|
||||
" }\n",
|
||||
"</style>\n",
|
||||
"<table border=\"1\" class=\"dataframe\">\n",
|
||||
" <thead>\n",
|
||||
" <tr style=\"text-align: right;\">\n",
|
||||
" <th></th>\n",
|
||||
" <th>text</th>\n",
|
||||
" <th>expected_label</th>\n",
|
||||
" </tr>\n",
|
||||
" </thead>\n",
|
||||
" <tbody>\n",
|
||||
" <tr>\n",
|
||||
" <th>0</th>\n",
|
||||
" <td>Product setup</td>\n",
|
||||
" <td>Billing</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>1</th>\n",
|
||||
" <td>Battery life</td>\n",
|
||||
" <td>Technical Support</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>2</th>\n",
|
||||
" <td>Refund request</td>\n",
|
||||
" <td>Billing</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>3</th>\n",
|
||||
" <td>Peripheral compatibility</td>\n",
|
||||
" <td>Billing</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>4</th>\n",
|
||||
" <td>Peripheral compatibility</td>\n",
|
||||
" <td>Billing</td>\n",
|
||||
" </tr>\n",
|
||||
" </tbody>\n",
|
||||
"</table>\n",
|
||||
"</div>"
|
||||
],
|
||||
"text/plain": [
|
||||
" text expected_label\n",
|
||||
"0 Product setup Billing\n",
|
||||
"1 Battery life Technical Support\n",
|
||||
"2 Refund request Billing\n",
|
||||
"3 Peripheral compatibility Billing\n",
|
||||
"4 Peripheral compatibility Billing"
|
||||
]
|
||||
},
|
||||
"execution_count": 25,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Evaluation subset\n",
|
||||
"\n",
|
||||
"eval_df = clean_df.sample(n=MAX_EVAL_SAMPLES, random_state=RANDOM_SEED).reset_index(drop=True)\n",
|
||||
"\n",
|
||||
"print(\"Evaluation samples:\", len(eval_df))\n",
|
||||
"print(eval_df[\"expected_label\"].value_counts())\n",
|
||||
"\n",
|
||||
"eval_df.head()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 26,
|
||||
"id": "e8ec2a89",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"application/vnd.jupyter.widget-view+json": {
|
||||
"model_id": "2b93189d3a9c4eb7a2a7c2400960e0e9",
|
||||
"version_major": 2,
|
||||
"version_minor": 0
|
||||
},
|
||||
"text/plain": [
|
||||
"Loading weights: 0%| | 0/515 [00:00<?, ?it/s]"
|
||||
]
|
||||
},
|
||||
"metadata": {},
|
||||
"output_type": "display_data"
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Model loaded: facebook/bart-large-mnli\n",
|
||||
"Candidate labels: ['Billing', 'Technical Support', 'Shipping']\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Load zero-shot classification model\n",
|
||||
"\n",
|
||||
"classifier = pipeline(\n",
|
||||
" \"zero-shot-classification\",\n",
|
||||
" model=MODEL_ID\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"print(\"Model loaded:\", MODEL_ID)\n",
|
||||
"print(\"Candidate labels:\", TARGET_LABELS)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 27,
|
||||
"id": "92c3f0ea",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"{'sequence': 'I need a refund for my last order',\n",
|
||||
" 'labels': ['Billing', 'Shipping', 'Technical Support'],\n",
|
||||
" 'scores': [0.6939348578453064, 0.21534056961536407, 0.0907246470451355]}"
|
||||
]
|
||||
},
|
||||
"execution_count": 27,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Test one ticket subject\n",
|
||||
"\n",
|
||||
"example_text = \"I need a refund for my last order\"\n",
|
||||
"\n",
|
||||
"classifier(example_text, TARGET_LABELS)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 28,
|
||||
"id": "fda54fb2",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Prediction function\n",
|
||||
"\n",
|
||||
"def predict_tickets(texts, candidate_labels):\n",
|
||||
" predictions = []\n",
|
||||
"\n",
|
||||
" for text in texts:\n",
|
||||
" output = classifier(text, candidate_labels)\n",
|
||||
"\n",
|
||||
" predictions.append(\n",
|
||||
" {\n",
|
||||
" \"text\": text,\n",
|
||||
" \"predicted_label\": output[\"labels\"][0],\n",
|
||||
" \"confidence\": float(output[\"scores\"][0]),\n",
|
||||
" }\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" return predictions"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 29,
|
||||
"id": "62b7f798",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"\n",
|
||||
"Input text: Battery life\n",
|
||||
"Expected label: Billing\n",
|
||||
"Predicted label: Billing\n",
|
||||
"Confidence: 0.8109\n",
|
||||
"Correct: True\n",
|
||||
"\n",
|
||||
"Input text: Hardware issue\n",
|
||||
"Expected label: Technical Support\n",
|
||||
"Predicted label: Technical Support\n",
|
||||
"Confidence: 0.4475\n",
|
||||
"Correct: True\n",
|
||||
"\n",
|
||||
"Input text: Peripheral compatibility\n",
|
||||
"Expected label: Billing\n",
|
||||
"Predicted label: Technical Support\n",
|
||||
"Confidence: 0.5673\n",
|
||||
"Correct: False\n",
|
||||
"\n",
|
||||
"Input text: Delivery problem\n",
|
||||
"Expected label: Shipping\n",
|
||||
"Predicted label: Shipping\n",
|
||||
"Confidence: 0.9077\n",
|
||||
"Correct: True\n",
|
||||
"\n",
|
||||
"Input text: Product setup\n",
|
||||
"Expected label: Technical Support\n",
|
||||
"Predicted label: Shipping\n",
|
||||
"Confidence: 0.4286\n",
|
||||
"Correct: False\n",
|
||||
"\n",
|
||||
"Input text: Installation support\n",
|
||||
"Expected label: Technical Support\n",
|
||||
"Predicted label: Technical Support\n",
|
||||
"Confidence: 0.7647\n",
|
||||
"Correct: True\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Demo predictions\n",
|
||||
"\n",
|
||||
"demo_df = eval_df.sample(n=6, random_state=RANDOM_SEED).reset_index(drop=True)\n",
|
||||
"demo_predictions = predict_tickets(demo_df[\"text\"].tolist(), TARGET_LABELS)\n",
|
||||
"\n",
|
||||
"for row, prediction in zip(demo_df.itertuples(index=False), demo_predictions):\n",
|
||||
" print(\"\\nInput text:\", row.text)\n",
|
||||
" print(\"Expected label:\", row.expected_label)\n",
|
||||
" print(\"Predicted label:\", prediction[\"predicted_label\"])\n",
|
||||
" print(\"Confidence:\", round(prediction[\"confidence\"], 4))\n",
|
||||
" print(\"Correct:\", prediction[\"predicted_label\"] == row.expected_label)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 30,
|
||||
"id": "e544a0ff",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Accuracy: 0.5917\n",
|
||||
"Correct predictions: 71 out of 120\n",
|
||||
"\n",
|
||||
"Classification report:\n",
|
||||
" precision recall f1-score support\n",
|
||||
"\n",
|
||||
" Billing 0.79 0.60 0.69 81\n",
|
||||
"Technical Support 0.31 0.39 0.35 28\n",
|
||||
" Shipping 0.48 1.00 0.65 11\n",
|
||||
"\n",
|
||||
" accuracy 0.59 120\n",
|
||||
" macro avg 0.53 0.67 0.56 120\n",
|
||||
" weighted avg 0.65 0.59 0.60 120\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Evaluation\n",
|
||||
"\n",
|
||||
"predictions = predict_tickets(eval_df[\"text\"].tolist(), TARGET_LABELS)\n",
|
||||
"\n",
|
||||
"y_true = eval_df[\"expected_label\"].tolist()\n",
|
||||
"y_pred = [prediction[\"predicted_label\"] for prediction in predictions]\n",
|
||||
"\n",
|
||||
"accuracy = accuracy_score(y_true, y_pred)\n",
|
||||
"\n",
|
||||
"print(f\"Accuracy: {accuracy:.4f}\")\n",
|
||||
"print(f\"Correct predictions: {int(accuracy * len(y_true))} out of {len(y_true)}\")\n",
|
||||
"\n",
|
||||
"print(\"\\nClassification report:\")\n",
|
||||
"print(\n",
|
||||
" classification_report(\n",
|
||||
" y_true,\n",
|
||||
" y_pred,\n",
|
||||
" labels=TARGET_LABELS,\n",
|
||||
" zero_division=0,\n",
|
||||
" )\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 31,
|
||||
"id": "28dc02cf",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<div>\n",
|
||||
"<style scoped>\n",
|
||||
" .dataframe tbody tr th:only-of-type {\n",
|
||||
" vertical-align: middle;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe tbody tr th {\n",
|
||||
" vertical-align: top;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe thead th {\n",
|
||||
" text-align: right;\n",
|
||||
" }\n",
|
||||
"</style>\n",
|
||||
"<table border=\"1\" class=\"dataframe\">\n",
|
||||
" <thead>\n",
|
||||
" <tr style=\"text-align: right;\">\n",
|
||||
" <th></th>\n",
|
||||
" <th>pred_Billing</th>\n",
|
||||
" <th>pred_Technical Support</th>\n",
|
||||
" <th>pred_Shipping</th>\n",
|
||||
" </tr>\n",
|
||||
" </thead>\n",
|
||||
" <tbody>\n",
|
||||
" <tr>\n",
|
||||
" <th>true_Billing</th>\n",
|
||||
" <td>49</td>\n",
|
||||
" <td>24</td>\n",
|
||||
" <td>8</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>true_Technical Support</th>\n",
|
||||
" <td>13</td>\n",
|
||||
" <td>11</td>\n",
|
||||
" <td>4</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>true_Shipping</th>\n",
|
||||
" <td>0</td>\n",
|
||||
" <td>0</td>\n",
|
||||
" <td>11</td>\n",
|
||||
" </tr>\n",
|
||||
" </tbody>\n",
|
||||
"</table>\n",
|
||||
"</div>"
|
||||
],
|
||||
"text/plain": [
|
||||
" pred_Billing pred_Technical Support pred_Shipping\n",
|
||||
"true_Billing 49 24 8\n",
|
||||
"true_Technical Support 13 11 4\n",
|
||||
"true_Shipping 0 0 11"
|
||||
]
|
||||
},
|
||||
"execution_count": 31,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Confusion matrix\n",
|
||||
"\n",
|
||||
"confusion = confusion_matrix(y_true, y_pred, labels=TARGET_LABELS)\n",
|
||||
"\n",
|
||||
"confusion_df = pd.DataFrame(\n",
|
||||
" confusion,\n",
|
||||
" index=[f\"true_{label}\" for label in TARGET_LABELS],\n",
|
||||
" columns=[f\"pred_{label}\" for label in TARGET_LABELS],\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"confusion_df"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 32,
|
||||
"id": "9b671b36",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Limitations:\n",
|
||||
"- Zero-shot classification is flexible, but less precise than fine-tuning.\n",
|
||||
"- Candidate labels influence the prediction.\n",
|
||||
"- The mapping from original Kaggle ticket types to demo labels is rule-based.\n",
|
||||
"- This demo uses only ticket subjects; descriptions could provide more context.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Limitations\n",
|
||||
"\n",
|
||||
"print(\"Limitations:\")\n",
|
||||
"print(\"- Zero-shot classification is flexible, but less precise than fine-tuning.\")\n",
|
||||
"print(\"- Candidate labels influence the prediction.\")\n",
|
||||
"print(\"- The mapping from original Kaggle ticket types to demo labels is rule-based.\")\n",
|
||||
"print(\"- This demo uses only ticket subjects; descriptions could provide more context.\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"jupytext": {
|
||||
"cell_metadata_filter": "-all",
|
||||
"main_language": "python",
|
||||
"notebook_metadata_filter": "-all"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python (aiis)",
|
||||
"language": "python",
|
||||
"name": "aiis"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.10.20"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,10 @@
|
||||
text,expected_label
|
||||
"I was charged twice for my last order and need a refund.",Billing
|
||||
"The invoice amount is different from the price shown on the website.",Billing
|
||||
"My payment was successful but I did not receive a confirmation email.",Billing
|
||||
"The app crashes every time I try to log in.",Technical Support
|
||||
"I cannot reset my password because I do not receive the verification email.",Technical Support
|
||||
"The website shows an error when I open my account settings.",Technical Support
|
||||
"My package has not arrived yet and the tracking number is not updating.",Shipping
|
||||
"The delivery address is wrong and I need to update it.",Shipping
|
||||
"My order was shipped to the wrong city.",Shipping
|
||||
|
Reference in New Issue
Block a user