mrqadeer commited on
Commit
f6ea7de
·
1 Parent(s): 171adcd

Initial project commit with code and figures

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.dockerignore ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ .env
3
+ __pycache__/
4
+ *.py[cod]
5
+ *$py.class
6
+ *.so
7
+ .Python
8
+ build/
9
+ develop-eggs/
10
+ dist/
11
+ downloads/
12
+ eggs/
13
+ .eggs/
14
+ lib/
15
+ lib64/
16
+ parts/
17
+ sdist/
18
+ var/
19
+ wheels/
20
+ *.egg-info/
21
+ .installed.cfg
22
+ *.egg
23
+ .git/
24
+ .github/
25
+ .gitignore
26
+ .DS_Store
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data
2
+
3
+ # Mac OS-specific storage files
4
+ .DS_Store
5
+
6
+ # vim
7
+ *.swp
8
+ *.swo
9
+
10
+ ## https://github.com/github/gitignore/blob/e8554d85bf62e38d6db966a50d2064ac025fd82a/Python.gitignore
11
+
12
+ # Byte-compiled / optimized / DLL files
13
+ __pycache__/
14
+ *.py[cod]
15
+ *$py.class
16
+
17
+ # C extensions
18
+ *.so
19
+
20
+ # Distribution / packaging
21
+ .Python
22
+ build/
23
+ develop-eggs/
24
+ dist/
25
+ downloads/
26
+ eggs/
27
+ .eggs/
28
+ lib/
29
+ lib64/
30
+ parts/
31
+ sdist/
32
+ var/
33
+ wheels/
34
+ share/python-wheels/
35
+ *.egg-info/
36
+ .installed.cfg
37
+ *.egg
38
+ MANIFEST
39
+
40
+ # PyInstaller
41
+ # Usually these files are written by a python script from a template
42
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
43
+ *.manifest
44
+ *.spec
45
+
46
+ # Installer logs
47
+ pip-log.txt
48
+ pip-delete-this-directory.txt
49
+
50
+ # Unit test / coverage reports
51
+ htmlcov/
52
+ .tox/
53
+ .nox/
54
+ .coverage
55
+ .coverage.*
56
+ .cache
57
+ nosetests.xml
58
+ coverage.xml
59
+ *.cover
60
+ *.py,cover
61
+ .hypothesis/
62
+ .pytest_cache/
63
+ cover/
64
+
65
+ # Translations
66
+ *.mo
67
+ *.pot
68
+
69
+ # Django stuff:
70
+ *.log
71
+ local_settings.py
72
+ db.sqlite3
73
+ db.sqlite3-journal
74
+
75
+ # Flask stuff:
76
+ instance/
77
+ .webassets-cache
78
+
79
+ # Scrapy stuff:
80
+ .scrapy
81
+
82
+ # MkDocs documentation
83
+ docs/site/
84
+
85
+ # PyBuilder
86
+ .pybuilder/
87
+ target/
88
+
89
+ # Jupyter Notebook
90
+ .ipynb_checkpoints
91
+
92
+ # IPython
93
+ profile_default/
94
+ ipython_config.py
95
+
96
+ # pyenv
97
+ # For a library or package, you might want to ignore these files since the code is
98
+ # intended to run in multiple environments; otherwise, check them in:
99
+ # .python-version
100
+
101
+ # pipenv
102
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
103
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
104
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
105
+ # install all needed dependencies.
106
+ #Pipfile.lock
107
+
108
+ # UV
109
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
110
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
111
+ # commonly ignored for libraries.
112
+ #uv.lock
113
+
114
+ # poetry
115
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
116
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
117
+ # commonly ignored for libraries.
118
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
119
+ #poetry.lock
120
+
121
+ # pdm
122
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
123
+ #pdm.lock
124
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
125
+ # in version control.
126
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
127
+ .pdm.toml
128
+ .pdm-python
129
+ .pdm-build/
130
+
131
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
132
+ __pypackages__/
133
+
134
+ # Celery stuff
135
+ celerybeat-schedule
136
+ celerybeat.pid
137
+
138
+ # SageMath parsed files
139
+ *.sage.py
140
+
141
+ # Environments
142
+ .env
143
+ .venv
144
+ env/
145
+ venv/
146
+ ENV/
147
+ env.bak/
148
+ venv.bak/
149
+
150
+ # Spyder project settings
151
+ .spyderproject
152
+ .spyproject
153
+
154
+ # Rope project settings
155
+ .ropeproject
156
+
157
+ # mkdocs documentation
158
+ /site
159
+
160
+ # mypy
161
+ .mypy_cache/
162
+ .dmypy.json
163
+ dmypy.json
164
+
165
+ # Pyre type checker
166
+ .pyre/
167
+
168
+ # pytype static type analyzer
169
+ .pytype/
170
+
171
+ # Cython debug symbols
172
+ cython_debug/
173
+
174
+ # PyCharm
175
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
176
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
177
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
178
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
179
+ #.idea/
180
+
181
+ # Ruff stuff:
182
+ .ruff_cache/
183
+
184
+
185
+
186
+ # PyPI configuration file
187
+ .pypirc
188
+
189
+ email_spam_clf.py
190
+ dvc-storage
191
+
Dockerfile ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ ENV PYTHONDONTWRITEBYTECODE=1
4
+ ENV PYTHONUNBUFFERED=1
5
+ ENV STREAMLIT_SERVER_PORT=8501
6
+ ENV STREAMLIT_SERVER_ADDRESS=0.0.0.0
7
+
8
+ WORKDIR /app
9
+
10
+ # Install system dependencies including curl for healthcheck and supervisor
11
+ RUN apt-get update && apt-get install -y \
12
+ build-essential \
13
+ wget \
14
+ curl \
15
+ supervisor \
16
+ && rm -rf /var/lib/apt/lists/*
17
+
18
+ # Create a non-root user to run the application
19
+ RUN useradd -m -u 1000 appuser
20
+
21
+ # Copy the entire project directory
22
+ # .dockerignore should exclude .venv and other unnecessary files
23
+ COPY . .
24
+
25
+ # Install uv and dependencies
26
+ RUN pip install --no-cache-dir --upgrade pip && \
27
+ pip install uv && \
28
+ uv venv /app/.venv && \
29
+ . /app/.venv/bin/activate && \
30
+ uv pip install . && \
31
+ uv sync
32
+
33
+ # Set environment variable to use the venv
34
+ ENV PATH="/app/.venv/bin:$PATH"
35
+
36
+ # Create supervisor configuration
37
+ RUN mkdir -p /etc/supervisor/conf.d
38
+ COPY <<EOF /etc/supervisor/conf.d/supervisord.conf
39
+ [supervisord]
40
+ nodaemon=true
41
+ user=root
42
+ pidfile=/tmp/supervisord.pid
43
+
44
+ [program:fastapi]
45
+ command=/app/.venv/bin/uvicorn api.main:app --host 0.0.0.0 --port 8000
46
+ directory=/app
47
+ user=appuser
48
+ autostart=true
49
+ autorestart=true
50
+ stdout_logfile=/dev/stdout
51
+ stdout_logfile_maxbytes=0
52
+ stderr_logfile=/dev/stderr
53
+ stderr_logfile_maxbytes=0
54
+
55
+ [program:streamlit]
56
+ command=/app/.venv/bin/streamlit run app/main.py --server.port=8501 --server.address=0.0.0.0
57
+ directory=/app
58
+ user=appuser
59
+ autostart=true
60
+ autorestart=true
61
+ stdout_logfile=/dev/stdout
62
+ stdout_logfile_maxbytes=0
63
+ stderr_logfile=/dev/stderr
64
+ stderr_logfile_maxbytes=0
65
+ EOF
66
+
67
+ # Create and set permissions for directories that need write access
68
+ RUN mkdir -p /.local && \
69
+ chown -R appuser:appuser /.local && \
70
+ mkdir -p /home/appuser/.cache && \
71
+ chown -R appuser:appuser /home/appuser && \
72
+ chown -R appuser:appuser /app && \
73
+ mkdir -p /tmp && \
74
+ chmod 777 /tmp
75
+
76
+ # Expose both ports
77
+ EXPOSE 8501 8000
78
+
79
+ HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health && curl --fail http://localhost:8000/health
80
+
81
+ # Command to run both applications (stay as root for supervisor)
82
+ CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
LICENSE ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ The MIT License (MIT)
3
+ Copyright (c) 2025, Qadeer Ahmad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10
+
Makefile ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #################################################################################
2
+ # GLOBALS #
3
+ #################################################################################
4
+
5
+ PROJECT_NAME = email-spam-classifier
6
+ PYTHON_VERSION = 3.12.10
7
+ PYTHON_INTERPRETER = python
8
+
9
+ #################################################################################
10
+ # COMMANDS #
11
+ #################################################################################
12
+
13
+
14
+ ## Install Python dependencies
15
+ .PHONY: requirements
16
+ requirements:
17
+ $(PYTHON_INTERPRETER) -m pip install -U pip
18
+ $(PYTHON_INTERPRETER) -m pip install -r requirements.txt
19
+
20
+
21
+
22
+
23
+ ## Delete all compiled Python files
24
+ .PHONY: clean
25
+ clean:
26
+ find . -type f -name "*.py[co]" -delete
27
+ find . -type d -name "__pycache__" -delete
28
+
29
+
30
+ ## Lint using ruff (use `make format` to do formatting)
31
+ .PHONY: lint
32
+ lint:
33
+ ruff format --check
34
+ ruff check
35
+
36
+ ## Format source code with ruff
37
+ .PHONY: format
38
+ format:
39
+ ruff check --fix
40
+ ruff format
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+ #################################################################################
49
+ # PROJECT RULES #
50
+ #################################################################################
51
+
52
+
53
+ ## Make dataset
54
+ .PHONY: data
55
+ data: requirements
56
+ $(PYTHON_INTERPRETER) email_spam_classifier/dataset.py
57
+
58
+
59
+ #################################################################################
60
+ # Self Documenting Commands #
61
+ #################################################################################
62
+
63
+ .DEFAULT_GOAL := help
64
+
65
+ define PRINT_HELP_PYSCRIPT
66
+ import re, sys; \
67
+ lines = '\n'.join([line for line in sys.stdin]); \
68
+ matches = re.findall(r'\n## (.*)\n[\s\S]+?\n([a-zA-Z_-]+):', lines); \
69
+ print('Available rules:\n'); \
70
+ print('\n'.join(['{:25}{}'.format(*reversed(match)) for match in matches]))
71
+ endef
72
+ export PRINT_HELP_PYSCRIPT
73
+
74
+ help:
75
+ @$(PYTHON_INTERPRETER) -c "${PRINT_HELP_PYSCRIPT}" < $(MAKEFILE_LIST)
README.md CHANGED
@@ -1,10 +1,11 @@
1
  ---
2
  title: Email Classifier
3
- emoji: ⚡
4
- colorFrom: green
5
- colorTo: gray
6
  sdk: docker
7
  pinned: false
 
8
  ---
9
 
10
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: Email Classifier
3
+ emoji: 📊
4
+ colorFrom: red
5
+ colorTo: blue
6
  sdk: docker
7
  pinned: false
8
+ license: apache-2.0
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
api/Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install uv globally
6
+ RUN pip install --no-cache-dir uv
7
+
8
+ # Copy the entire project directory
9
+ # .dockerignore should exclude .venv and other unnecessary files
10
+ COPY . .
11
+
12
+ # Create venv with uv and install dependencies
13
+ RUN uv venv /app/.venv && \
14
+ . /app/.venv/bin/activate && \
15
+ uv pip install . && \
16
+ uv sync
17
+
18
+ # Set environment variable to use the venv
19
+ ENV PATH="/app/.venv/bin:$PATH"
20
+
21
+ # Expose the port the API runs on
22
+ EXPOSE 8000
23
+
24
+ # Command to run the API
25
+ CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000"]
api/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file makes the api directory a Python package
api/core/config.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import AnyHttpUrl, validator
2
+ from pydantic_settings import BaseSettings
3
+ from typing import List, Optional, Union
4
+ import os
5
+ from dotenv import load_dotenv
6
+ from pathlib import Path
7
+
8
+ from email_spam_classifier.config import MODELS_DIR
9
+
10
+ # Load .env file
11
+ load_dotenv()
12
+
13
+ class Settings(BaseSettings):
14
+ # API settings
15
+ API_PREFIX: str = "/api/v1"
16
+ PROJECT_NAME: str = "Email Spam Classifier API"
17
+ PROJECT_DESCRIPTION: str = "An API for classifying emails as spam or ham"
18
+ PROJECT_VERSION: str = "1.0.0"
19
+
20
+ # Server settings
21
+ HOST: str = os.getenv("HOST", "0.0.0.0")
22
+ PORT: int = int(os.getenv("PORT", 8000))
23
+ DEBUG: bool = os.getenv("DEBUG", "False").lower() in ("true", "1", "t")
24
+
25
+ # Environment settings
26
+ ENVIRONMENT: str = os.getenv("ENVIRONMENT", "development")
27
+
28
+ # CORS settings
29
+ CORS_ORIGINS: List[AnyHttpUrl] = []
30
+
31
+ # Model settings
32
+ MODEL_PATH: Path = MODELS_DIR / "best_model.pkl"
33
+
34
+ # Rate limiting
35
+ RATE_LIMIT_ENABLED: bool = True
36
+ RATE_LIMIT_REQUESTS: int = 100
37
+ RATE_LIMIT_TIMEFRAME: int = 3600 # seconds
38
+
39
+ @validator("CORS_ORIGINS", pre=True)
40
+ def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
41
+ if isinstance(v, str) and not v.startswith("["):
42
+ return [i.strip() for i in v.split(",")]
43
+ elif isinstance(v, (list, str)):
44
+ return v
45
+ raise ValueError(v)
46
+
47
+ class Config:
48
+ case_sensitive = True
49
+
50
+ # Create settings instance
51
+ settings = Settings()
api/core/dependencies.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Depends, Request, Header, HTTPException
2
+ from fastapi.security import APIKeyHeader
3
+ import time
4
+ from typing import Optional
5
+
6
+ from api.core.config import settings
7
+ from api.core.exceptions import RateLimitException
8
+ from api.services.spam_classifier import SpamClassifierService
9
+
10
+ # API key security (if needed)
11
+ api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
12
+
13
+ # Create in-memory rate limiting store (in a real app, use Redis)
14
+ rate_limit_store = {}
15
+
16
+ # Dependency to get the spam classifier service
17
+ def get_spam_classifier_service():
18
+ return SpamClassifierService()
19
+
20
+ # Function to get client IP address from request
21
+ def get_client_ip(request: Request) -> str:
22
+ if "x-forwarded-for" in request.headers:
23
+ return request.headers["x-forwarded-for"].split(",")[0].strip()
24
+
25
+ # Fix for the error: Check if client attribute exists and has host property
26
+ if request.client is not None:
27
+ return request.client.host
28
+
29
+ # Fallback if client is None
30
+ return "127.0.0.1"
31
+
32
+ # Rate limiting dependency
33
+ def check_rate_limit(
34
+ request: Request,
35
+ x_client_id: Optional[str] = Header(None)
36
+ ):
37
+ if not settings.RATE_LIMIT_ENABLED:
38
+ return
39
+
40
+ # Use client ID from header or IP address
41
+ client_id = x_client_id or get_client_ip(request)
42
+ current_time = int(time.time())
43
+
44
+ # Initialize or get client's request history
45
+ if client_id not in rate_limit_store:
46
+ rate_limit_store[client_id] = {"count": 0, "reset_at": current_time + settings.RATE_LIMIT_TIMEFRAME}
47
+
48
+ client_data = rate_limit_store[client_id]
49
+
50
+ # Reset counter if timeframe has passed
51
+ if current_time > client_data["reset_at"]:
52
+ client_data["count"] = 0
53
+ client_data["reset_at"] = current_time + settings.RATE_LIMIT_TIMEFRAME
54
+
55
+ # Check if limit exceeded
56
+ if client_data["count"] >= settings.RATE_LIMIT_REQUESTS:
57
+ reset_in = client_data["reset_at"] - current_time
58
+ raise RateLimitException(f"Rate limit exceeded. Try again in {reset_in} seconds")
59
+
60
+ # Increment counter
61
+ client_data["count"] += 1
62
+
63
+ # Combined dependency
64
+ def common_dependencies(
65
+ request: Request,
66
+ x_client_id: Optional[str] = Header(None),
67
+ _: Optional[str] = Depends(check_rate_limit),
68
+ spam_classifier_service: SpamClassifierService = Depends(get_spam_classifier_service)
69
+ ):
70
+ return {"spam_classifier_service": spam_classifier_service}
api/core/exceptions.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import HTTPException
2
+ from typing import Any, Dict, Optional
3
+
4
+ class CustomException(HTTPException):
5
+ """Base custom exception class"""
6
+
7
+ def __init__(
8
+ self,
9
+ status_code: int,
10
+ detail: str,
11
+ error_code: str = "ERROR",
12
+ headers: Optional[Dict[str, Any]] = None
13
+ ):
14
+ self.status_code = status_code
15
+ self.detail = detail
16
+ self.error_code = error_code
17
+ self.headers = headers
18
+
19
+ class ModelLoadException(CustomException):
20
+ """Raised when model loading fails"""
21
+ def __init__(self, detail: str = "Failed to load model"):
22
+ super().__init__(
23
+ status_code=500,
24
+ detail=detail,
25
+ error_code="MODEL_LOAD_ERROR"
26
+ )
27
+
28
+ class PredictionException(CustomException):
29
+ """Raised when prediction fails"""
30
+ def __init__(self, detail: str = "Failed to make prediction"):
31
+ super().__init__(
32
+ status_code=500,
33
+ detail=detail,
34
+ error_code="PREDICTION_ERROR"
35
+ )
36
+
37
+ class RateLimitException(CustomException):
38
+ """Raised when rate limit is exceeded"""
39
+ def __init__(self, detail: str = "Rate limit exceeded"):
40
+ super().__init__(
41
+ status_code=429,
42
+ detail=detail,
43
+ error_code="RATE_LIMIT_EXCEEDED",
44
+ headers={"Retry-After": "3600"}
45
+ )
46
+
47
+ class ValidationException(CustomException):
48
+ """Raised when input validation fails"""
49
+ def __init__(self, detail: str = "Validation error"):
50
+ super().__init__(
51
+ status_code=422,
52
+ detail=detail,
53
+ error_code="VALIDATION_ERROR"
54
+ )
api/main.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import JSONResponse
4
+ from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
5
+ from fastapi.openapi.utils import get_openapi
6
+ from fastapi.staticfiles import StaticFiles
7
+ import os
8
+
9
+ from loguru import logger
10
+ import time
11
+ import uvicorn
12
+
13
+ from api.routers import spam_router, health_router
14
+ from api.core.config import settings
15
+ from api.core.exceptions import CustomException
16
+
17
+ app = FastAPI(
18
+ title=settings.PROJECT_NAME,
19
+ description=settings.PROJECT_DESCRIPTION,
20
+ version=settings.PROJECT_VERSION,
21
+ openapi_url=None if settings.ENVIRONMENT == "production" else "/openapi.json"
22
+ )
23
+
24
+ # Add CORS middleware
25
+ app.add_middleware(
26
+ CORSMiddleware,
27
+ allow_origins=[str(origin) for origin in settings.CORS_ORIGINS],
28
+ allow_credentials=True,
29
+ allow_methods=["*"],
30
+ allow_headers=["*"],
31
+ )
32
+
33
+ # Register routers
34
+ app.include_router(health_router.router, tags=["Health"])
35
+ app.include_router(spam_router.router, prefix="/api/v1", tags=["Spam Classification"])
36
+
37
+ # Mount static files
38
+ app.mount("/static", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "static")), name="static")
39
+
40
+ # Custom exception handler
41
+ @app.exception_handler(CustomException)
42
+ async def custom_exception_handler(request: Request, exc: CustomException):
43
+ return JSONResponse(
44
+ status_code=exc.status_code,
45
+ content={"detail": exc.detail, "error_code": exc.error_code}
46
+ )
47
+
48
+ # Middleware for request logging
49
+ @app.middleware("http")
50
+ async def log_requests(request: Request, call_next):
51
+ start_time = time.time()
52
+
53
+ # Get the client IP
54
+ forwarded = request.headers.get("X-Forwarded-For")
55
+ ip = forwarded.split(",")[0] if forwarded else (
56
+ request.client.host if request.client is not None else "127.0.0.1"
57
+ )
58
+
59
+ # Log the request
60
+ logger.info(f"Request: {request.method} {request.url.path} from {ip}")
61
+
62
+ response = await call_next(request)
63
+
64
+ # Calculate processing time
65
+ process_time = time.time() - start_time
66
+ logger.info(f"Response: {request.method} {request.url.path} - Status: {response.status_code}, Time: {process_time:.4f}s")
67
+
68
+ # Add custom header with processing time
69
+ response.headers["X-Process-Time"] = str(process_time)
70
+ return response
71
+
72
+
73
+ # Custom OpenAPI schema with additional metadata
74
+ @app.get("/openapi.json", include_in_schema=False)
75
+ async def get_open_api_endpoint():
76
+ openapi_schema = get_openapi(
77
+ title=settings.PROJECT_NAME,
78
+ version=settings.PROJECT_VERSION,
79
+ description=settings.PROJECT_DESCRIPTION,
80
+ routes=app.routes,
81
+ )
82
+
83
+ # Ensure the OpenAPI version is set
84
+ if "openapi" not in openapi_schema:
85
+ openapi_schema["openapi"] = "3.0.2"
86
+
87
+ return openapi_schema
88
+
89
+ if __name__ == "__main__":
90
+ uvicorn.run(
91
+ app=app,
92
+ host=settings.HOST,
93
+ port=settings.PORT,
94
+ reload=settings.DEBUG,
95
+ log_level="info"
96
+ )
api/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file makes the models directory a Python package
api/models/spam.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field, field_validator
2
+ from typing import List, Optional
3
+
4
+ class EmailContent(BaseModel):
5
+ """Single email content request model"""
6
+ text: str = Field(
7
+ ...,
8
+ min_length=1,
9
+ max_length=100000,
10
+ description="Email content text",
11
+ example="Get a free gift card now!"
12
+ )
13
+
14
+ @field_validator('text')
15
+ def text_must_not_be_empty(cls, v):
16
+ v = v.strip()
17
+ if not v:
18
+ raise ValueError('Email text cannot be empty')
19
+ return v
20
+
21
+ class BatchEmailsRequest(BaseModel):
22
+ """Batch email request model"""
23
+ emails: List[EmailContent] = Field(
24
+ default=...,
25
+ min_items=1,
26
+ max_items=100
27
+ )
28
+
29
+ class SpamPredictionResult(BaseModel):
30
+ """Single prediction result model"""
31
+ is_spam: bool
32
+ spam_probability: float = Field(
33
+ default=...,
34
+ ge=0.0,
35
+ le=1.0
36
+ )
37
+ classification: str # 'SPAM' or 'HAM'
38
+ text: Optional[str] = None # Original text might be included in response
39
+
40
+ class BatchPredictionResponse(BaseModel):
41
+ """Batch prediction response model"""
42
+ results: List[SpamPredictionResult]
43
+ summary: dict = Field(
44
+ default=...,
45
+ example={
46
+ "total": 10,
47
+ "spam_count": 7,
48
+ "ham_count": 3,
49
+ "spam_percentage": 70.0
50
+ }
51
+ )
52
+
53
+ class SinglePredictionResponse(BaseModel):
54
+ """Single prediction response model"""
55
+ result: SpamPredictionResult
api/routers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file makes the routers directory a Python package
api/routers/health_router.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends
2
+ from typing import Dict, Any
3
+
4
+ from api.core.dependencies import get_spam_classifier_service
5
+ from api.services.spam_classifier import SpamClassifierService
6
+
7
+ router = APIRouter()
8
+
9
+ @router.get("/health")
10
+ async def health_check():
11
+ """
12
+ Basic health check endpoint.
13
+ Returns status OK if API is running.
14
+ """
15
+ return {"status": "OK", "service": "Email Spam Classifier API"}
16
+
17
+ @router.get("/health/model")
18
+ async def model_health_check(
19
+ spam_classifier_service: SpamClassifierService = Depends(get_spam_classifier_service)
20
+ ):
21
+ """
22
+ Check if the model is loaded and ready to make predictions.
23
+ """
24
+ model_status = spam_classifier_service.check_model_health()
25
+ return {
26
+ "status": "OK" if model_status["is_ready"] else "ERROR",
27
+ "model": model_status
28
+ }
29
+
30
+ @router.get("/health/detailed")
31
+ async def detailed_health_check(
32
+ spam_classifier_service: SpamClassifierService = Depends(get_spam_classifier_service)
33
+ ):
34
+ """
35
+ Detailed health check with system information and component statuses.
36
+ """
37
+ import platform
38
+ import psutil
39
+ import time
40
+
41
+ model_status = spam_classifier_service.check_model_health()
42
+
43
+ return {
44
+ "status": "OK" if model_status["is_ready"] else "DEGRADED",
45
+ "timestamp": time.time(),
46
+ "system": {
47
+ "platform": platform.system(),
48
+ "python_version": platform.python_version(),
49
+ "cpu_usage": psutil.cpu_percent(),
50
+ "memory_usage": psutil.virtual_memory().percent
51
+ },
52
+ "components": {
53
+ "api": {"status": "OK"},
54
+ "model": model_status
55
+ }
56
+ }
api/routers/spam_router.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, BackgroundTasks
2
+ from typing import Dict, Any, List
3
+
4
+ from api.models.spam import (
5
+ EmailContent,
6
+ BatchEmailsRequest,
7
+ SpamPredictionResult,
8
+ SinglePredictionResponse,
9
+ BatchPredictionResponse
10
+ )
11
+ from api.core.dependencies import common_dependencies
12
+ from api.services.spam_classifier import SpamClassifierService
13
+
14
+ router = APIRouter()
15
+
16
+ @router.post("/classify", response_model=SinglePredictionResponse)
17
+ async def classify_email(
18
+ email: EmailContent,
19
+ background_tasks: BackgroundTasks,
20
+ commons: Dict[str, Any] = Depends(common_dependencies)
21
+ ):
22
+ """
23
+ Classify a single email as spam or ham.
24
+
25
+ - **email**: Email content to classify
26
+ - Returns prediction result with spam probability
27
+ """
28
+ spam_classifier: SpamClassifierService = commons["spam_classifier_service"]
29
+ result = spam_classifier.predict_single(email.text)
30
+
31
+ # Log the prediction asynchronously
32
+ background_tasks.add_task(spam_classifier.log_prediction, email.text, result)
33
+
34
+ return SinglePredictionResponse(
35
+ result=SpamPredictionResult(
36
+ is_spam=result["is_spam"],
37
+ spam_probability=result["spam_probability"],
38
+ classification=result["classification"],
39
+ text=email.text
40
+ )
41
+ )
42
+
43
+ @router.post("/batch-classify", response_model=BatchPredictionResponse)
44
+ async def classify_batch(
45
+ batch_request: BatchEmailsRequest,
46
+ background_tasks: BackgroundTasks,
47
+ commons: Dict[str, Any] = Depends(common_dependencies)
48
+ ):
49
+ """
50
+ Classify multiple emails in a single request.
51
+
52
+ - **batch_request**: Batch of emails to classify
53
+ - Returns prediction results for all emails
54
+ """
55
+ spam_classifier: SpamClassifierService = commons["spam_classifier_service"]
56
+
57
+ # Extract texts
58
+ texts = [email.text for email in batch_request.emails]
59
+
60
+ # Get predictions
61
+ predictions_df = spam_classifier.predict_batch(texts)
62
+
63
+ # Convert to response format
64
+ results = []
65
+ for i, (_, row) in enumerate(predictions_df.iterrows()):
66
+ results.append(
67
+ SpamPredictionResult(
68
+ is_spam=row["is_spam"],
69
+ spam_probability=row["spam_probability"],
70
+ classification=row["classification"],
71
+ text=texts[i]
72
+ )
73
+ )
74
+
75
+ # Calculate summary statistics
76
+ total = len(results)
77
+ spam_count = sum(1 for r in results if r.is_spam)
78
+ ham_count = total - spam_count
79
+ spam_percentage = (spam_count / total * 100) if total > 0 else 0
80
+
81
+ summary = {
82
+ "total": total,
83
+ "spam_count": spam_count,
84
+ "ham_count": ham_count,
85
+ "spam_percentage": round(spam_percentage, 1)
86
+ }
87
+
88
+ # Log batch processing asynchronously
89
+ background_tasks.add_task(spam_classifier.log_batch_processing, summary)
90
+
91
+ return BatchPredictionResponse(results=results, summary=summary)
api/services/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file makes the services directory a Python package
api/services/spam_classifier.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from pathlib import Path
3
+ from typing import Dict, List, Any, Optional
4
+ import time
5
+
6
+ from loguru import logger
7
+ from tqdm import tqdm
8
+
9
+ from email_spam_classifier.modeling.predict import SpamPredictor
10
+ from api.core.config import settings
11
+ from api.core.exceptions import ModelLoadException, PredictionException
12
+
13
+ class SpamClassifierService:
14
+ """Service for spam classification with alert levels"""
15
+
16
+ # Alert level thresholds based on spam probability - FIXED
17
+ ALERT_THRESHOLDS = {
18
+ 'LOW': 0.4, # 0.0 - 0.4: Low risk (less than 40% spam probability)
19
+ 'MEDIUM': 0.6, # 0.4 - 0.6: Medium risk
20
+ 'HIGH': 0.8, # 0.6 - 0.8: High risk
21
+ 'SEVERE': 1.0 # 0.8 - 1.0: Severe risk (80%+ spam probability)
22
+ }
23
+
24
+ def __init__(self, model_path: Optional[Path] = None, batch_size: int = 100,
25
+ cache_predictions: bool = True, cache_size: int = 1000):
26
+ """
27
+ Initialize the spam classifier service
28
+
29
+ Args:
30
+ model_path: Optional custom path to the model file
31
+ batch_size: Batch size for batch predictions
32
+ cache_predictions: Whether to cache predictions
33
+ cache_size: Size of prediction cache
34
+ """
35
+ self.model_path = model_path or settings.MODEL_PATH
36
+ self.batch_size = batch_size
37
+ self.cache_predictions = cache_predictions
38
+ self.cache_size = cache_size
39
+ self.predictor = None
40
+ self.is_initialized = False
41
+ self.initialize_predictor()
42
+
43
+ def initialize_predictor(self) -> None:
44
+ """Initialize the SpamPredictor with advanced options"""
45
+ try:
46
+ logger.info(f"Initializing spam predictor with model at {self.model_path}")
47
+ self.predictor = SpamPredictor(
48
+ model_path=self.model_path,
49
+ batch_size=self.batch_size,
50
+ cache_predictions=self.cache_predictions,
51
+ cache_size=self.cache_size
52
+ )
53
+ self.is_initialized = True
54
+ logger.success("Spam predictor initialized successfully")
55
+ except Exception as e:
56
+ logger.error(f"Failed to initialize spam predictor: {str(e)}")
57
+ self.is_initialized = False
58
+ raise ModelLoadException(f"Failed to load model: {str(e)}")
59
+
60
+ def _get_alert_level(self, spam_probability: float) -> str:
61
+ """
62
+ Determine alert level based on spam probability - FIXED LOGIC
63
+
64
+ Args:
65
+ spam_probability: Probability that message is spam (0.0 - 1.0)
66
+
67
+ Returns:
68
+ Alert level: LOW, MEDIUM, HIGH, or SEVERE
69
+ """
70
+ if spam_probability < self.ALERT_THRESHOLDS['LOW']: # < 0.4 (40%)
71
+ return 'LOW'
72
+ elif spam_probability < self.ALERT_THRESHOLDS['MEDIUM']: # 0.4 - 0.6 (40-60%)
73
+ return 'MEDIUM'
74
+ elif spam_probability < self.ALERT_THRESHOLDS['HIGH']: # 0.6 - 0.8 (60-80%)
75
+ return 'HIGH'
76
+ else: # >= 0.8 (80%+)
77
+ return 'SEVERE'
78
+
79
+ def _enhance_prediction_result(self, result: Dict[str, Any]) -> Dict[str, Any]:
80
+ """
81
+ Enhance prediction result with alert level and additional metadata
82
+
83
+ Args:
84
+ result: Basic prediction result from SpamPredictor
85
+
86
+ Returns:
87
+ Enhanced result with alert level and metadata
88
+ """
89
+ spam_probability = result['spam_probability']
90
+ alert_level = self._get_alert_level(spam_probability)
91
+
92
+ enhanced_result = {
93
+ **result,
94
+ 'alert_level': alert_level,
95
+ 'confidence_score': max(spam_probability, 1 - spam_probability),
96
+ 'risk_description': self._get_risk_description(alert_level),
97
+ 'timestamp': time.time()
98
+ }
99
+
100
+ return enhanced_result
101
+
102
+ def _get_risk_description(self, alert_level: str) -> str:
103
+ """Get human-readable risk description for alert level - UPDATED"""
104
+ descriptions = {
105
+ 'LOW': 'Low risk - spam probability less than 40%, likely legitimate message',
106
+ 'MEDIUM': 'Medium risk - spam probability 40-60%, requires review',
107
+ 'HIGH': 'High risk - spam probability 60-80%, likely spam, recommend blocking',
108
+ 'SEVERE': 'Severe risk - spam probability 80%+, almost certainly spam, block immediately'
109
+ }
110
+ return descriptions.get(alert_level, 'Unknown risk level')
111
+
112
+ def check_model_health(self) -> Dict[str, Any]:
113
+ """Check if the model is healthy with enhanced diagnostics"""
114
+ status = {
115
+ "is_ready": self.is_initialized and self.predictor is not None,
116
+ "model_path": str(self.model_path),
117
+ "loaded": self.predictor is not None,
118
+ "batch_size": self.batch_size,
119
+ "cache_enabled": self.cache_predictions
120
+ }
121
+
122
+ # If model is loaded, perform a test prediction
123
+ if status["is_ready"]:
124
+ try:
125
+ # Test with both ham and spam-like messages
126
+ test_ham = "This is a normal test message"
127
+ test_spam = "URGENT! Click here to claim your prize NOW!"
128
+
129
+ ham_result = self.predict_single(test_ham)
130
+ spam_result = self.predict_single(test_spam)
131
+
132
+ status["test_prediction"] = "successful"
133
+ status["test_results"] = {
134
+ "ham_test": {
135
+ "classification": ham_result["classification"],
136
+ "alert_level": ham_result["alert_level"]
137
+ },
138
+ "spam_test": {
139
+ "classification": spam_result["classification"],
140
+ "alert_level": spam_result["alert_level"]
141
+ }
142
+ }
143
+ status["last_checked"] = time.time()
144
+ except Exception as e:
145
+ status["is_ready"] = False
146
+ status["test_prediction"] = f"failed: {str(e)}"
147
+
148
+ return status
149
+
150
+ def predict_single(self, text: str) -> Dict[str, Any]:
151
+ """
152
+ Predict if a single message is spam or not with alert levels
153
+
154
+ Args:
155
+ text: Message text to classify
156
+
157
+ Returns:
158
+ Dictionary with enhanced prediction results including alert level
159
+ """
160
+ if not self.is_initialized or self.predictor is None:
161
+ self.initialize_predictor()
162
+
163
+ try:
164
+ # Use the enhanced SpamPredictor
165
+ result = self.predictor.predict_single(text)
166
+
167
+ # Enhance with alert level and metadata
168
+ enhanced_result = self._enhance_prediction_result(result)
169
+
170
+ return enhanced_result
171
+ except Exception as e:
172
+ logger.error(f"Prediction error: {str(e)}")
173
+ raise PredictionException(f"Failed to make prediction: {str(e)}")
174
+
175
+ def predict_batch(self, texts: List[str], parallel: bool = False,
176
+ max_workers: int = 4) -> pd.DataFrame:
177
+ """
178
+ Predict for a batch of texts with enhanced options
179
+
180
+ Args:
181
+ texts: List of message texts to classify
182
+ parallel: Whether to use parallel processing
183
+ max_workers: Number of workers for parallel processing
184
+
185
+ Returns:
186
+ DataFrame with enhanced prediction results including alert levels
187
+ """
188
+ if not self.is_initialized or self.predictor is None:
189
+ self.initialize_predictor()
190
+
191
+ try:
192
+ # Choose prediction method based on parameters
193
+ if parallel and len(texts) > 50: # Use parallel for larger batches
194
+ logger.info(f"Using parallel prediction with {max_workers} workers")
195
+ results_df = self.predictor.predict_parallel(texts, max_workers=max_workers)
196
+ else:
197
+ logger.info(f"Using batch prediction with batch size {self.batch_size}")
198
+ results_df = self.predictor.predict_batch(texts)
199
+
200
+ # Add alert levels and enhanced metadata
201
+ results_df['alert_level'] = results_df['spam_probability'].apply(self._get_alert_level)
202
+ results_df['confidence_score'] = results_df['spam_probability'].apply(
203
+ lambda x: max(x, 1 - x)
204
+ )
205
+ results_df['risk_description'] = results_df['alert_level'].apply(self._get_risk_description)
206
+ results_df['timestamp'] = time.time()
207
+
208
+ return results_df
209
+ except Exception as e:
210
+ logger.error(f"Batch prediction error: {str(e)}")
211
+ raise PredictionException(f"Failed to make batch prediction: {str(e)}")
212
+
213
+ def get_batch_summary(self, results_df: pd.DataFrame) -> Dict[str, Any]:
214
+ """
215
+ Generate summary statistics for batch predictions
216
+
217
+ Args:
218
+ results_df: DataFrame with prediction results
219
+
220
+ Returns:
221
+ Dictionary with summary statistics
222
+ """
223
+ total = len(results_df)
224
+ spam_count = results_df['is_spam'].sum()
225
+ ham_count = total - spam_count
226
+
227
+ # Alert level distribution
228
+ alert_distribution = results_df['alert_level'].value_counts().to_dict()
229
+
230
+ summary = {
231
+ 'total': total,
232
+ 'spam_count': spam_count,
233
+ 'ham_count': ham_count,
234
+ 'spam_percentage': f"{(spam_count/total*100):.1f}%" if total > 0 else "0%",
235
+ 'alert_distribution': alert_distribution,
236
+ 'high_risk_count': alert_distribution.get('HIGH', 0) + alert_distribution.get('SEVERE', 0),
237
+ 'average_spam_probability': results_df['spam_probability'].mean(),
238
+ 'timestamp': time.time()
239
+ }
240
+
241
+ return summary
242
+
243
+ def log_prediction(self, text: str, result: Dict[str, Any]) -> None:
244
+ """
245
+ Log a prediction with enhanced information
246
+
247
+ Args:
248
+ text: The predicted text
249
+ result: Enhanced prediction result
250
+ """
251
+ # Truncate text for logging
252
+ truncated_text = text[:30] + "..." if len(text) > 30 else text
253
+ classification = result["classification"]
254
+ probability = result["spam_probability"]
255
+ alert_level = result["alert_level"]
256
+
257
+ logger.info(
258
+ f"Prediction: '{truncated_text}' classified as {classification} "
259
+ f"(probability: {probability:.4f}, alert: {alert_level})"
260
+ )
261
+
262
+ def log_batch_processing(self, summary: Dict[str, Any]) -> None:
263
+ """
264
+ Log batch processing summary with enhanced metrics
265
+
266
+ Args:
267
+ summary: Enhanced batch processing summary
268
+ """
269
+ alert_dist = summary['alert_distribution']
270
+ logger.info(
271
+ f"Batch processing complete: {summary['total']} messages processed, "
272
+ f"{summary['spam_count']} spam ({summary['spam_percentage']}), "
273
+ f"{summary['ham_count']} ham. "
274
+ f"Alert levels - LOW: {alert_dist.get('LOW', 0)}, "
275
+ f"MEDIUM: {alert_dist.get('MEDIUM', 0)}, "
276
+ f"HIGH: {alert_dist.get('HIGH', 0)}, "
277
+ f"SEVERE: {alert_dist.get('SEVERE', 0)}"
278
+ )
279
+
280
+ def get_alert_statistics(self, results_df: pd.DataFrame) -> Dict[str, Any]:
281
+ """
282
+ Get detailed statistics about alert levels
283
+
284
+ Args:
285
+ results_df: DataFrame with prediction results
286
+
287
+ Returns:
288
+ Dictionary with alert level statistics
289
+ """
290
+ alert_stats = {}
291
+
292
+ for level in ['LOW', 'MEDIUM', 'HIGH', 'SEVERE']:
293
+ level_data = results_df[results_df['alert_level'] == level]
294
+ alert_stats[level] = {
295
+ 'count': len(level_data),
296
+ 'percentage': f"{(len(level_data)/len(results_df)*100):.1f}%" if len(results_df) > 0 else "0%",
297
+ 'avg_probability': level_data['spam_probability'].mean() if len(level_data) > 0 else 0.0,
298
+ 'min_probability': level_data['spam_probability'].min() if len(level_data) > 0 else 0.0,
299
+ 'max_probability': level_data['spam_probability'].max() if len(level_data) > 0 else 0.0
300
+ }
301
+
302
+ return alert_stats
api/static/redoc.standalone.js ADDED
The diff for this file is too large to render. See raw diff
 
api/static/swagger-ui-bundle.js ADDED
The diff for this file is too large to render. See raw diff
 
api/static/swagger-ui.css ADDED
The diff for this file is too large to render. See raw diff
 
api/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file makes the utils directory a Python package
api/utils/logging.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from loguru import logger
3
+ import time
4
+ from pathlib import Path
5
+
6
+ def setup_api_logging(log_path: Path ):
7
+ """
8
+ Configure Loguru logger for the API
9
+
10
+ Args:
11
+ log_path: Optional path to store log files
12
+ """
13
+ # Remove default handler
14
+ logger.remove()
15
+
16
+ # Add stdout handler with custom format
17
+ logger.add(
18
+ sys.stdout,
19
+ colorize=True,
20
+ format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
21
+ level="INFO"
22
+ )
23
+
24
+ # Add file logging if path provided
25
+ if log_path:
26
+ log_path.parent.mkdir(parents=True, exist_ok=True)
27
+ logger.add(
28
+ log_path / f"api_{time.strftime('%Y%m%d')}.log",
29
+ rotation="00:00", # New file at midnight
30
+ compression="zip", # Compress old logs
31
+ retention="30 days", # Keep logs for 30 days
32
+ format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
33
+ level="DEBUG"
34
+ )
35
+
36
+ logger.info("API logging configured")
37
+
38
+ return logger
app/Dockerfile ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ ENV PYTHONDONTWRITEBYTECODE=1
4
+ ENV PYTHONUNBUFFERED=1
5
+ ENV STREAMLIT_SERVER_PORT=8501
6
+ ENV STREAMLIT_SERVER_ADDRESS=0.0.0.0
7
+
8
+ WORKDIR /app
9
+
10
+ # Install system dependencies
11
+ RUN apt-get update && apt-get install -y \
12
+ build-essential \
13
+ wget \
14
+ && rm -rf /var/lib/apt/lists/*
15
+
16
+ # Create a non-root user to run the application
17
+ RUN useradd -m -u 1000 appuser
18
+
19
+ # Copy the entire project directory
20
+ # .dockerignore should exclude .venv and other unnecessary files
21
+ COPY . .
22
+
23
+ # Install uv and dependencies
24
+ RUN pip install --no-cache-dir --upgrade pip && \
25
+ pip install uv && \
26
+ uv venv /app/.venv && \
27
+ . /app/.venv/bin/activate && \
28
+ uv pip install . && \
29
+ uv sync
30
+
31
+ # Set environment variable to use the venv
32
+ ENV PATH="/app/.venv/bin:$PATH"
33
+
34
+ # Create and set permissions for directories that need write access
35
+ RUN mkdir -p /.local && \
36
+ chown -R appuser:appuser /.local && \
37
+ mkdir -p /home/appuser/.cache && \
38
+ chown -R appuser:appuser /home/appuser
39
+
40
+ # Set proper permissions for all app files
41
+ RUN chown -R appuser:appuser /app
42
+
43
+ # Switch to non-root user
44
+ USER appuser
45
+
46
+ # Expose Streamlit port
47
+ EXPOSE 8501
48
+
49
+ HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
50
+
51
+ # Command to run the application
52
+ CMD ["streamlit", "run", "app/main.py", "--server.port=8501", "--server.address=0.0.0.0"]
app/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file makes the app directory a Python package
app/api_client.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import time
4
+ from typing import Dict, Any, Optional, Union, List
5
+ import logging
6
+ import streamlit as st
7
+ from app.config import AppConfig
8
+
9
+ class APIClient:
10
+ """Client for interacting with the Email Spam Classifier API"""
11
+
12
+ def __init__(self, base_url: str = None):
13
+ self.config = AppConfig()
14
+ self.base_url = base_url or self.config.API_BASE_URL
15
+ self.timeout = self.config.API_TIMEOUT
16
+
17
+ # Set up logging
18
+ logging.basicConfig(level=logging.INFO)
19
+ self.logger = logging.getLogger("api_client")
20
+
21
+ # Validate API connection
22
+ self._validate_connection()
23
+
24
+ def _validate_connection(self) -> bool:
25
+ """Validate connection to the API"""
26
+ try:
27
+ response = self._make_request("GET", "/health")
28
+ if response.get("status") != "ok":
29
+ self.logger.warning("API responded but health check failed")
30
+ return False
31
+
32
+ self.logger.info("Successfully connected to API")
33
+ return True
34
+ except Exception as e:
35
+ self.logger.error(f"Failed to connect to API: {str(e)}")
36
+ return False
37
+
38
+ def _make_request(
39
+ self,
40
+ method: str,
41
+ endpoint: str,
42
+ data: Optional[Dict[str, Any]] = None,
43
+ params: Optional[Dict[str, Any]] = None,
44
+ headers: Optional[Dict[str, str]] = None,
45
+ retry_count: int = 3
46
+ ) -> Dict[str, Any]:
47
+ """Make a request to the API with retry logic"""
48
+ url = f"{self.base_url}{endpoint}"
49
+ default_headers = {
50
+ "Content-Type": "application/json",
51
+ "Accept": "application/json",
52
+ "User-Agent": f"SpamClassifier-StreamlitApp/{self.config.APP_VERSION}"
53
+ }
54
+
55
+ if headers:
56
+ default_headers.update(headers)
57
+
58
+ for attempt in range(retry_count):
59
+ try:
60
+ response = requests.request(
61
+ method=method,
62
+ url=url,
63
+ json=data,
64
+ params=params,
65
+ headers=default_headers,
66
+ timeout=self.timeout
67
+ )
68
+
69
+ response.raise_for_status()
70
+ return response.json()
71
+
72
+ except requests.exceptions.HTTPError as e:
73
+ if response.status_code == 429: # Rate limit
74
+ retry_after = int(response.headers.get("Retry-After", 1))
75
+ self.logger.warning(f"Rate limited, retrying in {retry_after}s")
76
+ time.sleep(retry_after)
77
+ continue
78
+
79
+ # Try to get error details from JSON response
80
+ try:
81
+ error_detail = response.json().get("detail", str(e))
82
+ except:
83
+ error_detail = str(e)
84
+
85
+ self.logger.error(f"HTTP error: {error_detail}")
86
+ raise Exception(f"API error: {error_detail}")
87
+
88
+ except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
89
+ if attempt < retry_count - 1:
90
+ wait_time = 2 ** attempt # Exponential backoff
91
+ self.logger.warning(f"Connection error, retrying in {wait_time}s: {str(e)}")
92
+ time.sleep(wait_time)
93
+ continue
94
+ self.logger.error(f"Connection failed after {retry_count} attempts: {str(e)}")
95
+ raise Exception(f"Failed to connect to API: {str(e)}")
96
+
97
+ except Exception as e:
98
+ self.logger.error(f"Unexpected error: {str(e)}")
99
+ raise Exception(f"Unexpected error: {str(e)}")
100
+
101
+ def get_health(self) -> Dict[str, Any]:
102
+ """Get API health status"""
103
+ return self._make_request("GET", "/health")
104
+
105
+ def classify_email(self, content: str) -> Dict[str, Any]:
106
+ """
107
+ Classify email content as spam or ham
108
+
109
+ Args:
110
+ content: The email content to classify
111
+
112
+ Returns:
113
+ Dict containing classification results
114
+ """
115
+ # The API endpoint expects a JSON object with a 'text' field
116
+ payload = {"text": content} # Ensure we use 'text' field as required by the API
117
+ self.logger.info(f"Sending classification request for email")
118
+
119
+ # Make the request to the API
120
+ response = self._make_request("POST", "/api/v1/classify", data=payload)
121
+ # st.write(response)
122
+ # The response contains a nested 'result' object based on the router's response model
123
+ if "result" in response:
124
+ return response["result"]
125
+ return response
126
+
127
+ def batch_classify_emails(self, contents: List[str]) -> List[Dict[str, Any]]:
128
+ """
129
+ Classify multiple email contents as spam or ham
130
+
131
+ Args:
132
+ contents: List of email contents to classify
133
+
134
+ Returns:
135
+ List of dictionaries containing classification results
136
+ """
137
+ results = []
138
+
139
+ # Process each email individually
140
+ # Note: In a production environment, you might want to implement
141
+ # a true batch endpoint on your API for better performance
142
+ for content in contents:
143
+ try:
144
+ result = self.classify_email(content)
145
+ results.append(result)
146
+ except Exception as e:
147
+ self.logger.error(f"Error classifying email: {str(e)}")
148
+ # Add a failed result
149
+ results.append({
150
+ "is_spam": False,
151
+ "spam_probability": 0.0,
152
+ "explanation": f"Error during classification: {str(e)}",
153
+ "error": True
154
+ })
155
+
156
+ return results
157
+
app/components/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file makes the components directory a Python package
app/components/footer.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import time
3
+ from datetime import datetime
4
+ from typing import Optional
5
+ from app.config import AppConfig
6
+
7
+ def render(config: Optional[AppConfig] = None) -> None:
8
+ """Render the footer component.
9
+
10
+ Args:
11
+ config: Optional application configuration
12
+ """
13
+ st.markdown("---")
14
+
15
+ col1, col2, col3 = st.columns([1, 2, 1])
16
+
17
+ with col1:
18
+ st.markdown("### Resources")
19
+ st.markdown("- [Documentation](https://docs.example.com)")
20
+ st.markdown("- [API Reference](https://api.example.com)")
21
+
22
+ with col2:
23
+ st.markdown("### About")
24
+ st.markdown("""
25
+ This application uses machine learning to classify
26
+ emails as spam or legitimate. The classifier is trained
27
+ on a dataset of thousands of emails and continuously
28
+ improves its accuracy.
29
+ """)
30
+
31
+ with col3:
32
+ st.markdown("### Contact")
33
+ st.markdown("support@example.com")
34
+ st.markdown("[GitHub Repository](https://github.com)")
35
+
36
+ # Use current year for copyright
37
+ current_year = datetime.now().year
38
+
39
+ # Get app name from config or use default
40
+ app_name = config.APP_NAME if config else "Email Spam Classifier"
41
+
42
+ # Copyright notice
43
+ st.markdown(
44
+ f"<div style='text-align: center; color: #888888;'>© {current_year} {app_name}. All Rights Reserved.</div>",
45
+ unsafe_allow_html=True
46
+ )
app/components/header.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from typing import Optional
3
+ from app.utils.ui_elements import load_css
4
+ from app.config import AppConfig
5
+
6
+ def render(config: Optional[AppConfig] = None) -> None:
7
+ """Render the header component.
8
+
9
+ Args:
10
+ config: Optional application configuration
11
+ """
12
+ # Load custom CSS
13
+ load_css()
14
+
15
+ # Get app title from config or use default
16
+ app_title = config.APP_NAME if config else "Email Spam Classifier"
17
+
18
+ # Header with logo and title
19
+ col1, col2 = st.columns([1, 5])
20
+
21
+ with col1:
22
+ # You can replace this with an actual logo image
23
+ st.markdown("# 📧")
24
+
25
+ with col2:
26
+ st.markdown(f"""
27
+ # {app_title}
28
+ Detect unwanted spam emails with machine learning
29
+ """)
30
+
31
+ st.markdown("---")
app/components/sidebar.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import time
3
+ from typing import Optional, Dict, Any
4
+ from datetime import datetime
5
+
6
+ from app.api_client import APIClient
7
+ from app.utils.ui_elements import show_error, show_info
8
+
9
+ def render(api_client: APIClient) -> None:
10
+ """Render the sidebar component.
11
+
12
+ Uses session state to store API status information between reruns.
13
+
14
+ Args:
15
+ api_client: Instance of APIClient
16
+ """
17
+ with st.sidebar:
18
+ st.title("📧 Spam Classifier")
19
+ st.markdown("---")
20
+
21
+ # Initialize session state for API status
22
+ if "api_status" not in st.session_state:
23
+ st.session_state.api_status = {"checked_at": None, "status": None, "error": None}
24
+
25
+ # API Status section
26
+ st.subheader("API Status")
27
+
28
+ # Check if we need to refresh the API status (e.g., every 5 minutes)
29
+ current_time = datetime.now()
30
+ last_check = st.session_state.api_status.get("checked_at")
31
+ should_refresh = (
32
+ last_check is None or
33
+ (current_time - last_check).total_seconds() > 300 # 5 minutes
34
+ )
35
+
36
+ # Only make API call if needed or if user clicks refresh
37
+ refresh_status = st.button("🔄 Refresh Status")
38
+
39
+ if should_refresh or refresh_status:
40
+ try:
41
+ with st.spinner("Checking API status..."):
42
+ health_status = api_client.get_health()
43
+
44
+ st.session_state.api_status = {
45
+ "checked_at": current_time,
46
+ "status": health_status.get("status", "").lower(),
47
+ "error": None
48
+ }
49
+
50
+ if st.session_state.api_status["status"] == "ok":
51
+ st.session_state.api_connected = True
52
+ else:
53
+ st.session_state.api_connected = False
54
+
55
+ except Exception as e:
56
+ st.session_state.api_status = {
57
+ "checked_at": current_time,
58
+ "status": "error",
59
+ "error": str(e)
60
+ }
61
+ st.session_state.api_connected = False
62
+
63
+ # Display the status based on session state
64
+ if st.session_state.api_status["status"] == "ok":
65
+ st.success("API Connected")
66
+ if "last_request_time" in st.session_state:
67
+ st.write(f"Last Request: {st.session_state.last_request_time:.2f}s")
68
+ elif st.session_state.api_status["status"] == "error":
69
+ st.error(f"API Connection Error: {st.session_state.api_status['error']}")
70
+ else:
71
+ st.error("API Not Responding Correctly")
72
+
73
+ st.markdown("---")
74
+
75
+ # Navigation section with callback functions to avoid reruns
76
+ st.subheader("Navigation")
77
+
78
+ def set_page(page_name: str) -> None:
79
+ """Set the current page in session state.
80
+
81
+ Args:
82
+ page_name: Name of the page to navigate to
83
+ """
84
+ st.session_state.current_page = page_name
85
+
86
+ # Use on_click to avoid page reruns
87
+ st.button(
88
+ "🔍 Single Email Analysis",
89
+ use_container_width=True,
90
+ on_click=set_page,
91
+ args=("single_email",)
92
+ )
93
+
94
+ st.button(
95
+ "📊 Batch Email Analysis",
96
+ use_container_width=True,
97
+ on_click=set_page,
98
+ args=("batch_email",)
99
+ )
100
+
101
+ st.button(
102
+ "📚 About",
103
+ use_container_width=True,
104
+ on_click=set_page,
105
+ args=("about",)
106
+ )
107
+
108
+ st.markdown("---")
109
+
110
+ # About section in sidebar
111
+ st.caption(f"Email Spam Classifier v{api_client.config.APP_VERSION}")
112
+ st.caption(f"© {datetime.now().year} Email Security Team")
app/config.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Dict, Any
3
+ from dotenv import load_dotenv
4
+
5
+ # Load environment variables from .env file if it exists
6
+ load_dotenv()
7
+
8
+ class AppConfig:
9
+ """Configuration for the Streamlit application."""
10
+
11
+ def __init__(self):
12
+ """Initialize the application configuration."""
13
+ # API Settings
14
+ self.API_BASE_URL = os.getenv("API_BASE_URL", "http://localhost:8000")
15
+ self.API_TIMEOUT = int(os.getenv("API_TIMEOUT", "30")) # seconds
16
+
17
+ # App Settings
18
+ self.APP_NAME = "Email Spam Classifier"
19
+ self.APP_VERSION = "1.0.0"
20
+
21
+ # UI Settings
22
+ self.THEME_COLOR = "#4B8BBE" # Python blue
23
+ self.SECONDARY_COLOR = "#FFE873" # Python yellow
24
+
25
+ # Cache settings
26
+ self.CACHE_TTL = int(os.getenv("CACHE_TTL", "3600")) # seconds
27
+
28
+ # Debug mode
29
+ self.DEBUG = os.getenv("DEBUG", "False").lower() in ("true", "1", "t")
30
+
31
+ def as_dict(self) -> Dict[str, Any]:
32
+ """Return the configuration as a dictionary.
33
+
34
+ Returns:
35
+ Dictionary containing all configuration values
36
+ """
37
+ return {
38
+ "API_BASE_URL": self.API_BASE_URL,
39
+ "API_TIMEOUT": self.API_TIMEOUT,
40
+ "APP_NAME": self.APP_NAME,
41
+ "APP_VERSION": self.APP_VERSION,
42
+ "THEME_COLOR": self.THEME_COLOR,
43
+ "SECONDARY_COLOR": self.SECONDARY_COLOR,
44
+ "CACHE_TTL": self.CACHE_TTL,
45
+ "DEBUG": self.DEBUG,
46
+ }
app/main.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from typing import Dict, Any, Callable
3
+
4
+ from app.api_client import APIClient
5
+ from app.config import AppConfig
6
+ from app.utils.ui_elements import load_css
7
+
8
+ # Initialize configuration
9
+ config = AppConfig()
10
+
11
+ # Page configuration
12
+ st.set_page_config(
13
+ page_title=config.APP_NAME,
14
+ page_icon="📧",
15
+ layout="wide",
16
+ initial_sidebar_state="expanded"
17
+ )
18
+
19
+ # Load custom CSS
20
+ load_css()
21
+
22
+ # Initialize API client
23
+ @st.cache_resource
24
+ def get_api_client() -> APIClient:
25
+ """Create and cache the API client instance.
26
+
27
+ Returns:
28
+ Initialized API client
29
+ """
30
+ return APIClient(base_url=config.API_BASE_URL)
31
+
32
+ api_client = get_api_client()
33
+
34
+ # Define pages with their metadata
35
+ home_page = st.Page(
36
+ page="views/home.py",
37
+ title="Home",
38
+ icon="🏠",
39
+ )
40
+
41
+ predictor_page = st.Page(
42
+ page="views/predictor.py",
43
+ title="Predictor",
44
+ icon="📧",
45
+ )
46
+
47
+ # Set up navigation
48
+ pages = st.navigation(
49
+ {
50
+ "Home": [home_page],
51
+ "Predictor": [predictor_page],
52
+ }
53
+ )
54
+
55
+ # Run the selected page
56
+ if __name__ == "__main__":
57
+ pages.run()
app/templates/home.html ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Email Spam Classifier</title>
7
+ <style>
8
+ :root {
9
+ --primary-color: #3498db;
10
+ --accent-color: #2ecc71;
11
+ --dark-bg: #121920;
12
+ --card-bg: #1e2a38;
13
+ --text-primary: #e1e1e1;
14
+ --text-secondary: #a0a0a0;
15
+ --card-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
16
+ --highlight: rgba(52, 152, 219, 0.1);
17
+ --footer-bg: #18222e;
18
+ }
19
+
20
+ * {
21
+ box-sizing: border-box;
22
+ margin: 0;
23
+ padding: 0;
24
+ }
25
+
26
+ body {
27
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
28
+ background-color: var(--dark-bg);
29
+ color: var(--text-primary);
30
+ line-height: 1.6;
31
+ overflow-x: hidden;
32
+ }
33
+
34
+ .container {
35
+ width: 100%;
36
+ max-width: 1200px;
37
+ margin: 0 auto;
38
+ padding: 2rem;
39
+ }
40
+
41
+ .header {
42
+ text-align: center;
43
+ margin-bottom: 3rem;
44
+ position: relative;
45
+ }
46
+
47
+ .header h1 {
48
+ font-size: 3.5rem;
49
+ font-weight: 700;
50
+ color: var(--text-primary);
51
+ margin-bottom: 0.5rem;
52
+ letter-spacing: -0.5px;
53
+ position: relative;
54
+ display: inline-block;
55
+ }
56
+
57
+ .header h1::after {
58
+ content: '';
59
+ display: block;
60
+ margin: 0.5rem auto 0;
61
+ width: 60%;
62
+ height: 4px;
63
+ border-radius: 2px;
64
+ background: linear-gradient(90deg, var(--primary-color), var(--accent-color));
65
+ }
66
+
67
+ .header p {
68
+ font-size: 1.2rem;
69
+ color: var(--text-secondary);
70
+ max-width: 700px;
71
+ margin: 0 auto;
72
+ }
73
+
74
+ .features-grid {
75
+ display: grid;
76
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
77
+ gap: 2rem;
78
+ }
79
+
80
+ .feature-card {
81
+ background-color: var(--card-bg);
82
+ padding: 2rem;
83
+ border-radius: 10px;
84
+ box-shadow: var(--card-shadow);
85
+ transition: transform 0.2s, box-shadow 0.2s;
86
+ cursor: pointer;
87
+ border: 1px solid transparent;
88
+ }
89
+
90
+ .feature-card:hover {
91
+ transform: translateY(-8px) scale(1.03);
92
+ box-shadow: 0 12px 24px rgba(52, 152, 219, 0.15);
93
+ border: 1px solid var(--primary-color);
94
+ background-color: var(--highlight);
95
+ }
96
+
97
+ .feature-card h3 {
98
+ font-size: 1.8rem;
99
+ color: var(--primary-color);
100
+ }
101
+
102
+ .feature-card p {
103
+ color: var(--text-secondary);
104
+ }
105
+
106
+ .footer {
107
+ text-align: center;
108
+ margin-top: 3rem;
109
+ padding: 2rem 0 1rem 0;
110
+ background: var(--footer-bg);
111
+ border-radius: 10px;
112
+ box-shadow: 0 2px 8px rgba(0,0,0,0.08);
113
+ }
114
+
115
+ .footer h3 {
116
+ margin-bottom: 0.5rem;
117
+ color: var(--accent-color);
118
+ }
119
+
120
+ .footer p {
121
+ margin-bottom: 1rem;
122
+ }
123
+
124
+ .social-links {
125
+ margin-top: 1rem;
126
+ display: flex;
127
+ justify-content: center;
128
+ gap: 1.5rem;
129
+ }
130
+
131
+ .social-link {
132
+ color: var(--primary-color);
133
+ text-decoration: none;
134
+ font-weight: 600;
135
+ padding: 0.5rem 1.2rem;
136
+ border-radius: 5px;
137
+ background: rgba(52, 152, 219, 0.08);
138
+ transition: background 0.2s, color 0.2s, box-shadow 0.2s;
139
+ box-shadow: 0 2px 8px rgba(52,152,219,0.05);
140
+ }
141
+
142
+ .social-link:hover {
143
+ background: var(--primary-color);
144
+ color: #fff;
145
+ box-shadow: 0 4px 16px rgba(52,152,219,0.15);
146
+ }
147
+
148
+ /* Responsive tweaks */
149
+ @media (max-width: 700px) {
150
+ .header h1 {
151
+ font-size: 2.2rem;
152
+ }
153
+
154
+ .container {
155
+ padding: 1rem;
156
+ }
157
+
158
+ .features-grid {
159
+ gap: 1rem;
160
+ }
161
+
162
+ .feature-card {
163
+ padding: 1.2rem;
164
+ }
165
+
166
+ .footer {
167
+ padding: 1rem 0 0.5rem 0;
168
+ }
169
+ }
170
+ </style>
171
+ </head>
172
+ <body>
173
+ <div class="container">
174
+ <div class="header">
175
+ <h1>Email Spam Classifier</h1>
176
+ <p>Advanced machine learning solution for detecting unwanted emails</p>
177
+ </div>
178
+
179
+
180
+ <div class="features-grid">
181
+ <div class="feature-card">
182
+ <h3>High Accuracy Detection</h3>
183
+ <p>Leverages advanced ML algorithms to provide highly accurate spam detection with minimal false positives.</p>
184
+ </div>
185
+ <div class="feature-card">
186
+ <h3>Real-time Analysis</h3>
187
+ <p>Process emails in real-time to get instant results about the legitimacy of your messages.</p>
188
+ </div>
189
+ <div class="feature-card">
190
+ <h3>User-friendly Interface</h3>
191
+ <p>Simple and intuitive design that makes email analysis accessible to everyone.</p>
192
+ </div>
193
+ </div>
194
+
195
+ <div class="footer">
196
+ <h3>Developed by Qadeer Ahmad</h3>
197
+ <p>Data Science and Machine Learning enthusiast</p>
198
+ <div class="social-links">
199
+ <a href="https://github.com/mrqadeer" target="_blank" class="social-link">GitHub</a>
200
+ <a href="https://www.linkedin.com/in/qadeer-ahmad-3499a4205/" target="_blank" class="social-link">LinkedIn</a>
201
+ <a href="https://kaggle.com/mrqadeer" target="_blank" class="social-link">Kaggle</a>
202
+ </div>
203
+ </div>
204
+ </div>
205
+ </body>
206
+ </html>
app/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # This file makes the utils directory a Python package
app/utils/ui_elements.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from contextlib import contextmanager
3
+ from typing import Optional, List, Dict, Any, Generator, Iterator, TypeVar
4
+ import pandas as pd
5
+ import re
6
+
7
+ T = TypeVar('T')
8
+
9
+ def load_css() -> None:
10
+ """Load custom CSS styles for the application."""
11
+ css = """
12
+ <style>
13
+ .reportview-container .main .block-container {
14
+ padding-top: 1rem;
15
+ }
16
+ .stAlert > div {
17
+ padding-top: 0.5rem;
18
+ padding-bottom: 0.5rem;
19
+ }
20
+ footer {visibility: hidden;}
21
+ .css-12oz5g7 {padding-top: 0rem;}
22
+ .css-1d391kg {padding-top: 0rem;}
23
+
24
+ .spam-card {
25
+ padding: 1rem;
26
+ border-radius: 0.5rem;
27
+ margin-bottom: 1rem;
28
+ background-color: #f0f0f0;
29
+ border-left: 4px solid #FF4B4B;
30
+ }
31
+
32
+ .ham-card {
33
+ padding: 1rem;
34
+ border-radius: 0.5rem;
35
+ margin-bottom: 1rem;
36
+ background-color: #f0f0f0;
37
+ border-left: 4px solid #00CC96;
38
+ }
39
+
40
+ .custom-info-box {
41
+ padding: 1rem;
42
+ border-radius: 0.5rem;
43
+ margin: 1rem 0;
44
+ background-color: #e6f3ff;
45
+ border: 1px solid #b3d9ff;
46
+ }
47
+
48
+ .batch-results-table {
49
+ width: 100%;
50
+ margin: 1rem 0;
51
+ }
52
+
53
+ .batch-progress {
54
+ margin: 1rem 0;
55
+ }
56
+ </style>
57
+ """
58
+ st.markdown(css, unsafe_allow_html=True)
59
+
60
+
61
+ def show_success(message: str) -> None:
62
+ """Show a success message.
63
+
64
+ Args:
65
+ message: The success message to display
66
+ """
67
+ st.success(message)
68
+
69
+
70
+ def show_info(message: str) -> None:
71
+ """Show an info message.
72
+
73
+ Args:
74
+ message: The info message to display
75
+ """
76
+ st.info(message)
77
+
78
+
79
+ def show_warning(message: str) -> None:
80
+ """Show a warning message.
81
+
82
+ Args:
83
+ message: The warning message to display
84
+ """
85
+ st.warning(message)
86
+
87
+
88
+ def show_error(message: str) -> None:
89
+ """Show an error message.
90
+
91
+ Args:
92
+ message: The error message to display
93
+ """
94
+ st.error(message)
95
+
96
+
97
+ @contextmanager
98
+ def show_spinner(text: str = "Processing...") -> Iterator[None]:
99
+ """Context manager for showing a spinner during operations.
100
+
101
+ Args:
102
+ text: The text to display with the spinner
103
+ """
104
+ with st.spinner(text):
105
+ yield
106
+
107
+
108
+ def create_prediction_card(prediction: Dict[str, Any]) -> None:
109
+ """Create a custom HTML card for displaying predictions.
110
+
111
+ Args:
112
+ prediction: Dictionary containing prediction details
113
+ """
114
+ is_spam = prediction.get("is_spam", False)
115
+ probability = prediction.get("spam_probability", 0)
116
+ card_class = "spam-card" if is_spam else "ham-card"
117
+
118
+ html = f"""
119
+ <div class="{card_class}">
120
+ <h3>{"Spam" if is_spam else "Not Spam"} ({probability:.2%})</h3>
121
+ <p>{prediction.get("explanation", "")}</p>
122
+ </div>
123
+ """
124
+
125
+ st.markdown(html, unsafe_allow_html=True)
126
+
127
+
128
+ def render_metric_tile(
129
+ title: str,
130
+ value: str,
131
+ description: Optional[str] = None,
132
+ bg_color: str = "#1e2a38", # Darker background for better UI
133
+ title_color: str = "#e1e1e1", # Light text for dark background
134
+ value_color: str = "#ffffff", # White text for emphasis
135
+ border_color: Optional[str] = None
136
+ ) -> None:
137
+ """Render a metric tile with a title, value, and optional description.
138
+
139
+ Args:
140
+ title: Title of the metric
141
+ value: Value to display
142
+ description: Optional description text
143
+ bg_color: Background color of the tile
144
+ title_color: Color for the title text
145
+ value_color: Color for the value text
146
+ border_color: Optional border color
147
+ """
148
+ border_style = f"border-left: 3px solid {border_color};" if border_color else ""
149
+
150
+ # Enhanced animation and improved styling with professional font
151
+ st.markdown(f"""
152
+ <style>
153
+ @keyframes fadeIn {{
154
+ from {{ opacity: 0; transform: translateY(10px); }}
155
+ to {{ opacity: 1; transform: translateY(0); }}
156
+ }}
157
+ .metric-tile {{
158
+ animation: fadeIn 0.6s ease-out forwards;
159
+ background-color: {bg_color};
160
+ padding: 20px;
161
+ border-radius: 10px;
162
+ margin-bottom: 15px;
163
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
164
+ {border_style}
165
+ font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
166
+ transition: transform 0.3s ease, box-shadow 0.3s ease;
167
+ }}
168
+ .metric-tile:hover {{
169
+ transform: translateY(-3px);
170
+ box-shadow: 0 6px 12px rgba(0,0,0,0.15);
171
+ }}
172
+ .metric-title {{
173
+ margin: 0;
174
+ color: {title_color};
175
+ font-size: 1.1rem;
176
+ font-weight: 600;
177
+ letter-spacing: 0.3px;
178
+ }}
179
+ .metric-value {{
180
+ font-size: 28px;
181
+ font-weight: bold;
182
+ margin: 10px 0;
183
+ color: {value_color};
184
+ transition: color 0.3s ease;
185
+ }}
186
+ .metric-tile:hover .metric-value {{
187
+ color: #ffffff;
188
+ }}
189
+ .metric-desc {{
190
+ color: #a0a0a0;
191
+ font-size: 14px;
192
+ }}
193
+ </style>
194
+ <div class="metric-tile" style="animation-delay: 0.{id(title)}s;">
195
+ <h4 class="metric-title">{title}</h4>
196
+ <p class="metric-value">{value}</p>
197
+ {f'<small class="metric-desc">{description}</small>' if description else ""}
198
+ </div>
199
+ """, unsafe_allow_html=True)
200
+
201
+
202
+ def create_batch_interface() -> Optional[List[str]]:
203
+ """Create an interface for batch email uploads or manual entry.
204
+
205
+ Uses session state to store input values between reruns.
206
+
207
+ Returns:
208
+ List of email contents (List[str]) if valid, None otherwise
209
+ """
210
+ # Initialize session state for file uploader
211
+ if "uploaded_file" not in st.session_state:
212
+ st.session_state.uploaded_file = None
213
+
214
+ # Initialize session state for text area
215
+ if "batch_email_input" not in st.session_state:
216
+ st.session_state.batch_email_input = ""
217
+
218
+ with st.expander("Upload Emails for Batch Analysis", expanded=True):
219
+ st.write("The file should contain a column named 'email' or 'text' with the email content.")
220
+
221
+ uploaded_file = st.file_uploader(
222
+ "Choose a file",
223
+ type=["csv", "xlsx", "xls"],
224
+ help="Upload a CSV or Excel file with email content",
225
+ key="file_uploader"
226
+ )
227
+
228
+ # Update session state if file uploaded
229
+ if uploaded_file is not None:
230
+ st.session_state.uploaded_file = uploaded_file
231
+
232
+ with st.expander("Or write emails directly:", expanded=False):
233
+ email_input = st.text_area(
234
+ "Enter email content (use <start>email</end> or double line breaks to separate emails)",
235
+ height=200,
236
+ help="Paste multiple emails here, separated by <start>...</end> or double line breaks",
237
+ key="batch_email_input"
238
+ )
239
+
240
+ # Process the inputs
241
+ if st.session_state.uploaded_file is None and not email_input:
242
+ return None
243
+
244
+ # If file is uploaded, extract emails as list of str
245
+ if st.session_state.uploaded_file is not None:
246
+ try:
247
+ uploaded_file = st.session_state.uploaded_file
248
+ # Determine file type and read accordingly
249
+ if uploaded_file.name.endswith('.csv'):
250
+ df = pd.read_csv(uploaded_file)
251
+ else:
252
+ df = pd.read_excel(uploaded_file)
253
+
254
+ # Check for required columns
255
+ if 'email' in df.columns:
256
+ email_column = 'email'
257
+ elif 'text' in df.columns:
258
+ email_column = 'text'
259
+ else:
260
+ st.error("File must contain a column named 'email' or 'text'")
261
+ return None
262
+
263
+ # Preview the dataframe
264
+ with st.expander("Preview of uploaded data", expanded=True):
265
+ st.dataframe(df.head(5))
266
+
267
+ # Extract emails as list of str, drop NaN and strip whitespace
268
+ emails = df[email_column].dropna().astype(str).map(str.strip).tolist()
269
+ return emails
270
+
271
+ except Exception as e:
272
+ st.error(f"Error processing file: {str(e)}")
273
+ return None
274
+
275
+ # If text area is used, parse emails
276
+ if email_input:
277
+ emails = _parse_emails_from_text(email_input)
278
+ if not emails:
279
+ st.warning("No valid emails found in the input.")
280
+ return None
281
+ return emails
282
+
283
+ return None
284
+
285
+
286
+ def _parse_emails_from_text(email_input: str) -> List[str]:
287
+ """Parse emails from text input using either tags or line breaks.
288
+
289
+ Args:
290
+ email_input: Raw text containing multiple emails
291
+
292
+ Returns:
293
+ List of parsed emails
294
+ """
295
+ emails = []
296
+ # Try to extract using <start>...</end> tags
297
+ pattern = re.compile(r"<start>(.*?)</end>", re.DOTALL | re.IGNORECASE)
298
+ matches = pattern.findall(email_input)
299
+
300
+ if matches:
301
+ emails = [m.strip() for m in matches if m.strip()]
302
+ else:
303
+ # Fallback: split by double line breaks (2 or more newlines)
304
+ emails = [e.strip() for e in re.split(r"\n{2,}", email_input) if e.strip()]
305
+
306
+ return emails
307
+
308
+
309
+ def display_batch_results(results: List[Dict[str, Any]]) -> None:
310
+ """Display batch processing results.
311
+
312
+ Args:
313
+ results: List of dictionaries containing classification results
314
+ """
315
+ if not results:
316
+ st.warning("No results to display")
317
+ return
318
+
319
+ # Create DataFrame from results
320
+ df = pd.DataFrame(results)
321
+
322
+ # Add index as Email ID
323
+ df.insert(0, 'Email ID', range(1, len(df) + 1))
324
+
325
+ # Format probability as percentage
326
+ if 'spam_probability' in df.columns:
327
+ df['spam_probability'] = df['spam_probability'].apply(lambda x: f"{x*100:.2f}%")
328
+
329
+ # Calculate statistics
330
+ spam_count = sum(1 for result in results if result.get('is_spam', False))
331
+ ham_count = len(results) - spam_count
332
+
333
+ # Display metrics with improved styling
334
+ st.markdown("<h2 style='color:white;font-size:1.5rem;margin-bottom:1rem;'>Analysis Summary</h2>", unsafe_allow_html=True)
335
+ col1, col2, col3 = st.columns(3)
336
+
337
+ with col1:
338
+ render_metric_tile(
339
+ "Total Emails",
340
+ str(len(results)),
341
+ "Processed emails",
342
+ bg_color="#1e2a38",
343
+ title_color="#e1e1e1",
344
+ value_color="#3498db",
345
+ border_color="#3498db"
346
+ )
347
+ with col2:
348
+ render_metric_tile(
349
+ "Spam Detected",
350
+ str(spam_count),
351
+ f"{spam_count/len(results)*100:.1f}% of total",
352
+ bg_color="#1e2a38",
353
+ title_color="#e1e1e1",
354
+ value_color="#e74c3c",
355
+ border_color="#470501"
356
+ )
357
+ with col3:
358
+ render_metric_tile(
359
+ "Ham Detected",
360
+ str(ham_count),
361
+ f"{ham_count/len(results)*100:.1f}% of total",
362
+ bg_color="#1e2a38",
363
+ title_color="#e1e1e1",
364
+ value_color="#2ecc71",
365
+ border_color="#2ecc71"
366
+ )
367
+
368
+ # Display results table with improved heading
369
+ st.markdown("<h2 style='color:white;font-size:1.5rem;margin:1.5rem 0 1rem 0;'>Classification Results</h2>", unsafe_allow_html=True)
370
+
371
+ # Style the dataframe
372
+ st.dataframe(
373
+ df,
374
+ use_container_width=True,
375
+ hide_index=True,
376
+ )
377
+
378
+ # Download option
379
+ csv = df.to_csv(index=False).encode('utf-8')
380
+ st.download_button(
381
+ "Download Results as CSV",
382
+ csv,
383
+ "spam_classification_results.csv",
384
+ "text/csv",
385
+ key="download-csv"
386
+ )
387
+
388
+
389
+ def batch_progress_bar(iterable: List[T], label: str = "Processing emails...") -> Generator[T, None, None]:
390
+ """Display a progress bar for batch processing.
391
+
392
+ Args:
393
+ iterable: An iterable to process
394
+ label: Text label for the progress bar
395
+
396
+ Yields:
397
+ Items from the iterable one by one
398
+ """
399
+ progress_bar = st.progress(0)
400
+ total = len(iterable)
401
+
402
+ for i, item in enumerate(iterable):
403
+ yield item
404
+ progress_bar.progress((i + 1) / total)
app/views/__init__.py ADDED
File without changes
app/views/home.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pathlib
3
+ from typing import Optional
4
+
5
+ class HomePage:
6
+ """Class to handle home page functionality."""
7
+
8
+ def __init__(self):
9
+ """Initialize the HomePage class with necessary resources."""
10
+ self.title = "Email Spam Classifier"
11
+ self.description = "Analyze your emails to determine if they are spam or legitimate."
12
+ self.html_path = pathlib.Path(__file__).parent.parent / "templates" / "home.html"
13
+
14
+ def home_page(self) -> None:
15
+ """Render the home page content."""
16
+ try:
17
+ # Load the HTML file
18
+ with open(self.html_path, 'r', encoding='utf-8') as file:
19
+ html_content = file.read()
20
+
21
+ # Render HTML in Streamlit
22
+ st.html(html_content)
23
+ except FileNotFoundError:
24
+ st.error(f"HTML template not found at {self.html_path}")
25
+ except Exception as e:
26
+ st.error(f"Error loading home page: {str(e)}")
27
+
28
+
29
+ # Initialize the page only once
30
+ def get_homepage_instance() -> HomePage:
31
+ """Get or create a singleton instance of the HomePage class."""
32
+ if "homepage_instance" not in st.session_state:
33
+ st.session_state.homepage_instance = HomePage()
34
+ return st.session_state.homepage_instance
35
+
36
+
37
+ # Render the home page
38
+ home_page = get_homepage_instance().home_page()
app/views/predictor.py ADDED
@@ -0,0 +1,872 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pathlib
3
+ import pandas as pd
4
+ import io
5
+ from typing import Dict, Any, Optional, List
6
+ from datetime import datetime
7
+
8
+ from app.api_client import APIClient
9
+ from app.utils.ui_elements import (
10
+ create_batch_interface,
11
+ display_batch_results,
12
+ show_error,
13
+ show_info,
14
+ show_spinner,
15
+ show_success
16
+ )
17
+
18
+ class Predictor:
19
+ """Class to handle email spam prediction functionality."""
20
+
21
+ def __init__(self):
22
+ """Initialize the Predictor class with necessary resources."""
23
+ self.title = "Email Spam Classifier"
24
+ self.description = "Analyze your emails to determine if they are spam or legitimate."
25
+ self.html_path = pathlib.Path(__file__).parent.parent / "templates" / "predictor.html"
26
+ self.api_client = APIClient()
27
+
28
+ # Initialize session state variables if not present
29
+ if "prediction_result" not in st.session_state:
30
+ st.session_state.prediction_result = None
31
+
32
+ if "email_input" not in st.session_state:
33
+ st.session_state.email_input = ""
34
+
35
+ if "batch_results" not in st.session_state:
36
+ st.session_state.batch_results = None
37
+
38
+ # Add active tab tracking to prevent tab switching
39
+ if "active_tab" not in st.session_state:
40
+ st.session_state.active_tab = 0
41
+
42
+ # Add analysis in progress flag
43
+ if "analysis_in_progress" not in st.session_state:
44
+ st.session_state.analysis_in_progress = False
45
+
46
+ def predictor_page(self) -> None:
47
+ """Render the main predictor page with tabs for single and batch analysis."""
48
+ self._set_custom_styles()
49
+ self._show_page_header()
50
+
51
+ # Use the active tab from session state
52
+ tab_names = ["Single Email Analysis", "Batch Email Analysis"]
53
+ tabs = st.tabs(tab_names)
54
+ with tabs[0]:
55
+
56
+ self.single_email_analyzer()
57
+ with tabs[1]:
58
+ self.batch_email_analyzer()
59
+
60
+
61
+ def _set_custom_styles(self) -> None:
62
+ """Set custom CSS styles for the page."""
63
+ st.markdown("""
64
+ <style>
65
+ .main-title { font-size:2.5rem; font-weight:700; color:white; }
66
+ .desc { font-size:1.2rem; color:white; margin-bottom:1.5rem; }
67
+
68
+ /* Updated result card styling to match the image, with dark background */
69
+ .result-card {
70
+ border-radius: 10px;
71
+ padding: 1.5rem;
72
+ margin-top: 1rem;
73
+ transition: transform 0.3s ease, box-shadow 0.3s ease;
74
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
75
+ background: #1e2a38;
76
+ }
77
+ .result-card:hover {
78
+ transform: translateY(-3px);
79
+ box-shadow: 0 8px 15px rgba(0,0,0,0.2);
80
+ }
81
+ .spam {
82
+ border: 2px solid #e74c3c;
83
+ border-left: 6px solid #e74c3c;
84
+ }
85
+ .ham {
86
+ border: 2px solid #27ae60;
87
+ border-left: 6px solid #27ae60;
88
+ }
89
+ .confidence-bar {
90
+ height: 20px;
91
+ border-radius: 10px;
92
+ transition: width 0.8s ease-in-out;
93
+ background-image: linear-gradient(to right, rgba(255,255,255,0.2), rgba(255,255,255,0));
94
+ }
95
+ .confidence-value {
96
+ font-weight: 600;
97
+ transition: color 0.3s ease;
98
+ color: #e0e0e0;
99
+ }
100
+ .result-card:hover .confidence-value {
101
+ color: #fff;
102
+ }
103
+ .result-icon {
104
+ margin-right: 8px;
105
+ font-size: 1.5rem;
106
+ vertical-align: middle;
107
+ }
108
+
109
+ /* Alert level styling */
110
+ .alert-badge {
111
+ display: inline-block;
112
+ padding: 8px 16px;
113
+ border-radius: 20px;
114
+ font-weight: 700;
115
+ font-size: 0.9rem;
116
+ text-align: center;
117
+ margin: 8px 0;
118
+ text-transform: uppercase;
119
+ letter-spacing: 1px;
120
+ box-shadow: 0 2px 4px rgba(0,0,0,0.2);
121
+ }
122
+ .alert-low {
123
+ background: linear-gradient(135deg, #2ecc71, #27ae60);
124
+ color: white;
125
+ border: 1px solid #229954;
126
+ }
127
+ .alert-medium {
128
+ background: linear-gradient(135deg, #f39c12, #e67e22);
129
+ color: white;
130
+ border: 1px solid #d68910;
131
+ }
132
+ .alert-high {
133
+ background: linear-gradient(135deg, #e74c3c, #c0392b);
134
+ color: white;
135
+ border: 1px solid #a93226;
136
+ }
137
+ .alert-severe {
138
+ background: linear-gradient(135deg, #8e44ad, #6c3483);
139
+ color: white;
140
+ border: 1px solid #5b2c6f;
141
+ animation: pulse-severe 2s infinite;
142
+ }
143
+
144
+ @keyframes pulse-severe {
145
+ 0% { box-shadow: 0 0 0 0 rgba(142, 68, 173, 0.7); }
146
+ 70% { box-shadow: 0 0 0 10px rgba(142, 68, 173, 0); }
147
+ 100% { box-shadow: 0 0 0 0 rgba(142, 68, 173, 0); }
148
+ }
149
+
150
+ .risk-description {
151
+ background: rgba(255,255,255,0.1);
152
+ border-radius: 8px;
153
+ padding: 12px;
154
+ margin: 10px 0;
155
+ border-left: 4px solid #3498db;
156
+ color: #e0e0e0;
157
+ font-style: italic;
158
+ }
159
+
160
+ /* Batch results styling */
161
+ .batch-summary {
162
+ background: #2c3e50;
163
+ border-radius: 10px;
164
+ padding: 20px;
165
+ margin: 15px 0;
166
+ border: 1px solid #34495e;
167
+ }
168
+ .summary-metric {
169
+ display: inline-block;
170
+ margin: 5px 15px 5px 0;
171
+ padding: 8px 12px;
172
+ background: rgba(52, 152, 219, 0.2);
173
+ border-radius: 5px;
174
+ color: #ecf0f1;
175
+ font-weight: 500;
176
+ }
177
+ .alert-distribution {
178
+ display: flex;
179
+ flex-wrap: wrap;
180
+ gap: 10px;
181
+ margin-top: 15px;
182
+ }
183
+ .alert-count {
184
+ flex: 1;
185
+ min-width: 120px;
186
+ text-align: center;
187
+ padding: 10px;
188
+ border-radius: 8px;
189
+ font-weight: 600;
190
+ }
191
+
192
+ /* Add spinner animation and processing indicator */
193
+ @keyframes spinner {
194
+ to {transform: rotate(360deg);}
195
+ }
196
+ .processing-spinner {
197
+ width: 20px;
198
+ height: 20px;
199
+ border: 3px solid rgba(255,255,255,0.3);
200
+ border-radius: 50%;
201
+ border-top-color: #3498db;
202
+ animation: spinner 1s linear infinite;
203
+ display: inline-block;
204
+ margin-right: 10px;
205
+ vertical-align: middle;
206
+ }
207
+ .processing-text {
208
+ display: inline-block;
209
+ vertical-align: middle;
210
+ font-weight: 500;
211
+ }
212
+ .processing-container {
213
+ padding: 10px;
214
+ border-radius: 5px;
215
+ background: rgba(52, 152, 219, 0.1);
216
+ margin: 15px 0;
217
+ border: 1px solid rgba(52, 152, 219, 0.2);
218
+ display: flex;
219
+ align-items: center;
220
+ }
221
+
222
+ /* Custom button styles */
223
+ .stButton > button[kind="primary"] {
224
+ background-color: #3498db !important;
225
+ border-color: #3498db !important;
226
+ transition: background-color 0.3s ease, transform 0.2s ease !important;
227
+ }
228
+ .stButton > button[kind="primary"]:hover {
229
+ background-color: #2980b9 !important;
230
+ transform: translateY(-2px) !important;
231
+ box-shadow: 0 4px 8px rgba(0,0,0,0.1) !important;
232
+ }
233
+ .stButton > button[kind="primary"]:active {
234
+ transform: translateY(0) !important;
235
+ }
236
+ </style>
237
+ """, unsafe_allow_html=True)
238
+
239
+ def _show_page_header(self) -> None:
240
+ """Display the main page header."""
241
+ st.markdown('<div class="main-title">📧 Email Spam Classifier</div>', unsafe_allow_html=True)
242
+ st.markdown(f'<div class="desc">{self.description}</div>', unsafe_allow_html=True)
243
+ st.markdown("---")
244
+
245
+ def handle_clear_input(self) -> None:
246
+ """Clear the email input and prediction result."""
247
+ st.session_state.email_input = ""
248
+ st.session_state.prediction_result = None
249
+
250
+ def _get_alert_level_from_probability(self, spam_probability: float) -> str:
251
+ """
252
+ Calculate alert level from spam probability (fallback if backend doesn't provide it)
253
+
254
+ Args:
255
+ spam_probability: Probability that message is spam (0.0 - 1.0)
256
+
257
+ Returns:
258
+ Alert level: LOW, MEDIUM, HIGH, or SEVERE
259
+ """
260
+ if spam_probability < 0.4: # < 40%
261
+ return 'LOW'
262
+ elif spam_probability < 0.6: # 40-60%
263
+ return 'MEDIUM'
264
+ elif spam_probability < 0.8: # 60-80%
265
+ return 'HIGH'
266
+ else: # >= 80%
267
+ return 'SEVERE'
268
+
269
+ def _get_risk_description_from_level(self, alert_level: str) -> str:
270
+ """Get risk description for alert level (fallback if backend doesn't provide it)"""
271
+ descriptions = {
272
+ 'LOW': 'Low risk - spam probability less than 40%, likely legitimate message',
273
+ 'MEDIUM': 'Medium risk - spam probability 40-60%, requires review',
274
+ 'HIGH': 'High risk - spam probability 60-80%, likely spam, recommend blocking',
275
+ 'SEVERE': 'Severe risk - spam probability 80%+, almost certainly spam, block immediately'
276
+ }
277
+ return descriptions.get(alert_level, 'Unknown risk level')
278
+
279
+ def _enhance_api_result(self, result: Dict[str, Any]) -> Dict[str, Any]:
280
+ """
281
+ Enhance API result with alert level if missing
282
+
283
+ Args:
284
+ result: API response result
285
+
286
+ Returns:
287
+ Enhanced result with alert level and metadata
288
+ """
289
+ # Check if alert_level is missing and calculate it
290
+ if 'alert_level' not in result:
291
+ spam_probability = result.get('spam_probability', 0.0)
292
+ result['alert_level'] = self._get_alert_level_from_probability(spam_probability)
293
+
294
+ # Check if risk_description is missing and calculate it
295
+ if 'risk_description' not in result:
296
+ result['risk_description'] = self._get_risk_description_from_level(result['alert_level'])
297
+
298
+ # Check if confidence_score is missing and calculate it
299
+ if 'confidence_score' not in result:
300
+ spam_probability = result.get('spam_probability', 0.0)
301
+ result['confidence_score'] = max(spam_probability, 1 - spam_probability)
302
+
303
+ return result
304
+
305
+ def handle_email_analysis(self) -> None:
306
+ """Process the email analysis when the analyze button is clicked."""
307
+ if not st.session_state.email_input:
308
+ show_info("Please enter email content to analyze.")
309
+ return
310
+
311
+ # Set the progress indicator
312
+ st.session_state.analysis_in_progress = True
313
+
314
+ with show_spinner("Analyzing email content..."):
315
+ try:
316
+ result = self.api_client.classify_email(st.session_state.email_input)
317
+ # Enhance result with alert level if missing
318
+ enhanced_result = self._enhance_api_result(result)
319
+ st.session_state.prediction_result = enhanced_result
320
+
321
+ # Debug logging
322
+ st.write(f"**Debug - API Response:**")
323
+ st.json(enhanced_result)
324
+
325
+ except Exception as e:
326
+ show_error(f"Error: {str(e)}")
327
+ finally:
328
+ st.session_state.analysis_in_progress = False
329
+
330
+ def single_email_analyzer(self) -> None:
331
+ """Function to handle single email analysis."""
332
+ st.subheader("Single Email Analysis")
333
+ st.write("Analyze an individual email to determine if it's spam or legitimate.")
334
+
335
+ # Example/placeholder text
336
+ example_email = (
337
+ "Dear user,\n\nCongratulations! You've won a $1000 gift card. "
338
+ "Click the link below to claim your prize.\n\nBest regards,\nSpammy Corp"
339
+ )
340
+
341
+ # Input area for email content
342
+ st.text_area(
343
+ "Enter email content to analyze",
344
+ height=200,
345
+ key="email_input",
346
+ placeholder=example_email
347
+ )
348
+
349
+ st.caption("💡 Tip: Paste the full email body for best results.")
350
+
351
+ col1, col2 = st.columns([1, 3])
352
+
353
+ with col1:
354
+ st.button(
355
+ "Analyze Email",
356
+ type="primary",
357
+ use_container_width=True,
358
+ on_click=self.handle_email_analysis
359
+ )
360
+
361
+ with col2:
362
+ st.button(
363
+ "Clear",
364
+ use_container_width=True,
365
+ on_click=self.handle_clear_input
366
+ )
367
+
368
+ # Show processing indicator if analysis is in progress
369
+ if st.session_state.analysis_in_progress:
370
+ st.markdown("""
371
+ <div class="processing-container">
372
+ <div class="processing-spinner"></div>
373
+ <div class="processing-text">Processing your email... Please wait.</div>
374
+ </div>
375
+ """, unsafe_allow_html=True)
376
+
377
+ # Display results if available
378
+ if st.session_state.prediction_result:
379
+ self._display_analysis_results(st.session_state.prediction_result)
380
+
381
+ def _get_alert_styling(self, alert_level: str) -> Dict[str, str]:
382
+ """Get styling information for alert level display.
383
+
384
+ Args:
385
+ alert_level: Alert level (LOW, MEDIUM, HIGH, SEVERE)
386
+
387
+ Returns:
388
+ Dictionary with styling information
389
+ """
390
+ alert_styles = {
391
+ 'LOW': {
392
+ 'class': 'alert-low',
393
+ 'icon': '✅',
394
+ 'color': '#27ae60',
395
+ 'bg_color': '#1e6e39'
396
+ },
397
+ 'MEDIUM': {
398
+ 'class': 'alert-medium',
399
+ 'icon': '⚠️',
400
+ 'color': '#f39c12',
401
+ 'bg_color': '#6e4a1e'
402
+ },
403
+ 'HIGH': {
404
+ 'class': 'alert-high',
405
+ 'icon': '🚨',
406
+ 'color': '#e74c3c',
407
+ 'bg_color': '#6e2020'
408
+ },
409
+ 'SEVERE': {
410
+ 'class': 'alert-severe',
411
+ 'icon': '🔥',
412
+ 'color': '#8e44ad',
413
+ 'bg_color': '#4a1e6e'
414
+ }
415
+ }
416
+ return alert_styles.get(alert_level, alert_styles['LOW'])
417
+
418
+ def _create_single_prediction_csv(self, result: Dict[str, Any], email_text: str) -> bytes:
419
+ """
420
+ Create CSV data for single prediction result
421
+
422
+ Args:
423
+ result: Prediction result dictionary
424
+ email_text: Original email text
425
+
426
+ Returns:
427
+ CSV data as bytes
428
+ """
429
+ data = {
430
+ 'email_text': [email_text],
431
+ 'classification': [result.get('classification', 'Unknown')],
432
+ 'is_spam': [result.get('is_spam', False)],
433
+ 'spam_probability': [result.get('spam_probability', 0.0)],
434
+ 'alert_level': [result.get('alert_level', 'LOW')],
435
+ 'confidence_score': [result.get('confidence_score', 0.0)],
436
+ 'risk_description': [result.get('risk_description', 'No description')],
437
+ 'timestamp': [datetime.now().strftime('%Y-%m-%d %H:%M:%S')]
438
+ }
439
+
440
+ df = pd.DataFrame(data)
441
+ csv_buffer = io.StringIO()
442
+ df.to_csv(csv_buffer, index=False)
443
+ return csv_buffer.getvalue().encode('utf-8')
444
+
445
+ def _create_batch_predictions_csv(self, results: List[Dict[str, Any]], emails: List[str]) -> bytes:
446
+ """
447
+ Create CSV data for batch prediction results
448
+
449
+ Args:
450
+ results: List of prediction result dictionaries
451
+ emails: List of original email texts
452
+
453
+ Returns:
454
+ CSV data as bytes
455
+ """
456
+ data = {
457
+ 'email_number': [i + 1 for i in range(len(results))],
458
+ 'email_text': emails[:len(results)], # Ensure same length
459
+ 'classification': [r.get('classification', 'Unknown') for r in results],
460
+ 'is_spam': [r.get('is_spam', False) for r in results],
461
+ 'spam_probability': [r.get('spam_probability', 0.0) for r in results],
462
+ 'alert_level': [r.get('alert_level', 'LOW') for r in results],
463
+ 'confidence_score': [r.get('confidence_score', 0.0) for r in results],
464
+ 'risk_description': [r.get('risk_description', 'No description') for r in results],
465
+ 'timestamp': [datetime.now().strftime('%Y-%m-%d %H:%M:%S')] * len(results)
466
+ }
467
+
468
+ df = pd.DataFrame(data)
469
+ csv_buffer = io.StringIO()
470
+ df.to_csv(csv_buffer, index=False)
471
+ return csv_buffer.getvalue().encode('utf-8')
472
+
473
+ def _display_analysis_results(self, result: Dict[str, Any]) -> None:
474
+ """Display the analysis results in a styled card with alert levels.
475
+
476
+ Args:
477
+ result: Dictionary containing the prediction results
478
+ """
479
+ st.subheader("Analysis Results")
480
+ is_spam = result["is_spam"]
481
+ confidence = result['spam_probability'] * 100
482
+ alert_level = result.get('alert_level', 'LOW')
483
+ risk_description = result.get('risk_description', 'Risk assessment unavailable')
484
+ confidence_score = result.get('confidence_score', confidence / 100) * 100
485
+
486
+ card_class = "spam" if is_spam else "ham"
487
+ label = "SPAM" if is_spam else "HAM (Not Spam)"
488
+ icon = "⚠️" if is_spam else "✅"
489
+ card_color = "#e74c3c" if is_spam else "#27ae60"
490
+ text_color = "#fff"
491
+
492
+ # Get alert styling
493
+ alert_style = self._get_alert_styling(alert_level)
494
+
495
+ st.markdown(
496
+ f"""
497
+ <div class="result-card {card_class}">
498
+ <h2 style="margin-bottom:0.5rem;color:{'#e74c3c' if is_spam else '#27ae60'};display:flex;align-items:center;">
499
+ <span class="result-icon">{icon}</span> {label}
500
+ </h2>
501
+ <div style="display:flex;align-items:center;margin:10px 0;">
502
+ <div class="alert-badge {alert_style['class']}">
503
+ {alert_style['icon']} {alert_level} Risk
504
+ </div>
505
+ </div>
506
+ <p style="font-size:1.2rem;margin:0.5rem 0 1rem 0;color:#e0e0e0;">
507
+ <b>Spam Probability:</b> <span class="confidence-value">{confidence:.2f}%</span><br>
508
+ <b>Confidence Score:</b> <span class="confidence-value">{confidence_score:.2f}%</span>
509
+ </p>
510
+ <div style="background:#e0e0e0;border-radius:10px;padding:1px;margin-bottom:0.5rem;">
511
+ <div class="confidence-bar" style="width:{confidence}%;background:{card_color};"></div>
512
+ </div>
513
+ <div class="risk-description">
514
+ <strong>Risk Assessment:</strong> {risk_description}
515
+ </div>
516
+ </div>
517
+ """,
518
+ unsafe_allow_html=True
519
+ )
520
+
521
+ # Show appropriate message based on alert level
522
+ if alert_level in ['HIGH', 'SEVERE']:
523
+ st.markdown(f"""
524
+ <div style="background:{alert_style['bg_color']};color:white;padding:15px;border-radius:8px;margin-top:15px;font-weight:500;display:flex;align-items:center;border-left:5px solid {alert_style['color']};">
525
+ <span style="margin-right:15px;font-size:1.5rem;">{alert_style['icon']}</span>
526
+ <div>
527
+ <strong>{alert_level} RISK DETECTED!</strong><br>
528
+ <span style="font-size:0.9rem;opacity:0.9;">{risk_description}</span>
529
+ </div>
530
+ </div>
531
+ """, unsafe_allow_html=True)
532
+ elif alert_level == 'MEDIUM':
533
+ st.markdown(f"""
534
+ <div style="background:{alert_style['bg_color']};color:white;padding:15px;border-radius:8px;margin-top:15px;font-weight:500;display:flex;align-items:center;border-left:5px solid {alert_style['color']};">
535
+ <span style="margin-right:15px;font-size:1.5rem;">{alert_style['icon']}</span>
536
+ <div>
537
+ <strong>Medium Risk - Review Recommended</strong><br>
538
+ <span style="font-size:0.9rem;opacity:0.9;">{risk_description}</span>
539
+ </div>
540
+ </div>
541
+ """, unsafe_allow_html=True)
542
+ else:
543
+ st.markdown(f"""
544
+ <div style="background:{alert_style['bg_color']};color:white;padding:15px;border-radius:8px;margin-top:15px;font-weight:500;display:flex;align-items:center;border-left:5px solid {alert_style['color']};">
545
+ <span style="margin-right:15px;font-size:1.5rem;">{alert_style['icon']}</span>
546
+ <div>
547
+ <strong>Low Risk - Appears Safe</strong><br>
548
+ <span style="font-size:0.9rem;opacity:0.9;">{risk_description}</span>
549
+ </div>
550
+ </div>
551
+ """, unsafe_allow_html=True)
552
+
553
+ # Add download button for single prediction
554
+ st.markdown("---")
555
+ col1, col2, col3 = st.columns([2, 1, 1])
556
+
557
+ with col2:
558
+ csv_data = self._create_single_prediction_csv(result, st.session_state.email_input)
559
+ st.download_button(
560
+ label="📥 Download Result",
561
+ data=csv_data,
562
+ file_name=f"spam_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
563
+ mime="text/csv",
564
+ use_container_width=True
565
+ )
566
+
567
+ def handle_batch_analysis(self) -> None:
568
+ """Process batch email analysis when the analyze button is clicked."""
569
+ emails = st.session_state.get("batch_emails")
570
+
571
+ if not emails:
572
+ show_info("Please upload or enter emails to analyze.")
573
+ return
574
+
575
+ # Set the progress indicator and ensure we stay on batch tab
576
+ st.session_state.analysis_in_progress = True
577
+ st.session_state.active_tab = 1
578
+
579
+ with show_spinner("Analyzing emails..."):
580
+ try:
581
+ # Create a progress bar
582
+ progress_bar = st.progress(0)
583
+ results = []
584
+
585
+ # Process each email with visible progress
586
+ for i, email in enumerate(emails):
587
+ try:
588
+ result = self.api_client.classify_email(email)
589
+ # Enhance result with alert level if missing
590
+ enhanced_result = self._enhance_api_result(result)
591
+ results.append(enhanced_result)
592
+ except Exception as e:
593
+ # Create a fallback result
594
+ fallback_result = {
595
+ "is_spam": False,
596
+ "spam_probability": 0.0,
597
+ "classification": "HAM",
598
+ "alert_level": "LOW",
599
+ "risk_description": f"Error: {str(e)}",
600
+ "confidence_score": 0.0,
601
+ "error": True
602
+ }
603
+ results.append(fallback_result)
604
+ # Update progress
605
+ progress_bar.progress((i + 1) / len(emails))
606
+
607
+ st.session_state.batch_results = results
608
+ except Exception as e:
609
+ show_error(f"Error: {str(e)}")
610
+ finally:
611
+ st.session_state.analysis_in_progress = False
612
+
613
+ def batch_email_analyzer(self) -> None:
614
+ """Function to handle batch email analysis."""
615
+ st.subheader("Batch Email Analysis")
616
+ st.write("Analyze multiple emails at once to determine if they are spam or legitimate.")
617
+
618
+ emails = create_batch_interface()
619
+ if emails:
620
+ st.session_state.batch_emails = emails
621
+
622
+ analyze_button = st.button(
623
+ "Analyze Emails",
624
+ type="primary",
625
+ use_container_width=True,
626
+ key="analyze_batch_btn",
627
+ disabled=st.session_state.analysis_in_progress
628
+ )
629
+
630
+ if analyze_button:
631
+ self.handle_batch_analysis()
632
+
633
+ # Show processing indicator if analysis is in progress
634
+ if st.session_state.analysis_in_progress:
635
+ st.markdown("""
636
+ <div class="processing-container">
637
+ <div class="processing-spinner"></div>
638
+ <div class="processing-text">Processing batch emails... Please wait.</div>
639
+ </div>
640
+ """, unsafe_allow_html=True)
641
+
642
+ # Display batch results if available
643
+ if st.session_state.batch_results:
644
+ self._display_batch_results_with_alerts(st.session_state.batch_results)
645
+
646
+ def _display_batch_results_with_alerts(self, results: List[Dict[str, Any]]) -> None:
647
+ """Display batch results with alert level information.
648
+
649
+ Args:
650
+ results: List of prediction results
651
+ """
652
+ st.subheader("Batch Analysis Results")
653
+
654
+ # Calculate summary statistics
655
+ total_emails = len(results)
656
+ spam_count = sum(1 for r in results if r.get('is_spam', False))
657
+ ham_count = total_emails - spam_count
658
+
659
+ # Count alert levels
660
+ alert_counts = {'LOW': 0, 'MEDIUM': 0, 'HIGH': 0, 'SEVERE': 0}
661
+ for result in results:
662
+ alert_level = result.get('alert_level', 'LOW')
663
+ if alert_level in alert_counts:
664
+ alert_counts[alert_level] += 1
665
+
666
+ # Display summary with download button
667
+ col1, col2 = st.columns([3, 1])
668
+
669
+ with col1:
670
+ st.markdown(f"""
671
+ <div class="batch-summary">
672
+ <h3 style="color:#ecf0f1;margin-bottom:15px;">📊 Analysis Summary</h3>
673
+ <div>
674
+ <span class="summary-metric">📧 Total: {total_emails}</span>
675
+ <span class="summary-metric">🚨 Spam: {spam_count}</span>
676
+ <span class="summary-metric">✅ Ham: {ham_count}</span>
677
+ <span class="summary-metric">📈 Spam Rate: {(spam_count/total_emails*100):.1f}%</span>
678
+ </div>
679
+ <h4 style="color:#ecf0f1;margin:20px 0 10px 0;">🎯 Alert Level Distribution</h4>
680
+ <div class="alert-distribution">
681
+ <div class="alert-count" style="background:#1e6e39;border:1px solid #27ae60;">
682
+ <div style="font-size:1.5rem;">✅</div>
683
+ <div>LOW</div>
684
+ <div style="font-size:1.2rem;font-weight:700;">{alert_counts['LOW']}</div>
685
+ </div>
686
+ <div class="alert-count" style="background:#6e4a1e;border:1px solid #f39c12;">
687
+ <div style="font-size:1.5rem;">⚠️</div>
688
+ <div>MEDIUM</div>
689
+ <div style="font-size:1.2rem;font-weight:700;">{alert_counts['MEDIUM']}</div>
690
+ </div>
691
+ <div class="alert-count" style="background:#6e2020;border:1px solid #e74c3c;">
692
+ <div style="font-size:1.5rem;">🚨</div>
693
+ <div>HIGH</div>
694
+ <div style="font-size:1.2rem;font-weight:700;">{alert_counts['HIGH']}</div>
695
+ </div>
696
+ <div class="alert-count" style="background:#4a1e6e;border:1px solid #8e44ad;">
697
+ <div style="font-size:1.5rem;">🔥</div>
698
+ <div>SEVERE</div>
699
+ <div style="font-size:1.2rem;font-weight:700;">{alert_counts['SEVERE']}</div>
700
+ </div>
701
+ </div>
702
+ </div>
703
+ """, unsafe_allow_html=True)
704
+
705
+ with col2:
706
+ # Download button for batch results
707
+ st.markdown("<br><br>", unsafe_allow_html=True) # Add some spacing
708
+ emails = st.session_state.get("batch_emails", [""] * len(results))
709
+ csv_data = self._create_batch_predictions_csv(results, emails)
710
+ st.download_button(
711
+ label="📥 Download All Results",
712
+ data=csv_data,
713
+ file_name=f"batch_spam_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
714
+ mime="text/csv",
715
+ use_container_width=True,
716
+ type="primary"
717
+ )
718
+
719
+ # Additional download options
720
+ st.markdown("<br>", unsafe_allow_html=True)
721
+
722
+ # Download only SPAM results
723
+ spam_results = [r for r in results if r.get('is_spam', False)]
724
+ if spam_results:
725
+ spam_emails = [emails[i] for i, r in enumerate(results) if r.get('is_spam', False)]
726
+ spam_csv_data = self._create_batch_predictions_csv(spam_results, spam_emails)
727
+ st.download_button(
728
+ label="🚨 Download SPAM Only",
729
+ data=spam_csv_data,
730
+ file_name=f"spam_only_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
731
+ mime="text/csv",
732
+ use_container_width=True
733
+ )
734
+
735
+ # Download HIGH/SEVERE risk only
736
+ high_risk_results = [r for r in results if r.get('alert_level', 'LOW') in ['HIGH', 'SEVERE']]
737
+ if high_risk_results:
738
+ high_risk_emails = [emails[i] for i, r in enumerate(results)
739
+ if r.get('alert_level', 'LOW') in ['HIGH', 'SEVERE']]
740
+ high_risk_csv_data = self._create_batch_predictions_csv(high_risk_results, high_risk_emails)
741
+ st.download_button(
742
+ label="⚠️ Download High Risk",
743
+ data=high_risk_csv_data,
744
+ file_name=f"high_risk_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
745
+ mime="text/csv",
746
+ use_container_width=True
747
+ )
748
+
749
+ # Display individual results
750
+ st.markdown("### 📋 Individual Results")
751
+
752
+ # Filter options
753
+ col1, col2, col3 = st.columns(3)
754
+ with col1:
755
+ show_filter = st.selectbox(
756
+ "Filter by classification:",
757
+ ["All", "Spam Only", "Ham Only"],
758
+ key="batch_filter"
759
+ )
760
+ with col2:
761
+ alert_filter = st.selectbox(
762
+ "Filter by alert level:",
763
+ ["All Levels", "LOW", "MEDIUM", "HIGH", "SEVERE"],
764
+ key="alert_filter"
765
+ )
766
+ with col3:
767
+ results_per_page = st.selectbox(
768
+ "Results per page:",
769
+ [10, 25, 50, 100],
770
+ index=1,
771
+ key="results_per_page"
772
+ )
773
+
774
+ # Apply filters
775
+ filtered_results = []
776
+ for i, result in enumerate(results):
777
+ # Classification filter
778
+ if show_filter == "Spam Only" and not result.get('is_spam', False):
779
+ continue
780
+ elif show_filter == "Ham Only" and result.get('is_spam', False):
781
+ continue
782
+
783
+ # Alert level filter
784
+ if alert_filter != "All Levels" and result.get('alert_level', 'LOW') != alert_filter:
785
+ continue
786
+
787
+ filtered_results.append((i, result))
788
+
789
+ if not filtered_results:
790
+ st.info("No results match the selected filters.")
791
+ return
792
+
793
+ # Pagination
794
+ total_filtered = len(filtered_results)
795
+ total_pages = (total_filtered - 1) // results_per_page + 1
796
+
797
+ if total_pages > 1:
798
+ col1, col2, col3 = st.columns([1, 2, 1])
799
+ with col2:
800
+ page = st.selectbox(
801
+ f"Page (showing {total_filtered} results):",
802
+ range(1, total_pages + 1),
803
+ key="page_selector"
804
+ )
805
+ else:
806
+ page = 1
807
+
808
+ # Calculate pagination bounds
809
+ start_idx = (page - 1) * results_per_page
810
+ end_idx = min(start_idx + results_per_page, total_filtered)
811
+ page_results = filtered_results[start_idx:end_idx]
812
+
813
+ # Display filtered results for current page
814
+ for i, result in page_results:
815
+ is_spam = result.get('is_spam', False)
816
+ spam_prob = result.get('spam_probability', 0.0)
817
+ alert_level = result.get('alert_level', 'LOW')
818
+ risk_description = result.get('risk_description', 'Risk assessment unavailable')
819
+
820
+ alert_style = self._get_alert_styling(alert_level)
821
+
822
+ # Get the email text (truncated for display)
823
+ email_text = st.session_state.batch_emails[i] if i < len(st.session_state.batch_emails) else "Email content unavailable"
824
+ display_text = email_text[:100] + "..." if len(email_text) > 100 else email_text
825
+
826
+ classification = "SPAM" if is_spam else "HAM"
827
+ card_class = "spam" if is_spam else "ham"
828
+
829
+ st.markdown(f"""
830
+ <div class="result-card {card_class}" style="margin:10px 0;">
831
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
832
+ <h4 style="color:{'#e74c3c' if is_spam else '#27ae60'};margin:0;">
833
+ 📧 Email #{i+1} - {classification}
834
+ </h4>
835
+ <div class="alert-badge {alert_style['class']}" style="margin:0;">
836
+ {alert_style['icon']} {alert_level}
837
+ </div>
838
+ </div>
839
+ <p style="color:#bdc3c7;font-size:0.9rem;margin:8px 0;font-style:italic;">
840
+ "{display_text}"
841
+ </p>
842
+ <div style="display:flex;justify-content:space-between;align-items:center;">
843
+ <span style="color:#e0e0e0;">
844
+ <strong>Spam Probability:</strong> {spam_prob*100:.1f}%
845
+ </span>
846
+ </div>
847
+ <div style="font-size:0.85rem;color:#95a5a6;margin-top:8px;">
848
+ {risk_description}
849
+ </div>
850
+ </div>
851
+ """, unsafe_allow_html=True)
852
+
853
+ # Show pagination info
854
+ if total_pages > 1:
855
+ st.markdown(f"""
856
+ <div style="text-align:center;margin:20px 0;color:#bdc3c7;">
857
+ Showing results {start_idx + 1}-{end_idx} of {total_filtered}
858
+ (Page {page} of {total_pages})
859
+ </div>
860
+ """, unsafe_allow_html=True)
861
+
862
+
863
+ # Initialize the page only once
864
+ def get_predictor_instance():
865
+ """Get or create a singleton instance of the Predictor class."""
866
+ if "predictor_instance" not in st.session_state:
867
+ st.session_state.predictor_instance = Predictor()
868
+ return st.session_state.predictor_instance
869
+
870
+
871
+ # Render the predictor page
872
+ predictor_page = get_predictor_instance().predictor_page()
data/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ /raw
data/external/.gitkeep ADDED
File without changes
data/interim/.gitkeep ADDED
File without changes
data/processed/.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ /processed_data.pkl
2
+ /processed_features.csv
3
+ /processed_labels.csv
4
+ /predictions.csv
data/processed/.gitkeep ADDED
File without changes
data/processed/test_features.csv ADDED
@@ -0,0 +1,1116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformed_text
2
+ oh right ok make sure load work day got realli nasti cough today dri n shot signific realli help
3
+ tirupur call da
4
+ mean fat head
5
+ 1000 cash 2000 prize claim call09050000327
6
+ come aftr ltdecimalgt clean hous
7
+ friendship poem dear dear r near hear get fear live cheer tear r alway dear good ni8
8
+ wot wed nite 3 today learn 9
9
+ talk ever ok word
10
+ congrat kano treat maga
11
+ eh rememb 2 spell name ye naughti make wet
12
+ sorri call later
13
+ cool last littl get time soon
14
+ okay sent
15
+ ok lor earli still project meet
16
+ ‰ look fri pan case ‰ cheap book perhap ‰ silli fri pan ‰ like book
17
+ ask keep one mayb get messag sent glo
18
+ peopl miss tabl lambda
19
+ oh okay watch
20
+ need coffe run tomo believ time week alreadi
21
+ derp wors dude alway want parti dude file complaint three drug abus live
22
+ still around could use half
23
+ signific holla
24
+ left alreadi orchard
25
+ unsubscrib servic get ton sexi babe hunk straight phone go http subscript
26
+ friendship poem dear dear r near hear get fear live cheer tear r alway dear good ni8
27
+ yeh indian nice though kane bit shud go 4 drink sometim soon mite hav 2 go 2 da work 4 laugh soon love pete x x
28
+ sorri call later
29
+ alright head minut text meet
30
+ yep derek hous see sunday lt3
31
+ goodo ye must speak friday egg ratio tortilla need
32
+ much eighth
33
+ time week ryan
34
+ fffff text kadeem far gone
35
+ yeah see
36
+ hi roger cl
37
+ want get laid tonight want real dog locat sent direct mobil join uk largest dog network txt park 69696 nyt ec2a 3lp å£
38
+ okay head min see
39
+ come friday leav pongal get news work place
40
+ ìï send content page
41
+ oh fine tonight
42
+ want 750 anytim network min 150 text new video phone five pound per week call 08000776320 repli deliveri tomorrow
43
+ ye innoc fun
44
+ nice 2 sheffield tom 2 air opinion categori 2 babe use 2 measur ethnic next censu busi transcrib
45
+ haha figur well found piec priscilla bowl
46
+ freemsg hey darl 3 week word back like fun still tb ok xxx std chg send å£ rcv
47
+ make easi pay back ltgt yr say pay back earlier get
48
+ xam hall boy ask girl tell start term di answer den manag lot hesit n lookin around silent said intha ponnungal ipaditan
49
+ like hotel dusk game think solv puzzl area thing
50
+ meet ì rite go home lor ì dun feel like comin ok
51
+ work ring thing whole hous scream brat signific pull hair love
52
+ know lei shd babe drive lor co go sch 1 hr oni
53
+ ok leav need ask
54
+ ye watch footi worri go blow phil nevil
55
+ laugh loud forgot eh ye bring babe
56
+ littl darl signific far week need coffe run tomo believ time week alreadi ‰û
57
+ sht eg new episod cool kalli dismissi 2nd test
58
+ sht eg new episod cool per request mell mell oru minnaminungint nurungu vettam set sht eg new episod cool callertun caller press 9 copi friend callertun
59
+ good afternoon babe goe day job prospect yet miss love sigh
60
+ ok
61
+ either idea know anyplac someth
62
+ 3 pa select
63
+ love 2 babe r sure everyth alrit idiot txt back keyboard girli
64
+ strang watch 2nd one bed sweet dream miss
65
+ yo guy ever figur much need alcohol jay tri figur much safe spend weed
66
+ aathi dear
67
+ urgent mobil award å£ bonu caller prize 1 2nd attempt contact call 0871 box95qu bt nation rate
68
+ uncl abbey happi new year abiola
69
+ today voda number end 7634 select receiv å£ reward match pleas call 08712300220 quot claim code 7684 standard rate appli
70
+ cool text
71
+ go take babe
72
+ yay wait parti togeth
73
+ fun fact although would think armand would eventu build toler shit consid much smoke get fuck like 2 hit
74
+ good afternoon loverboy goe day luck come way think sweeti send love across sea make smile happi
75
+ dare ask luck sort car
76
+ oh well c later
77
+ part check iq
78
+ sure sinc parent work tuesday realli need cover stori
79
+ call hope later malaria know miss guy miss bani big signific pleas give love especi great day
80
+ ho ho big belli laugh see ya tomo
81
+ msg r time pass silent say think right also make think least 4 moment gd nt drm shesil
82
+ new theori argument win situat lose person signific argu friend kick amp say alway correct
83
+ thank well month
84
+ also track lighter find
85
+ guess somebodi know secretli fanci want find give us call 09065394514 landlin datebox1282essexcm61xn 150p 18
86
+ dear reach railway happen
87
+ aah cuddl would lush need lot tea soup kind fumbl
88
+ laugh loud ok snatch purs
89
+ check head drop stuff
90
+ yup ì comin
91
+ short messag servic auction brand new nokia 7250 4 auction today auction free 2 join take part txt nokia 86021 hg row
92
+ yeah usual guy town definit peopl around know
93
+ great p diddi neighbor come toothpast everi morn
94
+ guy never invit anywher
95
+ put readi lttimegt
96
+ guarante å£ cash å£ prize claim yr prize call custom servic repres 08714712379 10am cost 10p
97
+ one day crab run sea shore wave came n clear footprint crab crab ask frnd r clear beauti footprint wave repli fox follow footprint catch clear frndsship never let us dwn good nyt
98
+ place want da
99
+ dear umma call
100
+ laugh loud tri make day littl interest
101
+ anytim
102
+ great never better day give even reason thank god
103
+ sorri call later
104
+ ok enjoy r home
105
+ oh ya got hip hop open haha think go jazz zoom cine actual tonight free leh kb lesson tonight
106
+ know friend alreadi told
107
+ imposs argu alway treat like sub like never releas remind necessari
108
+ signific check error difficulti correct
109
+ sell signific ton coin sell coin someon thru paypal voila money back life pocket
110
+ twenti past five said train durham alreadi coz reserv seat
111
+ adult would learn experi real danger like peep use drug need comment
112
+ 2 celebr båõday els
113
+ said ì dun haf passport smth like dat ì juz send email account
114
+ laugh loud differ go tri find everi real life photo ever took
115
+ carlo pick signific swing usf littl bit
116
+ aight text tonight see
117
+ text carlo let know hang
118
+ mean post wrote like signific mani time ritten stuff let sit feel time angri left hit send stop check phone got car said sleep bore signific time clean fold laundri etc least make bed
119
+ make babi yo though
120
+ ok lor
121
+ use foreign stamp countri
122
+ wat make thk fall actual thk quit prone 2 fall lucki dad home ask come n fetch alreadi
123
+ ye possibl dint tri pleas tell one okay
124
+ dear voucher holder 2 claim 1st class airport loung pass use holiday voucher call 08704439680 book quot 1st class x 2
125
+ talk sexi make new friend fall love world discreet text date servic text import person 83110 see could meet
126
+ prob hon doinat mo
127
+ think girl propos today se bloodi funki shit fuck face
128
+ sexi sexi cum text instant messag wet warm readi porn fun messag free recd msg 150p inc vat 2 cancel text stop
129
+ win winner mr foley ipod excit prize soon signific keep eye mobil visit www
130
+ signific mani peopl seem special first sight remain special till last sight maintain till life end sh
131
+ got got 2 colour lor one colour quit light n e darker lor actual done style hair
132
+ laugh loud would awesom payback
133
+ well great weekend
134
+ fujitsu seri lifebook good
135
+ entri å£ weekli comp send word enter 88877 18 www
136
+ chikku nt yet ya free
137
+ call
138
+ worri 1 day big lambu ji vl come enjoy batchlor parti
139
+ okay might come tonight class let us earli
140
+ photoshop make comput shut
141
+ hey hey wereth monkeespeopl say monkeyaround gorgeou
142
+ darren say dat meet da ge den dun meet 4 dinner co later leav xy feel awkward den meet 4 lunch lor
143
+ ugh hope asu peopl randomli reformat
144
+ use soc use home ìï know 2 type word action requir
145
+ think steyn sure get one wicket
146
+ tast fish curri p
147
+ sent ì part
148
+ oh send address
149
+ ok dear call chechi
150
+ jot thing want rememb later
151
+ ok would babe love r sure think wot want drinkin dancin eatin cinema wot
152
+ feel alway happi slowli becom habit amp final becom part life follow happi morn amp happi day
153
+ 10 min later okay
154
+ still waitin sht eg new episod cool usual ìï come back sch oredi
155
+ okay even da
156
+ vl bcum difficult
157
+ crucifi c told earlier
158
+ full heat pa appli oil pa
159
+ alway make thing bigger
160
+ cours math one day one chapter one month finish
161
+ search love let love find call fall love bcoz forc fall know smeon hold bslvyl
162
+ oh see better quickli go bath n settl
163
+ oh come arehol less commonli home
164
+ sex mobil free sexi pic jordan text babe 88600 everi wk get sexi celeb pocketbab 4 pic 16 å£ 087016248
165
+ 545 lor ya go 4 dinner togeth
166
+ oop thk dun haf enuff go check tell ì
167
+ hi lookin 4 sauci daytim fun wiv busti marri woman free next week chat 2 sort time 09099726429 janinexx callså£
168
+ want 2 meet 2morro
169
+ smile pleasur smile pain smile troubl pour like rain smile sum1 hurt smile becoz someon still love see smile
170
+ 80488 500 free text messag valid 31 decemb 2005
171
+ dai ltgt naal eruku
172
+ said mind go bedroom minut ok sed sexi mood came 5 minut latr wid cake wife
173
+ good day teeth sht eg new episod cool pain maintain stuff
174
+ sent signific type food like
175
+ norm tomorrow finish 4 co st test need sort librari stuff point tomo got letter today access today learn end march signific better get move
176
+ call da wait call
177
+ problem talk later
178
+ pleas give food prefer pap slowli load sugar take hour give water slowli
179
+ whore unbeliev
180
+ carri disturb
181
+ ya serious better yi though
182
+ aight time want come
183
+ hahaha brain dear
184
+ aight text address
185
+ laugh loud knew saw dollar store
186
+ babe talk think good boy miss love
187
+ 2nd attempt contract week top prize either å£ cash å£ prize call 09066361921
188
+ laugh loud yeah point guess
189
+ wait call
190
+ ok ok take care understand
191
+ yep great loxahatche xma tree burn ltgt start hour
192
+ inform take quick shower epsilon like ltgt min
193
+ come right ahmad
194
+ opinion 1 2 jada 3 kusruthi 4 lovabl 5 silent 6 spl charact 7 matur 8 stylish 9 simpl pleas repli
195
+ also piec
196
+ hello wat talk email address
197
+ r beauti girl ever seen r babi come c common room
198
+ ringtonek 84484
199
+ noth got messag frm tht unknown
200
+ prize go anoth custom www 18 150p polo ltd suit 373 london w1j 6hl pleas call back busi
201
+ id check like 1 bowl worth left
202
+ good word word may leav dismay mani time
203
+ wonder phone batteri went dead tell love babe
204
+ hi hun instant messag comin tonight every1 instant messag sorri 4 hope ava goodtim rang melnit ifink mite babe sort il explain everythin mon
205
+ alright took morphin back yo
206
+ short messag servic servic inclus text credit pleas gotto www login 3qxj9 unsubscrib stop extra charg help 08702840625 comuk 9ae
207
+ wah oki oki muz make use e unlimit haha
208
+ think spatula hand
209
+ free entri å£ weekli comp send word enter 84128 18 www cust care 08712405020
210
+ keep ten rs shelf buy two egg
211
+ smith wast da want gayl
212
+ still custom place
213
+ hi darlin youphon instant messag athom youwanna chat
214
+ zoe hit 2 instant messag fuck shitin il defo tri hardest 2 cum 2morow love million lekdog
215
+ loan purpos å£ å£ homeown tenant welcom previous refus still help call free 0800 1956669 text back help
216
+ 1st wk free great tone str8 2 wk txt nokia 8007 classic nokia tone hit 8007 poli nokia poli 16
217
+ ya referin mei ex wat arehol less commonli home waitin 4 treat somebodi shld babe rich liao gd den dun work frm tomorrow onward
218
+ urgent mobil number award å£ prize guarante call 09061790126 land line claim 3030 valid 12hr 150ppm
219
+ guarante å£ award even å£ cashto claim award call free 08000407165 18 2 stop getstop 88222 php rg21 4jx
220
+ sent email id soon
221
+ sorri miss call let talk time 07090201529
222
+ shall buy one dear
223
+ hello damn christma thing think decid keep mp3 work
224
+ call germani 1 penc per minut call fix line via access number 0844 861 85 85 prepay direct access www
225
+ hm good morn headach anyon
226
+ could seen recognis face
227
+ noth meant money enter account bank remov flat rate someon transfer ltgt account ltgt dollar got remov signific bank differ charg also differ sure trust 9ja person send account detail co
228
+ go let know co come back keyboard holiday day come number
229
+ offic matter call break
230
+ tessi favor pleas convey birthday wish nimya forget today birthday shija
231
+ 1 number 2 go massiv pain ass rather get involv possibl
232
+ fine rememb
233
+ winner sht eg new episod cool valu network custom hvae select receiv å£ reward collect call 09061701444 valid 24 hour acl03530150pm
234
+ rock yr chik get 100 filthi film xxx pic yr phone rpli filth 69669 saristar ltd e14 9yt 08701752560 450p per 5 day stop2 cancel
235
+ pussi perfect
236
+ ""
237
+ latest news polic station toilet stolen cop noth go
238
+ rose red blood heart send friend includ like get back 1 r poor relat 2 need 1 support 3 r frnd 2 mani 4 luv 5 some1 pray god marri tri
239
+ ok help ask work tomorrow
240
+ smoke peopl use wyli smoke much justifi ruin shit
241
+ revers cheat mathemat
242
+ leav hous
243
+ sorri uncl keep touch
244
+ sunshin quiz win super soni dvd record cannam capit australia text mquiz 82277 babe
245
+ problem spend lot qualiti time togeth
246
+ luton 0125698789 ring around h
247
+ e best 4 drive tomorrow
248
+ yeah right bring tape measur fri
249
+ uniqu user id 1172 remov send stop 87239 custom servic 08708034412
250
+ network technic support associ
251
+ sorri batteri die yeah
252
+ thank better work feel use otherwis
253
+ ok tell stay yeah tough optimist thing improv month
254
+ way
255
+ next month get upto 50 call 4 standard network charg 2 activ call 9061100010 c wire3 1st4term pobox84 m26 3uz cost å£ min mobcudb
256
+ know result
257
+ new car hous parent new job hand
258
+ thanx
259
+ like person size
260
+ eeri nokia tone 4u rpli tone titl 8007 eg tone dracula 8007 titl ghost addamsfa munster exorcist twilight www pobox36504w45wq 150p
261
+ ffffffffff alright way meet sooner
262
+ want kfc tuesday buy 2 meal 2 gravi 2 mark 2
263
+ peopl game mall iouri kaila
264
+ much buzi
265
+ good afternoon starshin boytoy crave yet ach fuck sip cappuccino miss babe teas kiss
266
+ seriou money base
267
+ themob link get premium pink panther game new 1 sugabab crazi zebra anim badass hoodi wallpap 4 free
268
+ nah think goe usf live around though
269
+ urgent mobil award å£ bonu caller prize 02 2nd attempt contact call 0871 box95qu
270
+ fine miss much
271
+ signific want gym harri
272
+ wait till end march el nino get oh
273
+ congrat 2 mobil 3g videophon r call 09063458130 videochat wid mate play java game dload polyph music nolin rentl bx420 ip4 5we 150p
274
+ probabl come everybodi done around ltgt right
275
+ yup thk r e teacher said make face look longer darren ask 2 cut short
276
+ check mail mail varma kept copi regard membership care allah
277
+ hi darlin kate doin somethin tonight instant messag go pub call swan someth parent one drink signific phone
278
+ dai da send resum id
279
+ thank way lost
280
+ call one pick e phone ask alreadi said ok
281
+ know ju say go lido time 930
282
+ yup want go yoga call book
283
+ oh fuck sake like tallahasse
284
+ okay okay watch film
285
+ lov line hurt truth
286
+ urgent tri contact today draw show å£ prize guarante call 09050001295 land line claim a21 valid 12hr
287
+ okay ill drink need seriou model pleas send mail id pa
288
+ come mahal bu stop ltdecimalgt
289
+ plan manag
290
+ bloomberg messag center 447797706009 wait appli futur http bloomberg
291
+ call 08702490080 tell 2 call 09066358152 claim å£ prize 2 enter mobil person detail prompt care
292
+ dad get back
293
+ ‰ leav around four ok
294
+ come slave go unconsci avoid make unhappi
295
+ come get babe quit differ guess rite
296
+ come home
297
+ got person stori
298
+ free polyphon rington text super 87131 get free poli tone week 16 sn pobox202 nr31 7z subscript 450pw
299
+ okay book alreadi includ one bugi
300
+ search good dual sim mobil pa
301
+ oh god happi see messag 3 day
302
+ also know lunch menu da know
303
+ face test 1 2 3 4 5 6 7 8 9 ltgt select number tell face astrolog wait quick repli
304
+ radio show
305
+ ì go 4 today meet
306
+ reach home ltgt minut
307
+ age abj
308
+ dear 0776xxxxxxx invit xchat final attempt contact txt chat 86688 150p ldn 18yr
309
+ cannot pick phone right pleas send messag
310
+ hey fanci meetin 4 cha åð hav lil beverag txt ring meet later quit tire got 3 love pete x x x
311
+ said go snow start around 8 9 privat messag tonit predict inch accumul
312
+ ok typic repli
313
+ ya told ask wat matter
314
+ neshanth r
315
+ ask knw nt may frnd classmat
316
+ might come kerala 2 day prepar take leav finalis plan travel visit finish urgent work
317
+ pick fone dumb
318
+ want bold 2 bb torch
319
+ need go get
320
+ dear mood cannot drive signific brother drive
321
+ ì go send
322
+ ew one
323
+ think rule tamilnadu tough peopl
324
+ come back 4 dinner rite dad ask signific confirm wif
325
+ hcl chennai requir fresher voic process english need upto ltgt call ms ltgt telephon interview via indyarock
326
+ whenev see still hook
327
+ x cours 2yr signific messag messeng lik r send
328
+ hi 07734396839 ibh custom loyalti offer new nokia6600 mobil å£ txtauction word get
329
+ ou guarante latest nokia phone 40gb ipod mp3 player å£ prize txt word collect 83355 ibhltd ldnw15h 150p
330
+ also da feel yesterday night wait today learn 2day night dear
331
+ eatin lor goin back work soon e mountain deer show huh watch liao nice
332
+ num corrct dane
333
+ think ‰ wait bu inform get ever get
334
+ tund wish great day abiola
335
+ sure mean get
336
+ okay good go
337
+ emigr someth ok mayb 5 bit hope
338
+ goin workout lor muz lose e fat
339
+ laugh loud great instant messag get hungri
340
+ love holiday monday feel even go dentist hour
341
+ probabl earlier station think
342
+ appar bff carli quick
343
+ remain bro amongst bro
344
+ case wake wonder forgot take care someth grandma today done parad
345
+ raji favour pleas convey birthday wish nimya pleas today birthday
346
+ sometim put wall around heart safe get hurt find care enough break wall amp get closer goodnoon
347
+ great see messag signific r leav congrat dear school wat r plan
348
+ say happen
349
+ dint come us
350
+ also rememb get dobbi bowl car
351
+ happi new year man
352
+ sleep surf
353
+ friend got say up order gram he got ltgt get
354
+ hey mate honey ave good holiday gimmi de goss
355
+ crazi action requir marri ìï like gd look guy fren like say korean leona fave dun thk aft think mayb prob go
356
+ e messag ju said thank gift
357
+ mmmmm love wake word morn miss love hope day goe well happi wait us togeth
358
+ yeah probabl still got check leo
359
+ bought one rington get text cost 3 pound offer tone etc
360
+ aight plan come later tonight
361
+ yeah leav hour least 4 sound
362
+ sht eg new episod cool usual call ard 10 smth
363
+ pleas call custom servic repres freephon 0808 145 4742 9am sht eg new episod cool guarante å£ cash å£ prize
364
+ romant pari 2 night 2 flight å£ book 4 next year call 08704439680t appli
365
+ 645
366
+ juz woke signific bit blur blur dad went liao cannot cum oso
367
+ hiya comin 2 bristol 1 st week april le got rudi new yr eve snore drunk back keyboard colleg yet work send ink 2 bath
368
+ custom loyalti offer new nokia6650 mobil å£ txtauction txt word start 81151 get 4t take care 150p
369
+ hey pple 900 5 night locat wif breakfast hamper
370
+ come 2 pick
371
+ got tv 2 watch meh work today
372
+ aiyo co short messag servic ì ì neva repli signific wait 4 ì repli lar tot ì finish lab wat
373
+ first gain ltgt kg sinc took second done blood sugar test ok blood pressur within normal limit worri
374
+ great escap fanci bridg need lager see tomo
375
+ short cute good person
376
+ 5 2 work time
377
+ said matter mind say matter
378
+ sorri call later
379
+ wait til least wednesday see get
380
+ guess could sht eg new episod cool good excus sht eg new episod cool laugh loud
381
+ know girl alway safe selfish know got pa thank good night
382
+ much ì will pay
383
+ go 2 bahama callfreefon 08081560665 speak live oper claim either bahama cruis ofå£ cash 18 opt txt x 07786200117
384
+ sun arehol less commonli home thk mayb dun anythin thk book e lesson e pilat orchard mrt noe hor
385
+ rememb day
386
+ dear ok
387
+ dun drive go 2 sch
388
+ tell pa pain de
389
+ wat time ì finish
390
+ prabha soryda heart sori
391
+ check wid corect spele sarcasm
392
+ sac score big hundr set batsman
393
+ congrat treat pend mail 2 day mail thru mother home mail
394
+ heehe signific funni though
395
+ eeri nokia tone 4u rpli tone titl 8007 eg tone dracula 8007 titl ghost addamsfa munster exorcist twilight www pobox36504w45wq 150p
396
+ make ne plan nxt wknd coz want us come ok
397
+ effect irrit ignor
398
+ freaki laugh loud
399
+ cannot wait see photo use
400
+ tiwari rcb bang kochi
401
+ 2 laptop noe infra slow lar wan fast one
402
+ yup remb think book
403
+ ok shall talk
404
+ id onluy matter get offcampu
405
+ ard 4 lor
406
+ okay make sens way carlo difficult signific guy go smoke go pick second batch get ga
407
+ love night wake see messag hope smile know sht eg new episod cool great morn
408
+ ìï takin linear algebra today
409
+ oh howda good good math en samachara chikku
410
+ hey anyway
411
+ cp caus outag conserv energi
412
+ good morn princess
413
+ wah lucki man save money hee
414
+ long time rememb today
415
+ good morn dear great amp success day
416
+ okay still love
417
+ hate turn fun shop trip annoy day everyth would look hous
418
+ hi probabl much fun get messag thought id txt co instant messag bore jame fart night
419
+ ultim tor motiv tui achiev korli
420
+ get 2 phone want chat 2 set meet call 09096102316 cum 2moro love jane xx callså£
421
+ en chikku nang bakra messag kalstiya tea
422
+ hey angri repli dr
423
+ free today haf 2 pick parent tonit
424
+ happen interview
425
+ dear deni word pleas
426
+ hi yiju regard 3230 textbook intro algorithm second edit sell 50
427
+ sorri help
428
+ haha awesom way back
429
+ take phone callon friday assum year
430
+ tell tell one signific treat hi hi hi
431
+ hey babe far 2 spun 2 speak da mo dead 2 da wrld sleep da sofa day
432
+ decemb mobil 11mth entitl updat latest colour camera mobil free call mobil updat co free 08002986906
433
+ rat hey ever vote next theme
434
+ come home 4 dinner
435
+ hi babe jordan r instant messag home abroad lone text back want chat xxsp visionsm text stop stopcost 150p 08712400603
436
+ stop howev suggest stay someon abl give or everi stool
437
+ horribl gal sch stuff come got mc
438
+ kind took garag centr part exhaust need replac part order n take fix tomo morn
439
+ ye da plm offic
440
+ like new hous
441
+ 1 new voicemail pleas call 08719181513
442
+ home love still awak love kiss
443
+ yeah like goe like friend go flip shit like half hour
444
+ eat shit wait monkey face bitch asshol
445
+ 7 esplanad ì mind give lift co got car today
446
+ pick variou point go 2 yeovil motor project 4 3 hour take home 12 2 5 max easi
447
+ dude see lotta corvett late
448
+ yunni walk citylink ì faster come hungri
449
+ okay call arehol less commonli home
450
+ height confid aeronaut professor wer calld amp wer askd 2 sit aeroplan aftr sat wer told dat plane ws made student dey hurri plane bt 1 move said made student
451
+ get offici england poli rington colour flag yer mobil tonight game text tone flag 84199 optout txt eng stop box39822 w111wx å£
452
+ unlimit text limit minut
453
+ man bu signific signific signific slow think go get
454
+ love come took signific long leav zaher got word ym happi see sad left miss
455
+ buy blackberri bold 2 torch buy new use let know plu say buy ltgt g wifi ipad say ltgt g
456
+ claim 200 shop spree call 08717895698 mobstorequiz10ppm
457
+ lastest stereophon marley dizze racal libertin stroke win nookii game flirt click themob wap bookmark text wap 82468
458
+ go home first lar ì wait 4 lor put stuff first
459
+ hello beauti r ok kind ad row wiv walk pub want night wiv miss
460
+ hi di yiju meet 7 privat messag esaplanad tonight
461
+ describ lucki actual awak noon
462
+ cme want go ho 2morow wil cme got dear say time
463
+ worri hope photo shoot went well spif fun workag
464
+ hey repli pa
465
+ hi harish rent transfr acnt
466
+ sorri took signific long way
467
+ place man
468
+ know taj mahal sht eg new episod cool symbol love lesser known fact 1 mumtaz shahjahan 4th wife 7 wife 2 shahjahan kill mumtaz husband marri 3 mumtaz die ltgt th deliveri 4 marri mumtaz sister question aris hell love great hari
469
+ peopl dog area call 09090204448 join like mind guy arrang 1 1 even aå£ minapn ls278bb
470
+ okay cannot come search job
471
+ forgot work today want chat thing ok signific drop text free bore etc ring hope well nose essay xx
472
+ babe miiiiiiissssssssss need crave geeee signific sad without babe love
473
+ aight work thank
474
+ reckon need town eightish walk carpark
475
+ hi wkend ok journey terribl wk good sht eg new episod cool huge back log mark
476
+ nah perpetu dd
477
+ come day class
478
+ big chic common declar
479
+ actual get readi leav hous
480
+ sale arsen dartboard good condit doubl trebl
481
+ think go honesti road call bank tomorrow tough decis make us great peopl
482
+ hello love went day alright think sweet send jolt heart remind love hear scream across sea world hear ahmad al hallaq love own possess passion kiss
483
+ know lei ì decid lor leona oop tot ben go n messag
484
+ weekli cool tone readi download week new tone includ 1 crazi frog f 2 akon 3 black eye p info n
485
+ still pretti weak today bad day
486
+ ok juz receiv
487
+ luck catch put
488
+ still look job much ta earn
489
+ shall disturb anymor jia
490
+ got room soon ‰û put clock back today learn 8 shout everyon get realis 7 wahay anoth hour bed
491
+ shop lor juz arriv
492
+ dude teresa hope okay hear peopl call receiv packag sinc dec ltgt thot like know fantast year best read plu realli realli bam first aid usml work done
493
+ send someon els
494
+ hi jon pete bin 2 spain recent hav sum dinero left bill said åôrent mayb interest hav 12 signific around å£ tb jame
495
+ yar quit clever aft mani guess lor got ask 2 bring thk darren signific will 2 go aiya thk leona still attach wat
496
+ haf combin n c lor
497
+ de see onlin shop signific ask
498
+ ye last practic
499
+ ya well fine bbd full pimpl becom quit black rite cold wear sweatter
500
+ class hour sorri
501
+ quit lor dun tell wait get complac
502
+ want sent ltgt mesag today sorri hurt
503
+ askd question hour answer
504
+ haha leg neck kill amigo hope end night burn think could swing like hour
505
+ okay sent
506
+ know dad said come home 2 bring us 4 lunch yup go w lor call reach school lor
507
+ good babi
508
+ watch cartoon listen music amp eve go templ amp church
509
+ friend help us problem give stupid suggest land us anoth problem help us forgt previou problem
510
+ noth ok anyway give treat
511
+ thanx yup come back sun finish dinner go back 2 hotel time fli tog 4 exactli mth today hope haf mani mth come
512
+ happi valentin day know earli hundr handsom beauti wish signific thought finish aunti uncl 1st
513
+ new textbuddi chat 2 horni guy area 4 25p free 2 receiv search postcod gaytextbuddi txt one name 89693 08715500022 rpl stop 2 cnl
514
+ er mw instant messag fill tuth aight
515
+ messag phone hold
516
+ okay soon best
517
+ dear free messag without recharg hi hi hi
518
+ call meet
519
+ let studi stress later
520
+ ìï call dad oredi
521
+ good mrng dear hav nice day
522
+ although told dat baig face watch realli like e watch gave co real thanx 4 everyth dat done today touch
523
+ workin get job
524
+ guess useless call 4 someth import
525
+ phone weirdest auto correct
526
+ got c lazi type forgot ì lect saw pouch like nice
527
+ today holiday work
528
+ nonenowher ikno doesdiscount
529
+ sorri got late start way
530
+ shore takin bu
531
+ camera quit good 10 pixel 3optic 5digit doom love holiday safe hope hav good journey happi new year see coupl week
532
+ ok feel like john lennon
533
+ escap theatr go watch kavalan minut
534
+ call number avail appoint ask connect call wahe fathima
535
+ love one law make happi person love way friendship one law never make friend feel alon aliv good night
536
+ cool text park
537
+ short messag servic servic inclus text credit pleas goto www login 3qxj9 unsubscrib stop extra charg help 08702840625 220 9ae
538
+ urgent mobil number award å£ prize guarante call 09061790121 land line claim 3030 valid 12hr 150ppm
539
+ 1 nokia tone 4 mob everi week txt nok 87021 1st tone free signific get txtin tell friend 150p 16 repli hl 4info
540
+ comput fri essenti part keep spare fuck idiot roommat looovvv leav thing run full ltgt 7
541
+ like tell deepest darkest fantasi call 09094646631 60p stop text call 08712460324 nat rate
542
+ laugh fish memori need
543
+ need 8th campu moment could pick hour two
544
+ nope go home go pump petrol lor like go 2 rain soon
545
+ get 1st rington free repli messag tone great top 20 tone phone everi week å£ per wk 2 opt send stop 08452810071 16
546
+ got tallent wast
547
+ ok
548
+ today accept day accept sht eg new episod cool brother sister lover dear1 best1 clos1 lvblefrnd jstfrnd cutefrnd lifpartnr belovd swtheart bstfrnd rpli mean enemi
549
+ ok
550
+ ga station like block away hous drive right sinc armenia end swann take howard
551
+ hope alright babe worri might felt bit despar learn job fake wait come back love
552
+ discuss mother arehol less commonli home
553
+ nice new shirt thing wear nudist theme miss
554
+ guess ltgt min
555
+ oki
556
+ sen told go join uncl financ cbe
557
+ st andr virgil cream
558
+ ya ì take ure practic lesson start june
559
+ privat 2003 account statement 07973788240 show 800 un point call 08715203649 identifi code 40533 expir 31
560
+ babe love cover face kiss
561
+ yep fine 7 8 ice age
562
+ laugh loud ye friendship hang thread buy stuff
563
+ forget own privat properti good boy alway passion kiss
564
+ freemsg fanci flirt repli date join uk fastest grow mobil date servic msg rcvd 25p optout txt stop 83021 repli date
565
+ pleas attend phone
566
+ call tell infront call
567
+ boo time get suppos take shop today
568
+ found differ farm shop buy chees way back call
569
+ sad stori man last week babe wife wish parent forgot n signific kid went work even colleagu wish
570
+ need detail onlin job
571
+ make sens take unless free need know wikipedia
572
+ refus loan secur unsecur get credit call free 0800 195 6669 text back help
573
+ signific messag food
574
+ custom place wil cal sir
575
+ urgent pleas call 09061743810 landlin abta complimentari 4 tenerif holiday 5000 cash await collect sae box 326 cw25wx 150 ppm
576
+ repli name address receiv post week complet free accommod variou global locat www ph
577
+ well go finish bath good night
578
+ dun thk quit yet hmmm go jazz yogasana oso go meet lesson den
579
+ 1 new messag pleas call 08715205273
580
+ number sir
581
+ hi custom loyalti offer new nokia6650 mobil å£ txtauction txt word start 81151 get 4t take care 150p
582
+ dai download exe file run exe instal
583
+ today sorri day ever angri ever misbehav hurt pleas pleas slap urself bcoz fault basic good
584
+ good mrng dear hav nice day
585
+ see film
586
+ ok call disturb one know avoid burden
587
+ dear 0776xxxxxxx invit xchat final attempt contact txt chat 86688 150p ldn 18yr
588
+ actual wait 2 week start put ad
589
+ sht eg new episod cool per request mell mell oru minnaminungint nurungu vettam set sht eg new episod cool callertun caller press 9 copi friend callertun
590
+ know lei neva say
591
+ want laugh tri chit mobil logon txting word chat send 8883 cm peac box 4217 london w1a 6zf 16 118p rcvd
592
+ good night go sleep
593
+ best messag hard person know one step foward make fall love amp one step back ruin friendship good night
594
+ ok watch tv
595
+ bruce babe down amp fletcher
596
+ thank keep mind
597
+ nope watch tv home go bore
598
+ ye pleas leav ltgt signific ltgt leav
599
+ tonight mate catch sleep new number way
600
+ yet like keep touch easiest way barcelona way ru hous
601
+ good hear
602
+ xma iscom award either å£ cd gift voucher free entri 2 å£ weekli draw txt music 87066 tnc www
603
+ never mind go wear sport shoe anyway go late leh
604
+ princess kitti shave natur
605
+ congratul award 500 cd voucher 125gift guarante free entri 2 100 wkli draw txt music 87066 tnc www
606
+ love someon make love sht eg new episod cool much sht eg new episod cool love signific much want love anyon except good nit
607
+ moji inform save live thank
608
+ email alertfrom jeri stewarts 2kbsubject low prescripiton drvgsto listen email call 123
609
+ marvel mobil play offici ultim spider game å£450 mobil right text spider 83338 game send free 8ball wallpap
610
+ poyyarikatur post di ltgt
611
+ telli brdget jone
612
+ yeah ju rite
613
+ work week
614
+ sorri call later
615
+ ey calm downon theacus itxt co iwana know wotu r doin thew haventcn age up4 neth sat j xxx
616
+ ìï give time walk
617
+ mysteri solv open email sent anoth batch sweeti
618
+ mobi pub quiz å£ high street prize know new duchess cornwal txt first name 82277 stop å£ 008704050406 sp
619
+ madam disturb receiv refer check dlf premarica inform
620
+ fine difficulti phone work mine pleas send anoth friend request
621
+ thanx darlin cool thanx birthday drink 2 nite 2morrow take care c soon
622
+ know dad back
623
+ romant
624
+ dear call
625
+ ye complet form also utter wast
626
+ still play gautham
627
+ wow love sooo much know bare stand wonder day goe well love think miss
628
+ urgent mobil number award å£ bonu caller prize call 09058095201 land line valid 12hr
629
+ anytim best
630
+ sad stori man last week babe wife wish parent forgot n signific kid went work even colleagu wish sht eg new episod cool enter cabin pa said happi babe boss felt special askd 4 lunch lunch invit apart went said mind go bedroom minut ok sed sexi mood came 5 minut latr wid cake wife parent kidz friend n colleagu scream surpris wait sofa nake
631
+ moon come color dream star make music short messag servic give warm peac sleep good night
632
+ serious tell exact word right
633
+ ha ha nan yalrigu heltini kothi chikku share mani thing wit far told bodi even utter word trust signific much tell other pleas nxt time use word chikku
634
+ okay actual guy meet sunoco howard right way
635
+ camera award sipix digit camera call 09061221066 fromm landlin deliveri within 28 day
636
+ watch tv lor nice one like lor
637
+ ok tell half hr come need 2 prepar
638
+ huh cannot thk oredi mani page
639
+ sir wait mail
640
+ much hdd case cost
641
+ think fix send test messag
642
+ goldvik 29m invit friend repli ye see www stop send stop frnd 62468
643
+ bishan lei tot ì say lavend
644
+ win å£ shop spree everi week start 2 play text store 88039 skilgm tscs08714740323 1winawk age16 å£
645
+ doubl min doubl txt 1 price linerent latest orang bluetooth mobil call mobileupd8 latest offer 08000839402 call2optout
646
+ sure night menu know noon menu
647
+ hous murder coz man murder ltgt th januari sht eg new episod cool public holiday govt close post offic
648
+ oh yeah diet flew window
649
+ kind first one get twelv aah speak tomo
650
+ call senthil hsbc
651
+ great role model give signific much realli wish day miracl god sht eg new episod cool reason everyth must say wish knew look sinc young still great day
652
+ go sleep tire travel
653
+ see laugh loud play 9 door sometim yo
654
+ got smaller capac one quit ex
655
+ hmm mani unfortun pic obvious hot cake kind fun though
656
+ hope result consist intellig kind start ask practicum link keep ear open best talk later
657
+ sick still go shop
658
+ know jabo abi
659
+ signific th gower mate r man good wale ill babe back åômorrow c wk messag 4 åð random
660
+ cool come like ltgt ish
661
+ give someth drink take vomit temp might drop unmit howev let know
662
+ fine fine
663
+ honestli made love cup tea promptli drop key burnt finger get
664
+ ceri rebel sweet dreamz littl buddi c ya 2moro need bloke
665
+ reason team budget avail last buy unsold player base rate
666
+ know thing wrong everyso often panick start goin bout bein good enough ‰û
667
+ good night dear sleepwel care
668
+ supervisor find 4 one lor thk student ask yet tell aft ask
669
+ care get weasel way shit twice row
670
+ take small dose tablet fever
671
+ cannot think anyon spare room top head
672
+ å£ winner guarante caller prize final attempt contact claim call 09071517866 150ppmpobox10183bhamb64x
673
+ home also
674
+ got shitload diamond though
675
+ ye think signific offic lap room think last day shut
676
+ thanx4 today cer nice 2 catch ave 2 find time often oh well take care c soon
677
+ tomorrow instant messag finish 9 door
678
+ thank gener date brotha
679
+ bit weird even suppos happen good idea sure pub
680
+ hui xin da lib
681
+ hey sorri didntgiv ya bellearli hunni
682
+ ltgt guess easi enough
683
+ whatsup want sleep
684
+ stayin troubl stranger dave day heåõ sort bloke gona get girl mr mum still think get 2getha
685
+ inform usf swing room whenev
686
+ privat 2003 account statement show 800 un point call 08715203694 identifi code 40533 expir 31
687
+ yeah think usual guy still pass last night get ahold anybodi let know throw
688
+ yo carlo friend alreadi ask work weekend
689
+ good ‰ need receipts‰ done ‰û ye pleas tell ‰ number could ring
690
+ send naughti pix
691
+ privat 2003 account statement show 800 un point call 08715203656 identifi code 42049 expir 26
692
+ reach ten morn
693
+ custom servic announc recent tri make deliveri unabl signific pleas call 07090298926 ref
694
+ got rumour go buy apart chennai
695
+ derek done class
696
+ got lousi sleep kept wake everi 2 hour see cat want come worri cold
697
+ yo class tomorrow right
698
+ deep sigh miss realli surpris gone net cafe yet get miss
699
+ good afternoon love good see word ym get tm smart move slave smile drink coffe await
700
+ hey signific sat go intro pilat kickbox
701
+ goodmorn today late ltdecimalgt min
702
+ hmmm open
703
+ xma offer latest motorola sonyericsson nokia free bluetooth dvd doubl min 1000 txt orang call mobileupd8 08000839402 call2optout
704
+ sht eg new episod cool valu custom pleas advis follow recent review mob award å£ bonu prize call 09066364589
705
+ unfortun found pick sister airport even signific think go tri go one th
706
+ suppos meet discuss trip thought xuhui told afternoon thought go lesson
707
+ okay chase dream good next
708
+ boy love gal propsd bt mind gv lv lttr bt frnd threw thm boy decid 2 aproach gal dt time truck speed toward gal wn 2 hit girl boy ran like hell n save ask hw cn run signific fast boy repli boost secret energi n instantli girl shout energi n thi live happili 2gthr drink boost evrydi moral stori free msg good ni8
709
+ much would cost hire hitman
710
+ hurt teas make cri end life die pleas keep one rose grave say stupid miss nice day bslvyl
711
+ gosh pain spose better come
712
+ honey sweetheart darl sexi bun sugar plum loverboy miss boytoy smack ass go gym
713
+ jordan got vote last nite
714
+ say slowli god love amp need heart blood ten special peopl amp c miracl tomorrow
715
+ job profil seem like bpo
716
+ home ard wat time reach
717
+ mean get door
718
+ e best 4 exam later
719
+ tkt euro2004 cup final å£ cash collect call 09058099801 b4190604 pobox 7876150ppm
720
+ make tonight
721
+ get garden readi summer free select summer bulb seed worth å£ scotsman saturday stop go2 notxt
722
+ head dey swell oh thank make day
723
+ freemsg xma tone real
724
+ love set soul fire spark flame big rawr flame hug kiss
725
+ congrat nokia 3650 video camera phone call 09066382422 call cost 150ppm ave call 3min vari mobil 16 close 300603 post bcm4284 ldn wc1n3xx
726
+ prashanthettan mother pass away last night pray famili
727
+ night night see tomorrow
728
+ ok
729
+ end might still vomit okay everyth come
730
+ ask darren go n pick lor oso sian tomorrow haf 2 meet lect
731
+ reach home tire come tomorro
732
+ got divorc laugh loud
733
+ go tell friend sure want live smoke much spend hour beg come smoke
734
+ tri contact repli offer video handset 750 anytim network min unlimit text camcord repli call 08000930705
735
+ ill littl closer like bu stop street
736
+ make life stressful alway find time laugh may address year life sure add life year good ni8 dream
737
+ hurri home soup done
738
+ joy father john john joy father an th hav ltgt iq ia question tri answer
739
+ see knew give break time woul lead alway want miss curfew go gibe til one midnight movi go get today learn 2 need come home need getsleep anyth need babe studdi ear train
740
+ sound better even instant messag costum instant messag sure time finish tomorrow txt end
741
+ secret admir look 2 make contact r think signific special 09065171142
742
+ think could stop like hour signific roommat look stock trip
743
+ realli good see day dudett miss
744
+ ex abl kid want kid one day
745
+ urgent mobil number award å£ prize guarante call 09058094454 land line claim 3030 valid 12hr
746
+ oh okay placement arehol less commonli home
747
+ know know send chat 86688 let find 150p rcvd hg ldn 18 year
748
+ thought could go dinner treat seem ok
749
+ say leh cours noth happen lar say romant ju bit lor thk e nite sceneri signific nice leh
750
+ ltgt fast approach signific wish happi new year happi sankranti happi republ day happi valentin day happi shivratri happi ugadi happi fool day happi may day happi independ day happi friendship day amp happi birthday 4 happi ganesh festiv happi dasara happi diwali happi christma ltgt good morn afternoon even night rememberi first wish raj
751
+ latest nokia mobil ipod mp3 player å£400 proze guarante repli win 83355 norcorp ltd
752
+ help swoop pick wherev bird r meet want
753
+ free 1st week no1 nokia tone 4 mob everi week txt nokia 8007 get txting tell mate www pobox 36504 w45wq norm150p 16
754
+ jane babe goin 2 wrk feel ill lst nite fone alreadi cover 4 chuck
755
+ congrat 2 mobil 3g videophon r call 09061744553 videochat wid mate play java game dload polyh music nolin rentl bx420 ip4 5we 150pm
756
+ 1000 girl mani local 2 r virgin 2 r readi 2 4fil everi sexual need 4fil text cute 69911
757
+ sir 8 trip bu last week anoth audit next wednesday think might drive time
758
+ goodnight sleep well da pleas take care pa pleas
759
+ ok problem yup go sch 4 rem correctli
760
+ specialis work slave labor look month sha co shakara 4 beggar
761
+ cancel cheyyamo get money back
762
+ nt goin got somethin unless meetin 4 dinner lor haha wonder go time
763
+ congratul thank good friend å£ xma prize 2 claim easi call 08712103738 10p per minut bt
764
+ laugh loud oop sorri fun
765
+ da also forgot
766
+ today vodafon number end 4882 select receiv å£ award number match call 09064019014 receiv å£ award
767
+ turn heater heater set ltgt degre
768
+ batteri mr adewal uncl also known egbon
769
+ well like actual call someon punto would wors
770
+ like jerk
771
+ best line said love wait till day forget day realiz cannot forget good night
772
+ ever one foot
773
+ uncl atlanta wish guy great semest
774
+ love soo much donåõt understand special r 2 ring 2morrow love xxx
775
+ arr birthday today wish get oscar
776
+ ìï thk wat eat tonight
777
+ know lei like dun haf
778
+ babe back come back
779
+ hmmm mani player select
780
+ felt signific convey reason ese
781
+ sir need velusami sir date birth compani bank facil detail
782
+ thank meet monday
783
+ mobil club choos top qualiti item mobil 7cfca1a
784
+ sorri call later
785
+ touch permiss
786
+ wot want missi
787
+ offic around 4 privat messag go hospit
788
+ taxt massag argh ok lool
789
+ great run signific talk later
790
+ okay best
791
+ oki
792
+ height confid aeronaut professor wer calld amp wer askd 2 sit aeroplan aftr sat wer told dat plane ws made student dey hurri plane bt 1 move said made student
793
+ spjanuari male sale hot gay chat cheaper call 08709222922 nation rate 1 cheap 7 peak stop text call 08712460324 10pmin
794
+ sea lay rock rock envelop envelop paper paper 3 word
795
+ honey boo miss
796
+ boy made fun today ok problem sent one messag fun
797
+ rington club get uk singl chart mobil week choos top qualiti rington messag free charg
798
+ 2
799
+ fight world easi either win lose bt fightng some1 close dificult lose lose win still lose
800
+ solv case man found murder ltdecimalgt ltgt afternoon 1 wife call polic 2 question everyon 3 sir sleep murder took place 4 cook 5 pick veget 6 went 2 post offic 7 went 2 play 8 went 2 marriag polic arrest murder immedi repli reason r brilliant
801
+ arehol less commonli home see lingo let know wot earth finish make
802
+ oh gei happend tron mayb ill download 3d
803
+ ok stay night xavier sleep bag get tire
804
+ secret admir look 2 make contact r think signific special 09058094565
805
+ gobi art colleg
806
+ ìï go home liao ask dad pick 6
807
+ decemb mobil 11mth entitl updat latest colour camera mobil free call mobil updat co free 08002986906
808
+ ok lor anyway thk cannot get ticket co like quit late alreadi wan 2 go look 4 fren darren wif
809
+ somebodi set websit play hold use eve onlin spacebuck
810
+ ok come home half hour
811
+ bit smile hppnss drop tear sorrow part heart life heart like mine wil care forevr sht eg new episod cool goodfriend
812
+ ok instant messag sure time finish tomorrow want spend even co would vewi vewi lubli love xxx
813
+ ìï come lt 25 n pass lar
814
+ want cock hubbi away need real man 2 satisfi txt wife 89938 string action txt stop 2 end txt rec å£ otbox 731 la1 7w
815
+ custom may claim free camera phone upgrad pay go sim card loyalti call 0845 021 3680 end 28thfeb appli
816
+ quit know still get hold anyon cud pick bout 7 see pub
817
+ orh tot say still dun believ
818
+ ask say pleas messag
819
+ want 750 anytim network min 150 text new video phone five pound per week call 08002888812 repli deliveri tomorrow
820
+ messag mobil content order resent sht eg new episod cool previou attempt fail due network error queri customersqueri
821
+ pleas pleas send mail know rel come deliv know cost risk benefit anyth els thank
822
+ ujhhhhhhh comput ship address sandiago parantella lane poop
823
+ switch fone dammit
824
+ get 3 unless guy want come time sooner
825
+ xclusiv 2morow 28 soire special zouk nichol pari rose 2 ladi info 07946746291
826
+ mark work tomorrow get 5 work hous signific meet afterward
827
+ hello handsom find job lazi work toward get back net mummi boytoy miss
828
+ free messag singl find partner area 1000 real peopl wait chat chat 62220cncl send stopc 08717890890å£ per messag
829
+ chang window logoff sound
830
+ cannot believ said signific mani thing morn realli want say good morn love beauti morn see librari later
831
+ go dinner
832
+ sorri delay ye master
833
+ aiyar sorri lor forgot 2 tell
834
+ tell femal v throw decid get
835
+ pick rayan macleran
836
+ think chennai forgot come auction
837
+ hello love get interview today happi good boy think miss
838
+ first time everyth
839
+ ok bag
840
+ earli bird purchas yet
841
+ download sht eg new episod cool mani rington sht eg new episod cool like restrict 1000 2 choos even send 2 yr buddi txt sir 80082 å£
842
+ mon oki lor haha best cheap n gd food la ex oso oki depend whether wana eat western chines food den prefer
843
+ romcapspam everyon around respond well presenc sinc signific warm outgo bring real breath sunshin
844
+ okay cannot come search job
845
+ free 1st week entri 2 textpod 4 chanc 2 win 40gb ipod å£ cash everi wk txt vpod 81303 ts www custcar 08712405020
846
+ dun believ thk told
847
+ ye appt
848
+ jason say cool pick place like hour
849
+ ok anybodi ask tel
850
+ like cheap ‰ happi splash wine make feel better
851
+ know leh cannot rememb mayb lor signific wat time r meet tomorrow
852
+ said okay sorri
853
+ hear
854
+ realiz 40 year thousand old ladi run around tattoo
855
+ honeybe said sweetest world god laugh amp said waitu havnt met person read messag moral even god crack joke good morn
856
+ let know kick
857
+ ye complet form also utter wast
858
+ okay readi ltgt
859
+ realli skateboard despit fact get thrown wind bandag shit arm everi five minut
860
+ buy today ìï need c meh
861
+ worth reason around time smoke ga afford around someon tell appar happen somebodi want light
862
+ laugh take pic send
863
+ wat time finish lect today
864
+ cab avail pick drop door step
865
+ stop get ice cream go back
866
+ tomorrow go theatr signific come wherev call tell come tomorrow
867
+ howz person stori
868
+ messag great doctor india 1 drink appi fizz contain cancer caus age
869
+ ride equal unev mani peski cyclist around time night
870
+ sing hu think also import find someon femal know place well prefer citizen also smart help navig even thing like choos phone plan requir guidanc doubt ask especi girl
871
+ never blame day life good day give happi bad day give experi essenti life god bless good morn
872
+ good afternon love today hope good mayb interview wake miss babe passion kiss across sea
873
+ app class varaya elaya
874
+ need coz never go
875
+ want new video phone750 anytim network min 150 text five pound per week call 08000776320 repli deliveri tomorrow
876
+ text way cup stop work bu
877
+ know need get hotel got invit apologis cali sweet come english bloke weddin
878
+ urgent 1 week free membership å£ prize jackpot txt word claim 81010 www lccltd pobox 4403ldnw1a7rw18
879
+ yup thk cine better co need 2 go 2 plaza mah
880
+ work right
881
+ said mind go bedroom minut ok sed sexi mood came 5 minut latr wid cake wife
882
+ life spend someon lifetim may meaningless moment spent someon realli love mean life
883
+ get offici england poli rington colour flag yer mobil tonight game text tone flag 84199 optout txt eng stop box39822 w111wx å£
884
+ want snow freez windi
885
+ oh ok
886
+ bu love
887
+ exhaust train morn much wine pie sleep well
888
+ search onlin let know
889
+ ok least armand still around
890
+ love cuddl want hold strong arm right
891
+ alway celebr ny famili
892
+ call done
893
+ sorri meet call later
894
+ guy browsin compulsori
895
+ mm umma ask vava also come tell play later togeth
896
+ ye signific text pshew signific much
897
+ love work home
898
+ okay call close
899
+ wish great semest
900
+ one best dialogu cute reltnship wen die
901
+ much fight good nite
902
+ road signific cannot txt
903
+ need person give na
904
+ ye see ya dot
905
+ let know need anyth els salad desert someth mani beer shall get
906
+ hey realli pretti late want go lesson first join reach tp mrt
907
+ back bit long co accid a30 divert via wadebridg brilliant weekend thank speak soon lot love
908
+ day ì say ì cut hair paragon call hair sens ì noe much hair cut
909
+ come onlin today night
910
+ olol print forum post guy exact prob fix gpu replac hope ignor
911
+ run away frm walk slowli amp kill care enough stop
912
+ secret admir look 2 make contact r think signific special 09058094599
913
+ world famamu
914
+ hmm shall bring bottl wine keep us amus joke still bring bottl red white see tomorrow
915
+ night sweet sleep well see exorc emili rose may never sleep hug snog
916
+ ye realli great told kalli best cricket sachin world tough get
917
+ updat face book statu frequent
918
+ make dinner
919
+ da intro cover energi trend n pro n con brief descript nuclear fusion n oso brief histori iter n jet got 7 n half page
920
+ hey gorgeou man work mobil number good one babe squishi mwah
921
+ stop club tone repli stop mix see html term club tone cost gbp4 mfl
922
+ forgotten might coupl buck send tomorrow okay love ya
923
+ wake sinc check stuff saw true avail space pleas call embassi send mail
924
+ cough noth
925
+ awesom minut
926
+ doubl min txt orang 1 price linerent motorola sonyericsson babe free free call mobileupd8 08000839402 or2optout
927
+ hi elain today meet confirm
928
+ way stay oh
929
+ sorri dude know forgot even dan remind sorri hope guy fun
930
+ ok lor soni ericsson salesman ask shuhui say quit gd 2 use signific consid
931
+ okay come nordstrom done
932
+ okay bore come home
933
+ come room cannot come hous co hous still messi haha
934
+ oop ltgt
935
+ join today
936
+ freemsg hey got 1 video fone repli wild txt ill send pic hurri instant messag signific bore work xxx 18 150p stop2stop
937
+ hey pay salari de ltgt
938
+ turn friend stay whole show back today learn ltgt signific feel free go ahead smoke ltgt worth
939
+ big differ ltgt versu ltgt everi ltgt hr
940
+ let know contact settl room let us know ok
941
+ right phone someon number like
942
+ pleas send compani name saibaba colani
943
+ leav wif lar ìï wan carri meh signific heavi da num 98321561 familiar ì
944
+ home doc gave pain med say everyth fine
945
+ sure tri make xavier smoke want smoke told smoke much
946
+ still chanc search hard get tri
947
+ yeah probabl swing roommat finish girl
948
+ adult 18 content video shortli
949
+ 1 thing chang sentenc want 2 concentr educ career instant messag leav
950
+ tri contact repli offer video phone 750 anytim network min half price line rental camcord repli call 08000930705
951
+ come home one last time anyth trust
952
+ time come
953
+ let heart compass mind map soul guid never loos world sent via way2sm
954
+ never mind ok
955
+ okay sister kid
956
+ funer home audrey dad
957
+ hellodrivby0quit edrunk sorri iff pthi make senrd dancc 2 drum n basq fun 2nhite x ro xxxxxxx
958
+ plan
959
+ ugh leg hurt musta overdid mon
960
+ perform award calcul everi two month current one month period
961
+ uncl g check reward month
962
+ edison rightli said fool ask question wise man answer know us speechless viva good morn
963
+ exactli anyway far jide studi visit
964
+ cash current 500 pound maxim cash send cash 86688 150p cc 08708800282 hg row
965
+ good good job like entrepreneur
966
+ meet lunch la
967
+ g
968
+ ya one slow sht eg new episod cool poo
969
+ work go min
970
+ oh ye like tortur watch england
971
+ swt thought nver get tire littl thing 4 lovabl person coz littl thing occupi biggest part heart good ni8
972
+ call ok said call
973
+ probabl want pick
974
+ sure check happen around area
975
+ say slowli god love amp need heart blood ten special peopl amp c miracl tomorrow
976
+ go draw seri mani year south african soil
977
+ nah instant messag goin 2 wrk j wot bout
978
+ mind blastin tsunami occur rajnik stop swim indian ocean
979
+ brother transfer ltgt ltgt pa
980
+ hungri gay guy feel hungri 4 call 08718730555 10p stop text call 08712460324 10pmin
981
+ hope settl new school year wishin great day
982
+ night worri appt shame miss girl night quizz popcorn hair
983
+ move morphin
984
+ yetund sorri moji seem busi abl go shop pleas find way get want us get pleas forgiv repli free via yahoo messeng
985
+ ok prob
986
+ ta job avail let know pleas co realli need start work
987
+ anyway serious hit back otherwis light armand alway shit vomit
988
+ leav hous
989
+ roger ‰ probabl go rem 20
990
+ ugh want get bed signific warm
991
+ sir good morn hope good weekend call let know abl rais ltgt dad howev said would make rest avail mid feb amount still quit short hope would help good day abiola
992
+ instant messag sorri bout last nite wasnåõt fault spous pmt sumthin 4give think shldxxxx
993
+ urgent mobil å£ bonu caller prize 02 2nd attempt reach call 09066362220 soon posibl box97n7qp 150ppm
994
+ better still catch let ask sell ltgt
995
+ tabl occupi wait tree
996
+ plan usual stop find realli weed
997
+ gumbi special ltgt chees pizza 2 signific know doin tonight
998
+ stomach thru signific much trauma swear eat better lose weight
999
+ hospit da return home even
1000
+ hey want anyth buy
1001
+ ye babi need stretch open pussi
1002
+ jay get realli impati belliger
1003
+ hot live fantasi call 08707509020 20p per min ntt ltd peac box 1327 croydon cr9 5wb 0870
1004
+ send resum
1005
+ howz person stori
1006
+ actual mobil full messag work onlin need send ltgt sent messag wil explain later
1007
+ arun transfr amt
1008
+ haha dinner cousin
1009
+ super da replac murali
1010
+ idea
1011
+ chill anoth 6hr could sleep pain surgic emerg signific see unfold okay
1012
+ rememb hurt day satan impost pay price destini keep go sht eg new episod cool said pray get mind get
1013
+ short cute good person
1014
+ imagin final get sink bath put pace mayb even eat left also imagin feel cage cock surround bath water remind alway own enjoy cuck
1015
+ eh send wrongli lar
1016
+ ha ju ate honey action requir signific sweet
1017
+ ummmmmaah mani mani happi return day dear sweet heart happi birthday dear
1018
+ chile pleas ltdecimalgt hour drive come time sublet feb audit season
1019
+ peopl see msg think meet addict msging wrong bcoz know meet addict sweet friend bslvyl
1020
+ hello thanx take call got job start monday
1021
+ call said choos futur
1022
+ pleas accept one day beg chang number
1023
+ eh laptop got stock lei say mon muz come take look c got
1024
+ yo call get chanc friend mine want ask big order
1025
+ let know detail fri find co tom fri mention chines thank
1026
+ revers cheat mathemat
1027
+ still game
1028
+ goodmorn today late 2hr back pain
1029
+ somewher fredericksburg
1030
+ freemsg award free mini digit camera repli snap collect prize quizclub opt stop 80122300p sp ph
1031
+ sorri instant messag stil fuck last nite went tobe 430 got 4 work 630
1032
+ watch lor saw swatch one thk quit ok ard 116 need 2nd opinion leh
1033
+ stalk
1034
+ hey realli horni want chat see nake text hot 69698 text charg 150pm unsubscrib text stop 69698
1035
+ get opinion someth first
1036
+ much imag class
1037
+ rct thnq adrian text rgd vatian
1038
+ two letter copi co one messag speak soon
1039
+ oh ok wat email
1040
+ year mani mile
1041
+ free entri 2 wkli comp win fa cup final tkt 21st may 2005 text fa 87121 receiv entri question txt rate appli 08452810075over18
1042
+ right second got hit peopl first
1043
+ well nice bad cannot eat
1044
+ laptop take
1045
+ doubl min txt 4 6month free bluetooth orang avail soni nokia motorola phone call mobileupd8 08000839402 call2optout
1046
+ problem renew right away know detail
1047
+ glad follow dream
1048
+ nokia phone lovli
1049
+ gentl princess make sweet gentl love
1050
+ uncl boy need movi oh guid plu know torrent particularli legal system slow great day plu start co meet onlin honey moon
1051
+ buy newspap alreadi
1052
+ beliv come home
1053
+ go worri noth give money use
1054
+ good thing get connect bw
1055
+ wana plan trip sometm
1056
+ gd lor go shop got stuff wan 2 watch infern affair come lar
1057
+ puriti friendship two smile read forward messag smile see name good evng
1058
+ oop 4 got bit
1059
+ even brother like speak treat like aid patent
1060
+ beauti truth express face could seen everyon depress heart could understood love one good ni8
1061
+ laugh 1
1062
+ wat make peopl dearer de happi dat feel meet de pain feel miss dem
1063
+ plan pongal
1064
+ hey babe friend cancel still visit
1065
+ thank
1066
+ take someth pain move howev side next 6hr see doctor
1067
+ win year suppli cd 4 store choic worth å£ enter å£ weekli draw txt music 87066 ts www
1068
+ yup leav right back soon
1069
+ aaooooright work
1070
+ shall come get pickl
1071
+ hi ya babe x 4goten bout scammer get smart regular vodafon respond get prem rate messag no use also bewar
1072
+ great hope like man well endow ltgt inch
1073
+ sorri call later
1074
+ wnt buy bmw car urgent vri urgent shortag ltgt lac sourc arng di amt ltgt lac prob
1075
+ 4mth half price orang line rental latest camera phone 4 free phone 11mth call mobilesdirect free 08000938767 updat or2stoptxt
1076
+ ill babe soon
1077
+ alrit
1078
+ velli good ye pleas
1079
+ start search get job day great potenti talent
1080
+ never blame day life good day give happi bad day give experi essenti life god bless good morn
1081
+ pathaya enketa maraikara pa
1082
+ hey book pilat yoga lesson alreadi haha
1083
+ thank vote sing along star karaok mobil free link repli sing
1084
+ everi day use sleep ltgt signific
1085
+ yay better told 5 girl either
1086
+ laugh loud nah bad thank good babe home quit realiti check day anyth websit
1087
+ sent price mean ltgt g
1088
+ decemb mobil 11mth entitl updat latest colour camera mobil free call mobil updat co free 08002986906
1089
+ awak oh
1090
+ shame mayb cld meet hr tomo
1091
+ 123 congratul week competit draw å£ prize claim call 09050002311 b4280703 short messag servic 08718727868 18 150ppm
1092
+ cannot pick phone right pleas send messag
1093
+ sorri meet call later
1094
+ miss tri figur much money everyon ga alcohol jay tri figur weed budget
1095
+ urgent tri contact today draw show å£ prize guarante call 09050003091 land line claim c52 valid 12hr
1096
+ water log desert geoenvironment implic
1097
+ joy father john john joy father an th hav ltgt iq ia question tri answer
1098
+ haiyoh mayb hamster jealou million
1099
+ oh unintent bad time great finger train play along give fifteen min warn
1100
+ ì wait 4 bu stop aft lect lar dun c ì go get car come back n pick ì
1101
+ umma say anyth
1102
+ doin babi girl hope okay everi time call ure phone miss get touch
1103
+ send number give repli tomorrow morn said like ok
1104
+ well told other marri
1105
+ pleas protect e sib never ask sensit inform like password pin thru email never share password anybodi
1106
+ guess pub instant messag instant messag sht eg new episod cool happi sht eg new episod cool pig clover whatev say
1107
+ let math good
1108
+ g class earli tomorrow thu tri smoke ltgt
1109
+ babe hope ok shit night sleep fell asleep 5 knacker iåõm dread work tonight thou upto tonight x
1110
+ repli win å£ weekli profession sport tiger wood play send stop 87239 end servic
1111
+ gent tri contact last weekend draw show å£ prize guarante call 09064012160 claim code k52 valid 12hr 150ppm
1112
+ stop stori told return say order
1113
+ sent jd custom servic cum account execut mail id detail contact us
1114
+ read shame tell take run blame 4 ever realli 4 ever long time
1115
+ well meant sht eg new episod cool oppos drunken night
1116
+ suppos make still town though
data/processed/test_labels.csv ADDED
@@ -0,0 +1,1116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ target
2
+ 0
3
+ 0
4
+ 0
5
+ 1
6
+ 0
7
+ 0
8
+ 0
9
+ 0
10
+ 0
11
+ 0
12
+ 0
13
+ 0
14
+ 0
15
+ 0
16
+ 0
17
+ 0
18
+ 0
19
+ 0
20
+ 0
21
+ 0
22
+ 0
23
+ 0
24
+ 0
25
+ 1
26
+ 0
27
+ 0
28
+ 0
29
+ 0
30
+ 0
31
+ 0
32
+ 0
33
+ 0
34
+ 0
35
+ 0
36
+ 0
37
+ 1
38
+ 0
39
+ 0
40
+ 0
41
+ 0
42
+ 1
43
+ 0
44
+ 0
45
+ 0
46
+ 1
47
+ 0
48
+ 0
49
+ 0
50
+ 0
51
+ 0
52
+ 0
53
+ 0
54
+ 0
55
+ 0
56
+ 0
57
+ 0
58
+ 0
59
+ 0
60
+ 0
61
+ 0
62
+ 0
63
+ 0
64
+ 0
65
+ 0
66
+ 0
67
+ 1
68
+ 0
69
+ 1
70
+ 0
71
+ 0
72
+ 0
73
+ 0
74
+ 0
75
+ 0
76
+ 0
77
+ 0
78
+ 0
79
+ 0
80
+ 0
81
+ 0
82
+ 0
83
+ 0
84
+ 0
85
+ 1
86
+ 0
87
+ 0
88
+ 0
89
+ 0
90
+ 0
91
+ 1
92
+ 0
93
+ 0
94
+ 0
95
+ 0
96
+ 1
97
+ 0
98
+ 0
99
+ 0
100
+ 0
101
+ 0
102
+ 0
103
+ 0
104
+ 0
105
+ 0
106
+ 0
107
+ 0
108
+ 0
109
+ 0
110
+ 0
111
+ 0
112
+ 0
113
+ 0
114
+ 0
115
+ 0
116
+ 0
117
+ 0
118
+ 0
119
+ 0
120
+ 0
121
+ 0
122
+ 0
123
+ 0
124
+ 1
125
+ 1
126
+ 0
127
+ 0
128
+ 1
129
+ 1
130
+ 0
131
+ 0
132
+ 0
133
+ 0
134
+ 0
135
+ 1
136
+ 0
137
+ 0
138
+ 0
139
+ 0
140
+ 0
141
+ 0
142
+ 0
143
+ 0
144
+ 0
145
+ 0
146
+ 0
147
+ 0
148
+ 0
149
+ 0
150
+ 0
151
+ 0
152
+ 0
153
+ 0
154
+ 0
155
+ 0
156
+ 0
157
+ 0
158
+ 0
159
+ 0
160
+ 0
161
+ 0
162
+ 0
163
+ 0
164
+ 1
165
+ 0
166
+ 0
167
+ 1
168
+ 0
169
+ 0
170
+ 1
171
+ 0
172
+ 0
173
+ 0
174
+ 0
175
+ 0
176
+ 0
177
+ 0
178
+ 0
179
+ 0
180
+ 0
181
+ 0
182
+ 0
183
+ 0
184
+ 0
185
+ 0
186
+ 0
187
+ 1
188
+ 0
189
+ 0
190
+ 0
191
+ 0
192
+ 0
193
+ 0
194
+ 0
195
+ 0
196
+ 0
197
+ 0
198
+ 1
199
+ 0
200
+ 1
201
+ 0
202
+ 0
203
+ 0
204
+ 0
205
+ 0
206
+ 1
207
+ 0
208
+ 0
209
+ 1
210
+ 0
211
+ 0
212
+ 0
213
+ 0
214
+ 0
215
+ 1
216
+ 1
217
+ 0
218
+ 1
219
+ 1
220
+ 0
221
+ 1
222
+ 0
223
+ 0
224
+ 1
225
+ 0
226
+ 0
227
+ 0
228
+ 0
229
+ 0
230
+ 0
231
+ 0
232
+ 0
233
+ 1
234
+ 1
235
+ 0
236
+ 0
237
+ 1
238
+ 0
239
+ 0
240
+ 0
241
+ 0
242
+ 0
243
+ 0
244
+ 1
245
+ 0
246
+ 0
247
+ 0
248
+ 0
249
+ 1
250
+ 0
251
+ 0
252
+ 0
253
+ 0
254
+ 0
255
+ 1
256
+ 0
257
+ 0
258
+ 0
259
+ 0
260
+ 1
261
+ 0
262
+ 0
263
+ 0
264
+ 0
265
+ 0
266
+ 0
267
+ 1
268
+ 0
269
+ 1
270
+ 0
271
+ 0
272
+ 0
273
+ 1
274
+ 0
275
+ 0
276
+ 0
277
+ 0
278
+ 0
279
+ 0
280
+ 0
281
+ 0
282
+ 0
283
+ 0
284
+ 0
285
+ 0
286
+ 1
287
+ 0
288
+ 0
289
+ 0
290
+ 1
291
+ 1
292
+ 0
293
+ 0
294
+ 0
295
+ 0
296
+ 0
297
+ 0
298
+ 1
299
+ 0
300
+ 0
301
+ 0
302
+ 0
303
+ 0
304
+ 0
305
+ 0
306
+ 0
307
+ 0
308
+ 1
309
+ 0
310
+ 0
311
+ 0
312
+ 0
313
+ 0
314
+ 0
315
+ 0
316
+ 0
317
+ 0
318
+ 0
319
+ 0
320
+ 0
321
+ 0
322
+ 0
323
+ 0
324
+ 0
325
+ 0
326
+ 0
327
+ 0
328
+ 1
329
+ 1
330
+ 0
331
+ 0
332
+ 0
333
+ 0
334
+ 0
335
+ 0
336
+ 0
337
+ 0
338
+ 0
339
+ 0
340
+ 0
341
+ 0
342
+ 0
343
+ 0
344
+ 0
345
+ 0
346
+ 0
347
+ 0
348
+ 0
349
+ 0
350
+ 0
351
+ 0
352
+ 0
353
+ 0
354
+ 0
355
+ 0
356
+ 0
357
+ 0
358
+ 0
359
+ 1
360
+ 0
361
+ 0
362
+ 0
363
+ 1
364
+ 1
365
+ 0
366
+ 0
367
+ 0
368
+ 1
369
+ 0
370
+ 0
371
+ 0
372
+ 0
373
+ 0
374
+ 0
375
+ 0
376
+ 0
377
+ 0
378
+ 0
379
+ 0
380
+ 0
381
+ 0
382
+ 0
383
+ 1
384
+ 0
385
+ 0
386
+ 0
387
+ 0
388
+ 0
389
+ 0
390
+ 0
391
+ 0
392
+ 0
393
+ 0
394
+ 0
395
+ 1
396
+ 0
397
+ 0
398
+ 0
399
+ 0
400
+ 0
401
+ 0
402
+ 0
403
+ 0
404
+ 0
405
+ 0
406
+ 0
407
+ 0
408
+ 0
409
+ 0
410
+ 0
411
+ 0
412
+ 0
413
+ 0
414
+ 0
415
+ 0
416
+ 0
417
+ 0
418
+ 0
419
+ 0
420
+ 1
421
+ 0
422
+ 0
423
+ 0
424
+ 0
425
+ 0
426
+ 0
427
+ 0
428
+ 0
429
+ 0
430
+ 0
431
+ 0
432
+ 1
433
+ 0
434
+ 0
435
+ 1
436
+ 0
437
+ 0
438
+ 0
439
+ 0
440
+ 0
441
+ 1
442
+ 0
443
+ 0
444
+ 0
445
+ 0
446
+ 0
447
+ 0
448
+ 0
449
+ 0
450
+ 0
451
+ 1
452
+ 0
453
+ 0
454
+ 0
455
+ 0
456
+ 1
457
+ 1
458
+ 0
459
+ 0
460
+ 0
461
+ 0
462
+ 0
463
+ 0
464
+ 0
465
+ 0
466
+ 0
467
+ 0
468
+ 0
469
+ 1
470
+ 0
471
+ 0
472
+ 0
473
+ 0
474
+ 0
475
+ 0
476
+ 0
477
+ 0
478
+ 0
479
+ 0
480
+ 1
481
+ 0
482
+ 0
483
+ 0
484
+ 1
485
+ 0
486
+ 0
487
+ 0
488
+ 0
489
+ 0
490
+ 0
491
+ 0
492
+ 0
493
+ 0
494
+ 0
495
+ 0
496
+ 0
497
+ 0
498
+ 0
499
+ 0
500
+ 0
501
+ 0
502
+ 0
503
+ 0
504
+ 0
505
+ 0
506
+ 0
507
+ 0
508
+ 0
509
+ 0
510
+ 0
511
+ 0
512
+ 0
513
+ 1
514
+ 0
515
+ 0
516
+ 0
517
+ 0
518
+ 0
519
+ 0
520
+ 0
521
+ 0
522
+ 0
523
+ 0
524
+ 0
525
+ 0
526
+ 0
527
+ 0
528
+ 0
529
+ 0
530
+ 0
531
+ 0
532
+ 0
533
+ 0
534
+ 0
535
+ 0
536
+ 0
537
+ 1
538
+ 1
539
+ 1
540
+ 0
541
+ 1
542
+ 0
543
+ 0
544
+ 0
545
+ 1
546
+ 0
547
+ 0
548
+ 0
549
+ 0
550
+ 0
551
+ 0
552
+ 0
553
+ 0
554
+ 0
555
+ 0
556
+ 0
557
+ 0
558
+ 0
559
+ 1
560
+ 0
561
+ 0
562
+ 0
563
+ 0
564
+ 1
565
+ 0
566
+ 0
567
+ 0
568
+ 0
569
+ 0
570
+ 0
571
+ 0
572
+ 1
573
+ 0
574
+ 0
575
+ 1
576
+ 1
577
+ 0
578
+ 0
579
+ 1
580
+ 0
581
+ 1
582
+ 0
583
+ 0
584
+ 0
585
+ 0
586
+ 0
587
+ 1
588
+ 0
589
+ 0
590
+ 0
591
+ 1
592
+ 0
593
+ 0
594
+ 0
595
+ 0
596
+ 0
597
+ 0
598
+ 0
599
+ 0
600
+ 0
601
+ 0
602
+ 1
603
+ 0
604
+ 0
605
+ 1
606
+ 0
607
+ 0
608
+ 1
609
+ 1
610
+ 0
611
+ 0
612
+ 0
613
+ 0
614
+ 0
615
+ 0
616
+ 0
617
+ 0
618
+ 1
619
+ 0
620
+ 0
621
+ 0
622
+ 0
623
+ 0
624
+ 0
625
+ 0
626
+ 0
627
+ 0
628
+ 1
629
+ 0
630
+ 0
631
+ 0
632
+ 0
633
+ 0
634
+ 0
635
+ 1
636
+ 0
637
+ 0
638
+ 0
639
+ 0
640
+ 0
641
+ 0
642
+ 1
643
+ 0
644
+ 1
645
+ 1
646
+ 0
647
+ 0
648
+ 0
649
+ 0
650
+ 0
651
+ 0
652
+ 0
653
+ 0
654
+ 0
655
+ 0
656
+ 0
657
+ 0
658
+ 0
659
+ 0
660
+ 0
661
+ 0
662
+ 0
663
+ 0
664
+ 0
665
+ 0
666
+ 0
667
+ 0
668
+ 0
669
+ 0
670
+ 0
671
+ 0
672
+ 1
673
+ 0
674
+ 0
675
+ 0
676
+ 0
677
+ 0
678
+ 0
679
+ 0
680
+ 0
681
+ 0
682
+ 0
683
+ 0
684
+ 0
685
+ 0
686
+ 1
687
+ 0
688
+ 0
689
+ 0
690
+ 0
691
+ 1
692
+ 0
693
+ 1
694
+ 0
695
+ 0
696
+ 0
697
+ 0
698
+ 0
699
+ 0
700
+ 0
701
+ 0
702
+ 0
703
+ 1
704
+ 1
705
+ 0
706
+ 0
707
+ 0
708
+ 0
709
+ 0
710
+ 0
711
+ 0
712
+ 0
713
+ 0
714
+ 0
715
+ 0
716
+ 0
717
+ 0
718
+ 0
719
+ 1
720
+ 0
721
+ 1
722
+ 0
723
+ 1
724
+ 0
725
+ 1
726
+ 0
727
+ 0
728
+ 0
729
+ 0
730
+ 0
731
+ 0
732
+ 0
733
+ 0
734
+ 1
735
+ 0
736
+ 0
737
+ 0
738
+ 0
739
+ 0
740
+ 0
741
+ 1
742
+ 0
743
+ 0
744
+ 0
745
+ 1
746
+ 0
747
+ 1
748
+ 0
749
+ 0
750
+ 0
751
+ 1
752
+ 0
753
+ 1
754
+ 0
755
+ 1
756
+ 1
757
+ 0
758
+ 0
759
+ 0
760
+ 0
761
+ 0
762
+ 0
763
+ 1
764
+ 0
765
+ 0
766
+ 1
767
+ 0
768
+ 0
769
+ 0
770
+ 0
771
+ 0
772
+ 0
773
+ 0
774
+ 0
775
+ 0
776
+ 0
777
+ 0
778
+ 0
779
+ 0
780
+ 0
781
+ 0
782
+ 0
783
+ 1
784
+ 0
785
+ 0
786
+ 0
787
+ 0
788
+ 0
789
+ 0
790
+ 0
791
+ 0
792
+ 0
793
+ 1
794
+ 0
795
+ 0
796
+ 0
797
+ 1
798
+ 0
799
+ 0
800
+ 0
801
+ 0
802
+ 0
803
+ 0
804
+ 1
805
+ 0
806
+ 0
807
+ 1
808
+ 0
809
+ 0
810
+ 0
811
+ 0
812
+ 0
813
+ 0
814
+ 1
815
+ 1
816
+ 0
817
+ 0
818
+ 0
819
+ 1
820
+ 1
821
+ 0
822
+ 0
823
+ 0
824
+ 0
825
+ 1
826
+ 0
827
+ 0
828
+ 1
829
+ 0
830
+ 0
831
+ 0
832
+ 0
833
+ 0
834
+ 0
835
+ 0
836
+ 0
837
+ 0
838
+ 0
839
+ 0
840
+ 0
841
+ 1
842
+ 0
843
+ 1
844
+ 0
845
+ 1
846
+ 0
847
+ 0
848
+ 0
849
+ 0
850
+ 0
851
+ 0
852
+ 0
853
+ 0
854
+ 1
855
+ 0
856
+ 0
857
+ 0
858
+ 0
859
+ 0
860
+ 0
861
+ 0
862
+ 0
863
+ 0
864
+ 0
865
+ 0
866
+ 0
867
+ 0
868
+ 0
869
+ 0
870
+ 0
871
+ 0
872
+ 0
873
+ 0
874
+ 0
875
+ 1
876
+ 0
877
+ 0
878
+ 1
879
+ 0
880
+ 0
881
+ 0
882
+ 0
883
+ 1
884
+ 0
885
+ 0
886
+ 0
887
+ 0
888
+ 0
889
+ 0
890
+ 0
891
+ 0
892
+ 0
893
+ 0
894
+ 0
895
+ 0
896
+ 0
897
+ 0
898
+ 0
899
+ 0
900
+ 0
901
+ 0
902
+ 0
903
+ 0
904
+ 0
905
+ 0
906
+ 0
907
+ 0
908
+ 0
909
+ 0
910
+ 0
911
+ 0
912
+ 1
913
+ 0
914
+ 0
915
+ 0
916
+ 0
917
+ 0
918
+ 0
919
+ 0
920
+ 0
921
+ 1
922
+ 0
923
+ 0
924
+ 0
925
+ 0
926
+ 1
927
+ 0
928
+ 0
929
+ 0
930
+ 0
931
+ 0
932
+ 0
933
+ 0
934
+ 0
935
+ 0
936
+ 1
937
+ 0
938
+ 0
939
+ 0
940
+ 0
941
+ 0
942
+ 0
943
+ 0
944
+ 0
945
+ 0
946
+ 0
947
+ 0
948
+ 1
949
+ 0
950
+ 1
951
+ 0
952
+ 0
953
+ 0
954
+ 0
955
+ 0
956
+ 0
957
+ 0
958
+ 0
959
+ 0
960
+ 0
961
+ 0
962
+ 0
963
+ 0
964
+ 1
965
+ 0
966
+ 0
967
+ 0
968
+ 0
969
+ 0
970
+ 0
971
+ 0
972
+ 0
973
+ 0
974
+ 0
975
+ 0
976
+ 0
977
+ 0
978
+ 0
979
+ 0
980
+ 1
981
+ 0
982
+ 0
983
+ 0
984
+ 0
985
+ 0
986
+ 0
987
+ 0
988
+ 0
989
+ 0
990
+ 0
991
+ 0
992
+ 0
993
+ 1
994
+ 0
995
+ 0
996
+ 0
997
+ 0
998
+ 0
999
+ 0
1000
+ 0
1001
+ 0
1002
+ 0
1003
+ 1
1004
+ 0
1005
+ 0
1006
+ 0
1007
+ 0
1008
+ 0
1009
+ 0
1010
+ 0
1011
+ 0
1012
+ 0
1013
+ 0
1014
+ 0
1015
+ 0
1016
+ 0
1017
+ 0
1018
+ 0
1019
+ 0
1020
+ 0
1021
+ 0
1022
+ 0
1023
+ 0
1024
+ 0
1025
+ 0
1026
+ 0
1027
+ 0
1028
+ 0
1029
+ 0
1030
+ 1
1031
+ 0
1032
+ 0
1033
+ 0
1034
+ 1
1035
+ 0
1036
+ 0
1037
+ 1
1038
+ 0
1039
+ 0
1040
+ 0
1041
+ 1
1042
+ 0
1043
+ 0
1044
+ 0
1045
+ 1
1046
+ 0
1047
+ 0
1048
+ 0
1049
+ 0
1050
+ 0
1051
+ 0
1052
+ 0
1053
+ 0
1054
+ 0
1055
+ 0
1056
+ 0
1057
+ 0
1058
+ 0
1059
+ 0
1060
+ 0
1061
+ 0
1062
+ 0
1063
+ 0
1064
+ 0
1065
+ 0
1066
+ 0
1067
+ 1
1068
+ 0
1069
+ 0
1070
+ 0
1071
+ 1
1072
+ 0
1073
+ 0
1074
+ 0
1075
+ 1
1076
+ 0
1077
+ 0
1078
+ 0
1079
+ 0
1080
+ 0
1081
+ 0
1082
+ 0
1083
+ 1
1084
+ 0
1085
+ 0
1086
+ 0
1087
+ 0
1088
+ 1
1089
+ 0
1090
+ 0
1091
+ 1
1092
+ 0
1093
+ 0
1094
+ 0
1095
+ 1
1096
+ 0
1097
+ 0
1098
+ 0
1099
+ 0
1100
+ 0
1101
+ 0
1102
+ 0
1103
+ 0
1104
+ 0
1105
+ 0
1106
+ 0
1107
+ 0
1108
+ 0
1109
+ 0
1110
+ 1
1111
+ 1
1112
+ 0
1113
+ 0
1114
+ 0
1115
+ 0
1116
+ 0
data/raw.dvc ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ outs:
2
+ - md5: a885737a29b50824c4c3f9a8deea1662.dir
3
+ size: 503663
4
+ nfiles: 2
5
+ hash: md5
6
+ path: raw
docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ email-classifier:
5
+ build:
6
+ context: .
7
+ dockerfile: Dockerfile
8
+ image: email-spam-classifier
9
+ ports:
10
+ - "8000:8000"
11
+ - "8501:8501"
12
+ volumes:
13
+ - .:/app
14
+ - /app/.venv
15
+ environment:
16
+ - ENVIRONMENT=production
17
+ - DEBUG=false
18
+ - API_BASE_URL=http://localhost:8000
19
+
20
+ networks:
21
+ spam-classifier-network:
22
+ driver: bridge
docs/.gitkeep ADDED
File without changes