Pujan Neupane
commited on
Commit
·
e9f0d54
1
Parent(s):
992f09e
Project : pushing all the files to hugging face
Browse files- .gitignore +54 -0
- Ai-Text-Detector/model/merges.txt +0 -0
- Ai-Text-Detector/model/special_tokens_map.json +30 -0
- Ai-Text-Detector/model/tokenizer.json +0 -0
- Ai-Text-Detector/model/tokenizer_config.json +28 -0
- Ai-Text-Detector/model/vocab.json +0 -0
- Ai-Text-Detector/model_weights.pth +3 -0
- Dockerfile +33 -0
- HuggingFace/main.py +18 -0
- HuggingFace/readme.md +61 -0
- Machine-learning/.gitattributes +2 -0
- Machine-learning/README.md +289 -0
- app.py +91 -0
- requirements.txt +6 -0
.gitignore
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ---- Python Environment ----
|
| 2 |
+
venv/
|
| 3 |
+
.venv/
|
| 4 |
+
env/
|
| 5 |
+
ENV/
|
| 6 |
+
*.pyc
|
| 7 |
+
*.pyo
|
| 8 |
+
*.pyd
|
| 9 |
+
__pycache__/
|
| 10 |
+
**/__pycache__/
|
| 11 |
+
|
| 12 |
+
# ---- VS Code / IDEs ----
|
| 13 |
+
.vscode/
|
| 14 |
+
.idea/
|
| 15 |
+
*.swp
|
| 16 |
+
|
| 17 |
+
# ---- Jupyter / IPython ----
|
| 18 |
+
.ipynb_checkpoints/
|
| 19 |
+
*.ipynb
|
| 20 |
+
|
| 21 |
+
# ---- Model & Data Artifacts ----
|
| 22 |
+
*.pt
|
| 23 |
+
*.h5
|
| 24 |
+
*.ckpt
|
| 25 |
+
*.onnx
|
| 26 |
+
*.joblib
|
| 27 |
+
*.pkl
|
| 28 |
+
|
| 29 |
+
# ---- Hugging Face Cache ----
|
| 30 |
+
~/.cache/huggingface/
|
| 31 |
+
huggingface_cache/
|
| 32 |
+
|
| 33 |
+
# ---- Logs and Dumps ----
|
| 34 |
+
*.log
|
| 35 |
+
*.out
|
| 36 |
+
*.err
|
| 37 |
+
|
| 38 |
+
# ---- Build Artifacts ----
|
| 39 |
+
build/
|
| 40 |
+
dist/
|
| 41 |
+
*.egg-info/
|
| 42 |
+
|
| 43 |
+
# ---- System Files ----
|
| 44 |
+
.DS_Store
|
| 45 |
+
Thumbs.db
|
| 46 |
+
|
| 47 |
+
# ---- Environment Configs ----
|
| 48 |
+
.env
|
| 49 |
+
.env.*
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ---- Node Projects (if applicable) ----
|
| 53 |
+
node_modules/
|
| 54 |
+
|
Ai-Text-Detector/model/merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Ai-Text-Detector/model/special_tokens_map.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": {
|
| 3 |
+
"content": "<|endoftext|>",
|
| 4 |
+
"lstrip": false,
|
| 5 |
+
"normalized": true,
|
| 6 |
+
"rstrip": false,
|
| 7 |
+
"single_word": false
|
| 8 |
+
},
|
| 9 |
+
"eos_token": {
|
| 10 |
+
"content": "<|endoftext|>",
|
| 11 |
+
"lstrip": false,
|
| 12 |
+
"normalized": true,
|
| 13 |
+
"rstrip": false,
|
| 14 |
+
"single_word": false
|
| 15 |
+
},
|
| 16 |
+
"pad_token": {
|
| 17 |
+
"content": "<|endoftext|>",
|
| 18 |
+
"lstrip": false,
|
| 19 |
+
"normalized": true,
|
| 20 |
+
"rstrip": false,
|
| 21 |
+
"single_word": false
|
| 22 |
+
},
|
| 23 |
+
"unk_token": {
|
| 24 |
+
"content": "<|endoftext|>",
|
| 25 |
+
"lstrip": false,
|
| 26 |
+
"normalized": true,
|
| 27 |
+
"rstrip": false,
|
| 28 |
+
"single_word": false
|
| 29 |
+
}
|
| 30 |
+
}
|
Ai-Text-Detector/model/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Ai-Text-Detector/model/tokenizer_config.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"added_tokens_decoder": {
|
| 4 |
+
"50256": {
|
| 5 |
+
"content": "<|endoftext|>",
|
| 6 |
+
"lstrip": false,
|
| 7 |
+
"normalized": true,
|
| 8 |
+
"rstrip": false,
|
| 9 |
+
"single_word": false,
|
| 10 |
+
"special": true
|
| 11 |
+
}
|
| 12 |
+
},
|
| 13 |
+
"bos_token": "<|endoftext|>",
|
| 14 |
+
"clean_up_tokenization_spaces": false,
|
| 15 |
+
"eos_token": "<|endoftext|>",
|
| 16 |
+
"extra_special_tokens": {},
|
| 17 |
+
"max_length": 1024,
|
| 18 |
+
"model_max_length": 1024,
|
| 19 |
+
"pad_to_multiple_of": null,
|
| 20 |
+
"pad_token": "<|endoftext|>",
|
| 21 |
+
"pad_token_type_id": 0,
|
| 22 |
+
"padding_side": "right",
|
| 23 |
+
"stride": 0,
|
| 24 |
+
"tokenizer_class": "GPT2Tokenizer",
|
| 25 |
+
"truncation_side": "right",
|
| 26 |
+
"truncation_strategy": "longest_first",
|
| 27 |
+
"unk_token": "<|endoftext|>"
|
| 28 |
+
}
|
Ai-Text-Detector/model/vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Ai-Text-Detector/model_weights.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:702042483ae656e9c286660ad82dd9b555d481c800c0d3adbccd22a3505e1c8c
|
| 3 |
+
size 497813466
|
Dockerfile
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use the latest slim Python 3.11 image
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# Set environment variables
|
| 5 |
+
ENV HOME=/home/user \
|
| 6 |
+
PATH=/home/user/.local/bin:$PATH \
|
| 7 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 8 |
+
PYTHONUNBUFFERED=1
|
| 9 |
+
|
| 10 |
+
# Install system dependencies
|
| 11 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 12 |
+
build-essential \
|
| 13 |
+
git \
|
| 14 |
+
curl \
|
| 15 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 16 |
+
|
| 17 |
+
# Create a non-root user for safety
|
| 18 |
+
RUN useradd -ms /bin/bash user
|
| 19 |
+
USER user
|
| 20 |
+
WORKDIR $HOME/app
|
| 21 |
+
|
| 22 |
+
# Copy app source code
|
| 23 |
+
COPY --chown=user . .
|
| 24 |
+
|
| 25 |
+
# Install Python dependencies
|
| 26 |
+
RUN pip install --no-cache-dir --upgrade pip \
|
| 27 |
+
&& pip install --no-cache-dir -r requirements.txt
|
| 28 |
+
|
| 29 |
+
# Expose port
|
| 30 |
+
EXPOSE 7860
|
| 31 |
+
|
| 32 |
+
# Start the FastAPI app using uvicorn
|
| 33 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
HuggingFace/main.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from huggingface_hub import Repository
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def download_repo():
|
| 6 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 7 |
+
if not hf_token:
|
| 8 |
+
raise ValueError("HF_TOKEN not found in environment variables.")
|
| 9 |
+
|
| 10 |
+
repo_id = "Pujan-Dev/test"
|
| 11 |
+
local_dir = "../Ai-Text-Detector/"
|
| 12 |
+
|
| 13 |
+
repo = Repository(local_dir, clone_from=repo_id, token=hf_token)
|
| 14 |
+
print(f"Repository downloaded to: {local_dir}")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
download_repo()
|
HuggingFace/readme.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
### Hugging Face CLI Tool
|
| 2 |
+
|
| 3 |
+
This CLI tool allows you to **upload** and **download** models from Hugging Face repositories. It requires an **Hugging Face Access Token (`HF_TOKEN`)** for authentication, especially for private repositories.
|
| 4 |
+
|
| 5 |
+
### Prerequisites
|
| 6 |
+
|
| 7 |
+
1. **Install Hugging Face Hub**:
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
pip install huggingface_hub
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
2. **Get HF_TOKEN**:
|
| 14 |
+
- Log in to [Hugging Face](https://huggingface.co/).
|
| 15 |
+
- Go to **Settings** → **Access Tokens** → **Create a new token** with `read` and `write` permissions.
|
| 16 |
+
- Save the token.
|
| 17 |
+
|
| 18 |
+
### Usage
|
| 19 |
+
|
| 20 |
+
1. **Set the Token**:
|
| 21 |
+
|
| 22 |
+
- **Linux/macOS**:
|
| 23 |
+
```bash
|
| 24 |
+
export HF_TOKEN=your_token_here
|
| 25 |
+
```
|
| 26 |
+
- **Windows (CMD)**:
|
| 27 |
+
```bash
|
| 28 |
+
set HF_TOKEN=your_token_here
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
2. **Download Model**:
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
python main.py --download --repo-id <repo_name> --save-dir <local_save_path>
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
3. **Upload Model**:
|
| 38 |
+
```bash
|
| 39 |
+
python main.py --upload --repo-id <repo_name> --model-path <local_model_path>
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
### Example
|
| 43 |
+
|
| 44 |
+
To download a model:
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
python main.py
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
### Authentication
|
| 51 |
+
|
| 52 |
+
Ensure you set `HF_TOKEN` to access private repositories. If not set, the script will raise an error.
|
| 53 |
+
Here’s a clearer and more polished version of that note:
|
| 54 |
+
|
| 55 |
+
---
|
| 56 |
+
|
| 57 |
+
### ⚠️ Note
|
| 58 |
+
|
| 59 |
+
**Make sure to run this script from the `HuggingFace` directory to ensure correct path resolution and functionality.**
|
| 60 |
+
|
| 61 |
+
---
|
Machine-learning/.gitattributes
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
Ai-Text-Detector/model_weights.pth filter=lfs diff=lfs merge=lfs -text
|
Machine-learning/README.md
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
### **FastAPI AI**
|
| 2 |
+
|
| 3 |
+
This FastAPI app loads a GPT-2 model, tokenizes input text, classifies it, and returns whether the text is AI-generated or human-written.
|
| 4 |
+
|
| 5 |
+
### **install Dependencies**
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
pip install -r requirements.txt
|
| 9 |
+
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
This command installs all the dependencies listed in the `requirements.txt` file. It ensures that your environment has the required packages to run the project smoothly.
|
| 13 |
+
|
| 14 |
+
**NOTE: IF YOU HAVE DONE ANY CHANGES DON'NT FORGOT TO PUT IT IN THE REQUIREMENTS.TXT USING `bash pip freeze > requirements.txt `**
|
| 15 |
+
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
### **Functions**
|
| 19 |
+
|
| 20 |
+
1. **`load_model()`**
|
| 21 |
+
Loads the GPT-2 model and tokenizer from specified paths.
|
| 22 |
+
|
| 23 |
+
2. **`lifespan()`**
|
| 24 |
+
Manages the app's lifecycle: loads the model at startup and handles cleanup on shutdown.
|
| 25 |
+
|
| 26 |
+
3. **`classify_text_sync()`**
|
| 27 |
+
Synchronously tokenizes input text and classifies it using the GPT-2 model. Returns the classification and perplexity.
|
| 28 |
+
|
| 29 |
+
4. **`classify_text()`**
|
| 30 |
+
Asynchronously executes `classify_text_sync()` in a thread pool to ensure non-blocking processing.
|
| 31 |
+
|
| 32 |
+
5. **`analyze_text()`**
|
| 33 |
+
**POST** endpoint: accepts text input, classifies it using `classify_text()`, and returns the result with perplexity.
|
| 34 |
+
|
| 35 |
+
6. **`health_check()`**
|
| 36 |
+
**GET** endpoint: simple health check to confirm the API is running.
|
| 37 |
+
|
| 38 |
+
---
|
| 39 |
+
|
| 40 |
+
### **Code Overview**
|
| 41 |
+
|
| 42 |
+
```python
|
| 43 |
+
executor = ThreadPoolExecutor(max_workers=2)
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
- **`ThreadPoolExecutor(max_workers=2)`** limits the number of concurrent threads (tasks) per worker process to 2 for text classification. This helps control resource usage and prevent overloading the server.
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
### **Running and Load Balancing:**
|
| 51 |
+
|
| 52 |
+
To run the app in production with load balancing:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
uvicorn app:app --host 0.0.0.0 --port 8000 --workers 4
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
This command launches the FastAPI app with **4 worker processes**, allowing it to handle multiple requests concurrently.
|
| 59 |
+
|
| 60 |
+
### **Concurrency Explained:**
|
| 61 |
+
|
| 62 |
+
1. **`ThreadPoolExecutor(max_workers=20)`**
|
| 63 |
+
|
| 64 |
+
- Controls the **number of threads** within a **single worker** process.
|
| 65 |
+
- Allows up to 20 tasks (text classification requests) to be handled simultaneously per worker, improving responsiveness for I/O-bound tasks.
|
| 66 |
+
|
| 67 |
+
2. **`--workers 4` in Uvicorn**
|
| 68 |
+
- Spawns **4 independent worker processes** to handle incoming HTTP requests.
|
| 69 |
+
- Each worker can independently handle multiple tasks, increasing the app's ability to process concurrent requests in parallel.
|
| 70 |
+
|
| 71 |
+
### **How They Relate:**
|
| 72 |
+
|
| 73 |
+
- **Uvicorn’s `--workers`** defines how many worker processes the server will run.
|
| 74 |
+
- **`ThreadPoolExecutor`** limits how many tasks (threads) each worker can process concurrently.
|
| 75 |
+
|
| 76 |
+
For example, with **4 workers** and **20 threads per worker**, the server can handle **80 tasks concurrently**. This provides scalable and efficient processing, balancing the load across multiple workers and threads.
|
| 77 |
+
|
| 78 |
+
### **Endpoints**
|
| 79 |
+
|
| 80 |
+
#### 1. **`/analyze`**
|
| 81 |
+
|
| 82 |
+
- **Method:** `POST`
|
| 83 |
+
- **Description:** Classifies whether the text is AI-generated or human-written.
|
| 84 |
+
- **Request:**
|
| 85 |
+
```json
|
| 86 |
+
{ "text": "sample text" }
|
| 87 |
+
```
|
| 88 |
+
- **Response:**
|
| 89 |
+
```json
|
| 90 |
+
{ "result": "AI-generated", "perplexity": 55.67 }
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
#### 2. **`/health`**
|
| 94 |
+
|
| 95 |
+
- **Method:** `GET`
|
| 96 |
+
- **Description:** Returns the status of the API.
|
| 97 |
+
- **Response:**
|
| 98 |
+
```json
|
| 99 |
+
{ "status": "ok" }
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
---
|
| 103 |
+
|
| 104 |
+
### **Running the API**
|
| 105 |
+
|
| 106 |
+
Start the server with:
|
| 107 |
+
|
| 108 |
+
```bash
|
| 109 |
+
uvicorn app:app --host 0.0.0.0 --port 8000 --workers 4
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
---
|
| 113 |
+
|
| 114 |
+
### **🧪 Testing the API**
|
| 115 |
+
|
| 116 |
+
You can test the FastAPI endpoint using `curl` like this:
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
curl -X POST http://127.0.0.1:8000/analyze \
|
| 120 |
+
-H "Authorization: Bearer HelloThere" \
|
| 121 |
+
-H "Content-Type: application/json" \
|
| 122 |
+
-d '{"text": "This is a sample sentence for analysis."}'
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
- The `-H "Authorization: Bearer HelloThere"` part is used to simulate the **handshake**.
|
| 126 |
+
- FastAPI checks this token against the one loaded from the `.env` file.
|
| 127 |
+
- If the token matches, the request is accepted and processed.
|
| 128 |
+
- Otherwise, it responds with a `403 Unauthorized` error.
|
| 129 |
+
|
| 130 |
+
---
|
| 131 |
+
|
| 132 |
+
### **API Documentation**
|
| 133 |
+
|
| 134 |
+
- **Swagger UI:** `http://127.0.0.1:8000/docs` -> `/docs`
|
| 135 |
+
- **ReDoc:** `http://127.0.0.1:8000/redoc` -> `/redoc`
|
| 136 |
+
|
| 137 |
+
### **🔐 Handshake Mechanism**
|
| 138 |
+
|
| 139 |
+
In this part, we're implementing a simple handshake to verify that the request is coming from a trusted source (e.g., our NestJS server). Here's how it works:
|
| 140 |
+
|
| 141 |
+
- We load a secret token from the `.env` file.
|
| 142 |
+
- When a request is made to the FastAPI server, we extract the `Authorization` header and compare it with our expected secret token.
|
| 143 |
+
- If the token does **not** match, we immediately return a **403 Forbidden** response with the message `"Unauthorized"`.
|
| 144 |
+
- If the token **does** match, we allow the request to proceed to the next step.
|
| 145 |
+
|
| 146 |
+
The verification function looks like this:
|
| 147 |
+
|
| 148 |
+
```python
|
| 149 |
+
def verify_token(auth: str):
|
| 150 |
+
if auth != f"Bearer {EXPECTED_TOKEN}":
|
| 151 |
+
raise HTTPException(status_code=403, detail="Unauthorized")
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
This provides a basic but effective layer of security to prevent unauthorized access to the API.
|
| 155 |
+
|
| 156 |
+
### **Implement it with NEST.js**
|
| 157 |
+
|
| 158 |
+
NOTE: Make an micro service in NEST.JS and implement it there and call it from app.controller.ts
|
| 159 |
+
|
| 160 |
+
in fastapi.service.ts file what we have done is
|
| 161 |
+
|
| 162 |
+
### Project Structure
|
| 163 |
+
|
| 164 |
+
```files
|
| 165 |
+
nestjs-fastapi-bridge/
|
| 166 |
+
├── src/
|
| 167 |
+
│ ├── app.controller.ts
|
| 168 |
+
│ ├── app.module.ts
|
| 169 |
+
│ └── fastapi.service.ts
|
| 170 |
+
├── .env
|
| 171 |
+
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
---
|
| 175 |
+
|
| 176 |
+
### Step-by-Step Setup
|
| 177 |
+
|
| 178 |
+
#### 1. `.env`
|
| 179 |
+
|
| 180 |
+
Create a `.env` file at the root with the following:
|
| 181 |
+
|
| 182 |
+
```environment
|
| 183 |
+
FASTAPI_BASE_URL=http://localhost:8000
|
| 184 |
+
SECRET_TOKEN="HelloThere"
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
#### 2. `fastapi.service.ts`
|
| 188 |
+
|
| 189 |
+
```javascript
|
| 190 |
+
// src/fastapi.service.ts
|
| 191 |
+
import { Injectable } from "@nestjs/common";
|
| 192 |
+
import { HttpService } from "@nestjs/axios";
|
| 193 |
+
import { ConfigService } from "@nestjs/config";
|
| 194 |
+
import { firstValueFrom } from "rxjs";
|
| 195 |
+
|
| 196 |
+
@Injectable()
|
| 197 |
+
export class FastAPIService {
|
| 198 |
+
constructor(
|
| 199 |
+
private http: HttpService,
|
| 200 |
+
private config: ConfigService,
|
| 201 |
+
) {}
|
| 202 |
+
|
| 203 |
+
async analyzeText(text: string) {
|
| 204 |
+
const url = `${this.config.get("FASTAPI_BASE_URL")}/analyze`;
|
| 205 |
+
const token = this.config.get("SECRET_TOKEN");
|
| 206 |
+
|
| 207 |
+
const response = await firstValueFrom(
|
| 208 |
+
this.http.post(
|
| 209 |
+
url,
|
| 210 |
+
{ text },
|
| 211 |
+
{
|
| 212 |
+
headers: {
|
| 213 |
+
Authorization: `Bearer ${token}`,
|
| 214 |
+
},
|
| 215 |
+
},
|
| 216 |
+
),
|
| 217 |
+
);
|
| 218 |
+
|
| 219 |
+
return response.data;
|
| 220 |
+
}
|
| 221 |
+
}
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
#### 3. `app.module.ts`
|
| 225 |
+
|
| 226 |
+
```javascript
|
| 227 |
+
// src/app.module.ts
|
| 228 |
+
import { Module } from "@nestjs/common";
|
| 229 |
+
import { ConfigModule } from "@nestjs/config";
|
| 230 |
+
import { HttpModule } from "@nestjs/axios";
|
| 231 |
+
import { AppController } from "./app.controller";
|
| 232 |
+
import { FastAPIService } from "./fastapi.service";
|
| 233 |
+
|
| 234 |
+
@Module({
|
| 235 |
+
imports: [ConfigModule.forRoot(), HttpModule],
|
| 236 |
+
controllers: [AppController],
|
| 237 |
+
providers: [FastAPIService],
|
| 238 |
+
})
|
| 239 |
+
export class AppModule {}
|
| 240 |
+
```
|
| 241 |
+
|
| 242 |
+
---
|
| 243 |
+
|
| 244 |
+
#### 4. `app.controller.ts`
|
| 245 |
+
|
| 246 |
+
```javascript
|
| 247 |
+
// src/app.controller.ts
|
| 248 |
+
import { Body, Controller, Post, Get, Query } from '@nestjs/common';
|
| 249 |
+
import { FastAPIService } from './fastapi.service';
|
| 250 |
+
|
| 251 |
+
@Controller()
|
| 252 |
+
export class AppController {
|
| 253 |
+
constructor(private readonly fastapiService: FastAPIService) {}
|
| 254 |
+
|
| 255 |
+
@Post('analyze-text')
|
| 256 |
+
async callFastAPI(@Body('text') text: string) {
|
| 257 |
+
return this.fastapiService.analyzeText(text);
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
@Get()
|
| 261 |
+
getHello(): string {
|
| 262 |
+
return 'NestJS is connected to FastAPI ';
|
| 263 |
+
}
|
| 264 |
+
}
|
| 265 |
+
```
|
| 266 |
+
|
| 267 |
+
### 🚀 How to Run
|
| 268 |
+
|
| 269 |
+
Run the server of flask and nest.js:
|
| 270 |
+
|
| 271 |
+
- for nest.js
|
| 272 |
+
```bash
|
| 273 |
+
npm run start
|
| 274 |
+
```
|
| 275 |
+
- for Fastapi
|
| 276 |
+
|
| 277 |
+
```bash
|
| 278 |
+
uvicorn app:app --reload
|
| 279 |
+
```
|
| 280 |
+
|
| 281 |
+
Make sure your FastAPI service is running at `http://localhost:8000`.
|
| 282 |
+
|
| 283 |
+
### Test with CURL
|
| 284 |
+
|
| 285 |
+
```bash
|
| 286 |
+
curl -X POST http://localhost:3000/analyze-text \
|
| 287 |
+
-H 'Content-Type: application/json' \
|
| 288 |
+
-d '{"text": "This is a test input"}'
|
| 289 |
+
```
|
app.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import GPT2LMHeadModel, GPT2TokenizerFast, GPT2Config
|
| 3 |
+
from fastapi import FastAPI, HTTPException
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from contextlib import asynccontextmanager
|
| 6 |
+
import asyncio
|
| 7 |
+
|
| 8 |
+
# FastAPI app instance
|
| 9 |
+
app = FastAPI()
|
| 10 |
+
|
| 11 |
+
# Global model and tokenizer variables
|
| 12 |
+
model, tokenizer = None, None
|
| 13 |
+
|
| 14 |
+
# Function to load model and tokenizer
|
| 15 |
+
def load_model():
|
| 16 |
+
model_path = "./Ai-Text-Detector/model"
|
| 17 |
+
weights_path = "./Ai-Text-Detector/model_weights.pth"
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
tokenizer = GPT2TokenizerFast.from_pretrained(model_path)
|
| 21 |
+
config = GPT2Config.from_pretrained(model_path)
|
| 22 |
+
model = GPT2LMHeadModel(config)
|
| 23 |
+
model.load_state_dict(torch.load(weights_path, map_location=torch.device("cpu")))
|
| 24 |
+
model.eval() # Set model to evaluation mode
|
| 25 |
+
except Exception as e:
|
| 26 |
+
raise RuntimeError(f"Error loading model: {str(e)}")
|
| 27 |
+
|
| 28 |
+
return model, tokenizer
|
| 29 |
+
|
| 30 |
+
# Load model on app startup
|
| 31 |
+
@asynccontextmanager
|
| 32 |
+
async def lifespan(app: FastAPI):
|
| 33 |
+
global model, tokenizer
|
| 34 |
+
model, tokenizer = load_model()
|
| 35 |
+
yield
|
| 36 |
+
|
| 37 |
+
# Attach startup loader
|
| 38 |
+
app = FastAPI(lifespan=lifespan)
|
| 39 |
+
|
| 40 |
+
# Input schema
|
| 41 |
+
class TextInput(BaseModel):
|
| 42 |
+
text: str
|
| 43 |
+
|
| 44 |
+
# Sync text classification
|
| 45 |
+
def classify_text(sentence: str):
|
| 46 |
+
inputs = tokenizer(sentence, return_tensors="pt", truncation=True, padding=True)
|
| 47 |
+
input_ids = inputs["input_ids"]
|
| 48 |
+
attention_mask = inputs["attention_mask"]
|
| 49 |
+
|
| 50 |
+
with torch.no_grad():
|
| 51 |
+
outputs = model(input_ids, attention_mask=attention_mask, labels=input_ids)
|
| 52 |
+
loss = outputs.loss
|
| 53 |
+
perplexity = torch.exp(loss).item()
|
| 54 |
+
|
| 55 |
+
if perplexity < 60:
|
| 56 |
+
result = "AI-generated"
|
| 57 |
+
elif perplexity < 80:
|
| 58 |
+
result = "Probably AI-generated"
|
| 59 |
+
else:
|
| 60 |
+
result = "Human-written"
|
| 61 |
+
|
| 62 |
+
return result, perplexity
|
| 63 |
+
|
| 64 |
+
# POST route to analyze text
|
| 65 |
+
@app.post("/analyze")
|
| 66 |
+
async def analyze_text(data: TextInput):
|
| 67 |
+
user_input = data.text.strip()
|
| 68 |
+
if not user_input:
|
| 69 |
+
raise HTTPException(status_code=400, detail="Text cannot be empty")
|
| 70 |
+
|
| 71 |
+
# Run classification asynchronously to prevent blocking
|
| 72 |
+
result, perplexity = await asyncio.to_thread(classify_text, user_input)
|
| 73 |
+
|
| 74 |
+
return {
|
| 75 |
+
"result": result,
|
| 76 |
+
"perplexity": round(perplexity, 2),
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
# Health check route
|
| 80 |
+
@app.get("/health")
|
| 81 |
+
async def health_check():
|
| 82 |
+
return {"status": "ok"}
|
| 83 |
+
|
| 84 |
+
# Simple index route
|
| 85 |
+
@app.get("/")
|
| 86 |
+
def index():
|
| 87 |
+
return {
|
| 88 |
+
"message": "FastAPI API is up.",
|
| 89 |
+
"try": "/docs to test the API.",
|
| 90 |
+
"status": "OK"
|
| 91 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.6.0
|
| 2 |
+
transformers==4.51.3
|
| 3 |
+
fastapi==0.103.0
|
| 4 |
+
pydantic==1.10.12
|
| 5 |
+
asyncio==3.4.3
|
| 6 |
+
uvicorn[standard]==0.21.1
|