push
Browse filesFiles changed (8)
- docs/api_endpoints.mdAdded+75
- docs/deployment.mdAdded+105
- docs/functions.mdAdded+53
- docs/nestjs_integration.mdAdded+82
- docs/security.mdAdded+9
- docs/setup.mdAdded+23
- docs/structure.mdAdded+54
- readme.md+11-320
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475# 🧩 API Endpoints
### English (GPT-2) - `/text/`
| Endpoint | Method | Description || --------------------------------- | ------ | ----------------------------------------- || `/text/analyse` | POST | Classify raw English text || `/text/analyse-sentences` | POST | Sentence-by-sentence breakdown || `/text/analyse-sentance-file` | POST | Upload file, per-sentence breakdown || `/text/upload` | POST | Upload file for overall classification || `/text/health` | GET | Health check |
#### Example: Classify English text
```bashcurl -X POST http://localhost:8000/text/analyse \ -H "Authorization: Bearer <SECRET_TOKEN>" \ -H "Content-Type: application/json" \ -d '{"text": "This is a sample text for analysis."}'```
**Response:**```json{ "result": "AI-generated", "perplexity": 55.67, "ai_likelihood": 66.6}```
#### Example: File upload
```bashcurl -X POST http://localhost:8000/text/upload \ -H "Authorization: Bearer <SECRET_TOKEN>" \ -F 'file=@yourfile.txt;type=text/plain'```
---
### Nepali (SentencePiece) - `/NP/`
| Endpoint | Method | Description || --------------------------------- | ------ | ----------------------------------------- || `/NP/analyse` | POST | Classify Nepali text || `/NP/analyse-sentences` | POST | Sentence-by-sentence breakdown || `/NP/upload` | POST | Upload Nepali PDF for classification || `/NP/file-sentences-analyse` | POST | PDF upload, per-sentence breakdown || `/NP/health` | GET | Health check |
#### Example: Nepali text classification
```bashcurl -X POST http://localhost:8000/NP/analyse \ -H "Authorization: Bearer <SECRET_TOKEN>" \ -H "Content-Type: application/json" \ -d '{"text": "यो उदाहरण वाक्य हो।"}'```
**Response:**```json{ "label": "Human", "confidence": 98.6}```
#### Example: Nepali PDF upload
```bashcurl -X POST http://localhost:8000/NP/upload \ -H "Authorization: Bearer <SECRET_TOKEN>" \ -F 'file=@NepaliText.pdf;type=application/pdf'```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
# Deployment
This project is containerized and deployed on **Hugging Face Spaces** using a custom `Dockerfile`. This guide explains the structure of the Dockerfile and key considerations for deploying FastAPI apps on Spaces with Docker SDK.
---
## 📦 Base Image
```dockerfileFROM python:3.9````
We use the official Python 3.9 image for compatibility and stability across most Python libraries and tools.
---
## 👤 Create a Non-Root User
```dockerfileRUN useradd -m -u 1000 userUSER userENV PATH="/home/user/.local/bin:$PATH"```
* Hugging Face Spaces **requires** that containers run as a non-root user with UID `1000`.* We also prepend the user's local binary path to `PATH` for Python package accessibility.
---
## 🗂️ Set Working Directory
```dockerfileWORKDIR /app```
All application files will reside under `/app` for consistency and clarity.
---
## 📋 Install Dependencies
```dockerfileCOPY --chown=user ./requirements.txt requirements.txtRUN pip install --no-cache-dir --upgrade -r requirements.txt```
* Copies the dependency list with correct file ownership.* Uses `--no-cache-dir` to reduce image size.* Ensures the latest compatible versions are installed.
---
## 🔡 Download Language Model (Optional)
```dockerfileRUN python -m spacy download en_core_web_sm || echo "Failed to download model"```
* Downloads the small English NLP model required by SpaCy.* Uses `|| echo ...` to prevent build failure if the download fails (optional safeguard).
---
## 📁 Copy Project Files
```dockerfileCOPY --chown=user . /app```
Copies the entire project source into the container, setting correct ownership for Hugging Face's user-based execution.
---
## 🌐 Start the FastAPI Server
```dockerfileCMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]```
* Launches the FastAPI app using `uvicorn`.* **Port 7860 is mandatory** for Docker-based Hugging Face Spaces deployments.* `app:app` refers to the `FastAPI()` instance in `app.py`.
---
## ✅ Deployment Checklist
* [x] Ensure your main file is named `app.py` or adjust `CMD` accordingly.* [x] All dependencies should be listed in `requirements.txt`.* [x] If using models like SpaCy, verify they are downloaded or bundled.* [x] Test your Dockerfile locally with `docker build` before pushing to Hugging Face.
---
## 📚 References
* Hugging Face Docs: [Spaces Docker SDK](https://huggingface.co/docs/hub/spaces-sdks-docker)* Uvicorn Docs: [https://www.uvicorn.org/](https://www.uvicorn.org/)* SpaCy Models: [https://spacy.io/models](https://spacy.io/models)
---
Happy deploying! **P.S.** Try not to break stuff. 😅1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253# Major Functions used
## in Text Classifier (`features/text_classifier/` and `features/text_classifier/`)
- **`load_model()`** Loads the GPT-2 model and tokenizer from the specified directory paths.
- **`lifespan()`** Manages the application lifecycle. Initializes the model at startup and handles cleanup on shutdown.
- **`classify_text_sync()`** Synchronously tokenizes input text and predicts using the GPT-2 model. Returns classification and perplexity.
- **`classify_text()`** Asynchronously runs `classify_text_sync()` in a thread pool for non-blocking text classification.
- **`analyze_text()`** **POST** endpoint: Accepts text input, classifies it using `classify_text()`, and returns the result with perplexity.
- **`health()`** **GET** endpoint: Simple health check for API liveness.
- **`parse_docx()`, `parse_pdf()`, `parse_txt()`** Utilities to extract and convert `.docx`, `.pdf`, and `.txt` file contents to plain text.
- **`warmup()`** Downloads the model repository and initializes the model/tokenizer using `load_model()`.
- **`download_model_repo()`** Downloads the model files from the designated `MODEL` folder.
- **`get_model_tokenizer()`** Checks if the model already exists; if not, downloads it—otherwise, loads the cached model.
- **`handle_file_upload()`** Handles file uploads from the `/upload` route. Extracts text, classifies, and returns results.
- **`extract_file_contents()`** Extracts and returns plain text from uploaded files (PDF, DOCX, TXT).
- **`handle_file_sentence()`** Processes file uploads by analyzing each sentence (under 10,000 chars) before classification.
- **`handle_sentence_level_analysis()`** Checks/strips each sentence, then computes AI/human likelihood for each.
- **`analyze_sentences()`** Splits paragraphs into sentences, classifies each, and returns all results.
- **`analyze_sentence_file()`** Like `handle_file_sentence()`—analyzes sentences in uploaded files.
## for image_classifier12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Nestjs + fastapi
You can easily call this API from a NestJS microservice.
**.env**```envFASTAPI_BASE_URL=http://localhost:8000SECRET_TOKEN=your_secret_token_here```
**fastapi.service.ts**
```typescriptimport { Injectable } from "@nestjs/common";import { HttpService } from "@nestjs/axios";import { ConfigService } from "@nestjs/config";import { firstValueFrom } from "rxjs";
@Injectable()export class FastAPIService { constructor( private http: HttpService, private config: ConfigService, ) {}
async analyzeText(text: string) { const url = `${this.config.get("FASTAPI_BASE_URL")}/text/analyse`; const token = this.config.get("SECRET_TOKEN");
const response = await firstValueFrom( this.http.post( url, { text }, { headers: { Authorization: `Bearer ${token}`, }, }, ), );
return response.data; }}```
**app.module.ts**```typescriptimport { Module } from "@nestjs/common";import { ConfigModule } from "@nestjs/config";import { HttpModule } from "@nestjs/axios";import { AppController } from "./app.controller";import { FastAPIService } from "./fastapi.service";
@Module({ imports: [ConfigModule.forRoot(), HttpModule], controllers: [AppController], providers: [FastAPIService],})export class AppModule {}```
**app.controller.ts**```typescriptimport { Body, Controller, Post, Get } from '@nestjs/common';import { FastAPIService } from './fastapi.service';
@Controller()export class AppController { constructor(private readonly fastapiService: FastAPIService) {}
@Post('analyze-text') async callFastAPI(@Body('text') text: string) { return this.fastapiService.analyzeText(text); }
@Get() getHello(): string { return 'NestJS is connected to FastAPI'; }}```123456789# Security: Bearer Token Auth
All endpoints require authentication via Bearer token:
- Set `SECRET_TOKEN` in `.env`- Add header: `Authorization: Bearer <SECRET_TOKEN>`
Unauthorized requests receive `403 Forbidden`.
1234567891011121314151617181920212223# Setup & Installation
## 1. Clone the Repository```bashgit clone https://github.com/cyberalertnepal/aiapicd aiapi```
## 2. Install Dependencies```bashpip install -r requirements.txt```
## 3. Configure EnvironmentCreate a `.env` file:```envSECRET_TOKEN=your_secret_token_here```
## 4. Run the API```bashuvicorn app:app --host 0.0.0.0 --port 8000```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354## 🏗️ Project Structure
```├── app.py # Main FastAPI app entrypoint├── config.py # Configuration loader (.env, settings)├── features/│ ├── text_classifier/ # English (GPT-2) classifier│ │ ├── controller.py│ │ ├── inferencer.py│ │ ├── model_loader.py│ │ ├── preprocess.py│ │ └── routes.py│ └── nepali_text_classifier/ # Nepali (sentencepiece) classifier│ ├── controller.py│ ├── inferencer.py│ ├── model_loader.py│ ├── preprocess.py│ └── routes.py├── np_text_model/ # Nepali model artifacts (auto-downloaded)│ ├── classifier/│ │ └── sentencepiece.bpe.model│ └── model_95_acc.pth├── models/ # English GPT-2 model/tokenizer (auto-downloaded)│ ├── merges.txt│ ├── tokenizer.json│ └── model_weights.pth├── Dockerfile # Container build config├── Procfile # Deployment entrypoint (for PaaS)├── requirements.txt # Python dependencies├── README.md ├── Docs # documents└── .env # Secret token(s), environment config```### 🌟 Key Files and Their Roles
- **`app.py`**: Entry point initializing FastAPI app and routes.- **`Procfile`**: Tells Railway (or similar platforms) how to run the program.- **`requirements.txt`**: Tracks all Python dependencies for the project.- **`__init__.py`**: Package initializer for the root module and submodules.- **`features/text_classifier/`** - **`controller.py`**: Handles logic between routes and the model. - **`inferencer.py`**: Runs inference and returns predictions as well as file system utilities.- **`features/NP/`** - **`controller.py`**: Handles logic between routes and the model. - **`inferencer.py`**: Runs inference and returns predictions as well as file system utilities. - **`model_loader.py`**: Loads the ML model and tokenizer. - **`preprocess.py`**: Prepares input text for the model. - **`routes.py`**: Defines API routes for text classification.
-[Main](../README.md)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330# 🚀 FastAPI AI Text DetectorA production-ready FastAPI application for **AI-generated vs. human-written text detection** in both **English** and **Nepali**. Models are auto-managed and endpoints are secured via Bearer token authentication.---## 🏗️ Project Structure```├── app.py # Main FastAPI app entrypoint├── config.py # Configuration loader (.env, settings)├── features/│ ├── text_classifier/ # English (GPT-2) classifier│ │ ├── controller.py│ │ ├── inferencer.py│ │ ├── model_loader.py│ │ ├── preprocess.py│ │ └── routes.py│ └── nepali_text_classifier/ # Nepali (sentencepiece) classifier│ ├── controller.py│ ├── inferencer.py│ ├── model_loader.py│ ├── preprocess.py│ └── routes.py├── np_text_model/ # Nepali model artifacts (auto-downloaded)│ ├── classifier/│ │ └── sentencepiece.bpe.model│ └── model_95_acc.pth├── models/ # English GPT-2 model/tokenizer (auto-downloaded)│ ├── merges.txt│ ├── tokenizer.json│ └── model_weights.pth├── Dockerfile # Container build config├── Procfile # Deployment entrypoint (for PaaS)├── requirements.txt # Python dependencies├── README.md # This file└── .env # Secret token(s), environment config```---### 🌟 Key Files and Their Roles- **`app.py`**: Entry point initializing FastAPI app and routes.- **`Procfile`**: Tells Railway (or similar platforms) how to run the program.- **`requirements.txt`**: Tracks all Python dependencies for the project.- **`__init__.py`**: Package initializer for the root module and submodules.- **`features/text_classifier/`**- **`controller.py`**: Handles logic between routes and the model.- **`inferencer.py`**: Runs inference and returns predictions as well as file systemutilities.- **`features/NP/`**- **`controller.py`**: Handles logic between routes and the model.- **`inferencer.py`**: Runs inference and returns predictions as well as file systemutilities.- **`model_loader.py`**: Loads the ML model and tokenizer.- **`preprocess.py`**: Prepares input text for the model.- **`routes.py`**: Defines API routes for text classification.---## ⚙️ Setup & Installation1. **Clone the repository**```bashgit clone https://github.com/cyberalertnepal/aiapicd aiapi```2. **Install dependencies**```bashpip install -r requirements.txt```3. **Configure secrets**- Create a `.env` file at the project root:```envSECRET_TOKEN=your_secret_token_here```- **All endpoints require `Authorization: Bearer <SECRET_TOKEN>`**---## 🚦 Running the API Server```bashuvicorn app:app --host 0.0.0.0 --port 8000```---## 🔒 Security: Bearer Token AuthAll endpoints require authentication via Bearer token:- Set `SECRET_TOKEN` in `.env`- Add header: `Authorization: Bearer <SECRET_TOKEN>`Unauthorized requests receive `403 Forbidden`.---## 🧩 API Endpoints### English (GPT-2) - `/text/`| Endpoint | Method | Description || --------------------------------- | ------ | ----------------------------------------- || `/text/analyse` | POST | Classify raw English text || `/text/analyse-sentences` | POST | Sentence-by-sentence breakdown || `/text/analyse-sentance-file` | POST | Upload file, per-sentence breakdown || `/text/upload` | POST | Upload file for overall classification || `/text/health` | GET | Health check |#### Example: Classify English text```bashcurl -X POST http://localhost:8000/text/analyse \-H "Authorization: Bearer <SECRET_TOKEN>" \-H "Content-Type: application/json" \-d '{"text": "This is a sample text for analysis."}'```**Response:**```json{"result": "AI-generated","perplexity": 55.67,"ai_likelihood": 66.6}```#### Example: File upload```bashcurl -X POST http://localhost:8000/text/upload \-H "Authorization: Bearer <SECRET_TOKEN>" \-F 'file=@yourfile.txt;type=text/plain'```---### Nepali (SentencePiece) - `/NP/`| Endpoint | Method | Description || --------------------------------- | ------ | ----------------------------------------- || `/NP/analyse` | POST | Classify Nepali text || `/NP/analyse-sentences` | POST | Sentence-by-sentence breakdown || `/NP/upload` | POST | Upload Nepali PDF for classification || `/NP/file-sentences-analyse` | POST | PDF upload, per-sentence breakdown || `/NP/health` | GET | Health check |#### Example: Nepali text classification```bashcurl -X POST http://localhost:8000/NP/analyse \-H "Authorization: Bearer <SECRET_TOKEN>" \-H "Content-Type: application/json" \-d '{"text": "यो उदाहरण वाक्य हो।"}'```**Response:**```json{"label": "Human","confidence": 98.6}```#### Example: Nepali PDF upload```bashcurl -X POST http://localhost:8000/NP/upload \-H "Authorization: Bearer <SECRET_TOKEN>" \-F 'file=@NepaliText.pdf;type=application/pdf'```---## 📝 API Docs- **Swagger UI:** [http://localhost:8000/docs](http://localhost:8000/docs)- **ReDoc:** [http://localhost:8000/redoc](http://localhost:8000/redoc)---## 🧪 Example: Integration with NestJSYou can easily call this API from a NestJS microservice.**.env**```envFASTAPI_BASE_URL=http://localhost:8000SECRET_TOKEN=your_secret_token_here```**fastapi.service.ts**```typescriptimport { Injectable } from "@nestjs/common";import { HttpService } from "@nestjs/axios";import { ConfigService } from "@nestjs/config";import { firstValueFrom } from "rxjs";@Injectable()export class FastAPIService {constructor(private http: HttpService,private config: ConfigService,) {}async analyzeText(text: string) {const url = `${this.config.get("FASTAPI_BASE_URL")}/text/analyse`;const token = this.config.get("SECRET_TOKEN");const response = await firstValueFrom(this.http.post(url,{ text },{headers: {Authorization: `Bearer ${token}`,},},),);return response.data;}}```**app.module.ts**```typescriptimport { Module } from "@nestjs/common";import { ConfigModule } from "@nestjs/config";import { HttpModule } from "@nestjs/axios";import { AppController } from "./app.controller";import { FastAPIService } from "./fastapi.service";@Module({imports: [ConfigModule.forRoot(), HttpModule],controllers: [AppController],providers: [FastAPIService],})export class AppModule {}```**app.controller.ts**```typescriptimport { Body, Controller, Post, Get } from '@nestjs/common';import { FastAPIService } from './fastapi.service';@Controller()export class AppController {constructor(private readonly fastapiService: FastAPIService) {}@Post('analyze-text')async callFastAPI(@Body('text') text: string) {return this.fastapiService.analyzeText(text);}@Get()getHello(): string {return 'NestJS is connected to FastAPI';}}```---## 🧠 Main Functions in Text Classifier (`features/text_classifier/` and `features/text_classifier/`)- **`load_model()`**Loads the GPT-2 model and tokenizer from the specified directory paths.- **`lifespan()`**Manages the application lifecycle. Initializes the model at startup and handles cleanup on shutdown.- **`classify_text_sync()`**Synchronously tokenizes input text and predicts using the GPT-2 model. Returns classification and perplexity.- **`classify_text()`**Asynchronously runs `classify_text_sync()` in a thread pool for non-blocking text classification.- **`analyze_text()`****POST** endpoint: Accepts text input, classifies it using `classify_text()`, and returns the result with perplexity.- **`health()`****GET** endpoint: Simple health check for API liveness.- **`parse_docx()`, `parse_pdf()`, `parse_txt()`**Utilities to extract and convert `.docx`, `.pdf`, and `.txt` file contents to plain text.- **`warmup()`**Downloads the model repository and initializes the model/tokenizer using `load_model()`.- **`download_model_repo()`**Downloads the model files from the designated `MODEL` folder.- **`get_model_tokenizer()`**Checks if the model already exists; if not, downloads it—otherwise, loads the cached model.- **`handle_file_upload()`**Handles file uploads from the `/upload` route. Extracts text, classifies, and returns results.- **`extract_file_contents()`**Extracts and returns plain text from uploaded files (PDF, DOCX, TXT).- **`handle_file_sentence()`**Processes file uploads by analyzing each sentence (under 10,000 chars) before classification.- **`handle_sentence_level_analysis()`**Checks/strips each sentence, then computes AI/human likelihood for each.- **`analyze_sentences()`**Splits paragraphs into sentences, classifies each, and returns all results.- **`analyze_sentence_file()`**Like `handle_file_sentence()`—analyzes sentences in uploaded files.---## 🚀 Deployment- **Local**: Use `uvicorn` as above.123456789101112131415161718192021# 🚀 FastAPI AI DetectorA production-ready FastAPI app for detecting AI vs. human-written text in English and Nepali. It uses GPT-2 and SentencePiece-based models, with Bearer token security.## 📂 Documentation- [Project Structure](docs/structure.md)- [API Endpoints](docs/api_endpoints.md)- [Setup & Installation](docs/setup.md)- [Deployment](docs/deployment.md)- [Security](docs/security.md)- [NestJS Integration](docs/nestjs_integration.md)- [Core Functions](docs/functions.md)## ⚡ Quick Start```bashuvicorn app:app --host 0.0.0.0 --port 8000```## 🚀 Deployment- **Local**: Use `uvicorn` as above.
docs/api_endpoints.mdAdded+75
docs/deployment.mdAdded+105
docs/functions.mdAdded+53
docs/nestjs_integration.mdAdded+82
docs/security.mdAdded+9
docs/setup.mdAdded+23
docs/structure.mdAdded+54
readme.md+11-320