Added the files adding system and formated the files system
Browse filesFiles changed (16)
- DockerfileDeleted-34
- MODEL/app.pyDeleted-18
- MODEL/readme.mdDeleted-61
- MODEL/requirements.txtDeleted-1
- ProcfileAdded+1
- README.mdDeleted-268
- __init__.pyAdded
- app.py+8-90
- features/text_classifier/__init__.pyAdded
- features/text_classifier/controller.pyAdded+54
- features/text_classifier/inferencer.pyAdded+27
- features/text_classifier/model_loader.pyAdded+50
- features/text_classifier/preprocess.pyAdded+30
- features/text_classifier/routes.pyAdded+28
- readme.md+316-1
- requirements.txt+11-7
12345678910111213141516171819202122232425262728293031323334# Use the latest slim Python 3.11 imageFROM python:3.11-slim
# Set environment variablesENV HOME=/home/user \ PATH=/home/user/.local/bin:$PATH \ PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1
# Install system dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ git \ curl \ && rm -rf /var/lib/apt/lists/*
# Create a non-root user for safetyRUN useradd -ms /bin/bash userUSER userWORKDIR $HOME/app
# Copy app source codeCOPY --chown=user . .
# Install Python dependenciesRUN pip install --no-cache-dir --upgrade pip \ && pip install --no-cache-dir -r requirements.txt
# Expose portEXPOSE 7860
# Start the FastAPI app using uvicornCMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
123456789101112131415161718import osfrom huggingface_hub import Repository
def download_repo(): hf_token = os.getenv("HF_TOKEN") if not hf_token: raise ValueError("HF_TOKEN not found in environment variables.")
repo_id = "can-org/AIModel" local_dir = "../Ai-Text-Detector/"
repo = Repository(local_dir, clone_from=repo_id, token=hf_token) print(f"Repository downloaded to: {local_dir}")
if __name__ == "__main__": download_repo()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061### Hugging Face CLI Tool
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.
### Prerequisites
1. **Install Hugging Face Hub**:
```bash pip install huggingface_hub ```
2. **Get HF_TOKEN**: - Log in to [Hugging Face](https://huggingface.co/). - Go to **Settings** β **Access Tokens** β **Create a new token** with `read` and `write` permissions. - Save the token.
### Usage
1. **Set the Token**:
- **Linux/macOS**: ```bash export HF_TOKEN=your_token_here ``` - **Windows (CMD)**: ```bash set HF_TOKEN=your_token_here ```
2. **Download Model**:
```bash python main.py --download --repo-id <repo_name> --save-dir <local_save_path> ```
3. **Upload Model**: ```bash python main.py --upload --repo-id <repo_name> --model-path <local_model_path> ```
### Example
To download a model:
```bashpython main.py```
### Authentication
Ensure you set `HF_TOKEN` to access private repositories. If not set, the script will raise an error.Hereβs a clearer and more polished version of that note:
---
### β οΈ Note
**Make sure to run this script from the `HuggingFace` directory to ensure correct path resolution and functionality.**
---1huggingface_hub1web: uvicorn app:app --host 0.0.0.0 --port ${PORT:-8000}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268### **FastAPI AI**
This FastAPI app loads a GPT-2 model, tokenizes input text, classifies it, and returns whether the text is AI-generated or human-written.
### **install Dependencies**
```bashpip install -r requirements.txt
```
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.
**NOTE: IF YOU HAVE DONE ANY CHANGES DON'NT FORGOT TO PUT IT IN THE REQUIREMENTS.TXT USING `bash pip freeze > requirements.txt `**
---
### **Functions**
1. **`load_model()`** Loads the GPT-2 model and tokenizer from specified paths.
2. **`lifespan()`** Manages the app's lifecycle: loads the model at startup and handles cleanup on shutdown.
3. **`classify_text_sync()`** Synchronously tokenizes input text and classifies it using the GPT-2 model. Returns the classification and perplexity.
4. **`classify_text()`** Asynchronously executes `classify_text_sync()` in a thread pool to ensure non-blocking processing.
5. **`analyze_text()`** **POST** endpoint: accepts text input, classifies it using `classify_text()`, and returns the result with perplexity.
6. **`health_check()`** **GET** endpoint: simple health check to confirm the API is running.
---
### **Code Overview**
### **Running and Load Balancing:**
To run the app in production with load balancing:
```bashuvicorn app:app --host 0.0.0.0 --port 8000 --workers 4```
This command launches the FastAPI app.
### **Endpoints**
#### 1. **`/analyze`**
- **Method:** `POST`- **Description:** Classifies whether the text is AI-generated or human-written.- **Request:** ```json { "text": "sample text" } ```- **Response:** ```json { "result": "AI-generated", "perplexity": 55.67 } ```
#### 2. **`/health`**
- **Method:** `GET`- **Description:** Returns the status of the API.- **Response:** ```json { "status": "ok" } ```
---
### **Running the API**
Start the server with:
```bashuvicorn app:app --host 0.0.0.0 --port 8000 --workers 4```
---
### **π§ͺ Testing the API**
You can test the FastAPI endpoint using `curl` like this:
```bashcurl -X POST https://can-org-canspace.hf.space/analyze \ -H "Authorization: Bearer SECRET_CODE" \ -H "Content-Type: application/json" \ -d '{"text": "This is a sample sentence for analysis."}'```
- The `-H "Authorization: Bearer SECRET_CODE"` part is used to simulate the **handshake**.- FastAPI checks this token against the one loaded from the `.env` file.- If the token matches, the request is accepted and processed.- Otherwise, it responds with a `403 Unauthorized` error.
---
### **API Documentation**
- **Swagger UI:** `https://can-org-canspace.hf.space/docs` -> `/docs`- **ReDoc:** `https://can-org-canspace.hf.space/redoc` -> `/redoc`
### **π Handshake Mechanism**
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:
- We load a secret token from the `.env` file.- When a request is made to the FastAPI server, we extract the `Authorization` header and compare it with our expected secret token.- If the token does **not** match, we immediately return a **403 Forbidden** response with the message `"Unauthorized"`.- If the token **does** match, we allow the request to proceed to the next step.
The verification function looks like this:
```pythondef verify_token(auth: str): if auth != f"Bearer {EXPECTED_TOKEN}": raise HTTPException(status_code=403, detail="Unauthorized")```
This provides a basic but effective layer of security to prevent unauthorized access to the API.
### **Implement it with NEST.js**
NOTE: Make an micro service in NEST.JS and implement it there and call it from app.controller.ts
in fastapi.service.ts file what we have done is
### Project Structure
```filesnestjs-fastapi-bridge/βββ src/β βββ app.controller.tsβ βββ app.module.tsβ βββ fastapi.service.tsβββ .env
```
---
### Step-by-Step Setup
#### 1. `.env`
Create a `.env` file at the root with the following:
```environment FASTAPI_BASE_URL=https://can-org-canspace.hf.space/ SECRET_TOKEN="SECRET_CODE_TOKEN"```
#### 2. `fastapi.service.ts`
```javascript // src/fastapi.service.ts import { 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")}/analyze`; const token = this.config.get("SECRET_TOKEN");
const response = await firstValueFrom( this.http.post( url, { text }, { headers: { Authorization: `Bearer ${token}`, }, }, ), );
return response.data; } }```
#### 3. `app.module.ts`
```javascript// src/app.module.tsimport { 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 {}```
---
#### 4. `app.controller.ts`
```javascript // src/app.controller.ts import { Body, Controller, Post, Get, Query } 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 '; } }```
### π How to Run
Run the server of flask and nest.js:
- for nest.js ```bash npm run start ```- for Fastapi
```bash uvicorn app:app --reload ```
Make sure your FastAPI service is running at `http://localhost:8000`.
### Test with CURLhttp://localhost:3000/-> Server of nest.js```bashcurl -X POST http://localhost:3000/analyze-text \ -H 'Content-Type: application/json' \ -d '{"text": "This is a test input"}'```
### MODEL - You can download the model from the `/MODEL/app.py` file.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102from fastapi import FastAPI, HTTPException, Dependsfrom fastapi.security import HTTPBearerfrom pydantic import BaseModelfrom transformers import GPT2LMHeadModel, GPT2TokenizerFast, GPT2Configimport torchimport asynciofrom contextlib import asynccontextmanager# FastAPI app instanceapp = FastAPI()# Global model and tokenizer variablesmodel, tokenizer = None, None# HTTPBearer instance for securitybearer_scheme = HTTPBearer()# Function to load model and tokenizerdef load_model():model_path = "./Ai-Text-Detector/model"weights_path = "./Ai-Text-Detector/model_weights.pth"try:tokenizer = GPT2TokenizerFast.from_pretrained(model_path)config = GPT2Config.from_pretrained(model_path)model = GPT2LMHeadModel(config)model.load_state_dict(torch.load(weights_path, map_location=torch.device("cpu")))model.eval()except Exception as e:raise RuntimeError(f"Error loading model: {str(e)}")return model, tokenizer# Load model on app startup@asynccontextmanagerasync def lifespan(app: FastAPI):global model, tokenizermodel, tokenizer = load_model()yield# Attach startup loaderapp = FastAPI(lifespan=lifespan)# Input schemaclass TextInput(BaseModel):text: str# Sync text classificationdef classify_text(sentence: str):inputs = tokenizer(sentence, return_tensors="pt", truncation=True, padding=True)input_ids = inputs["input_ids"]attention_mask = inputs["attention_mask"]with torch.no_grad():outputs = model(input_ids, attention_mask=attention_mask, labels=input_ids)loss = outputs.lossperplexity = torch.exp(loss).item()if perplexity < 60:result = "AI-generated"elif perplexity < 80:result = "Probably AI-generated"else:result = "Human-written"return result, perplexity# POST route to analyze text with Bearer token@app.post("/analyze")async def analyze_text(data: TextInput, token: str = Depends(bearer_scheme)):user_input = data.text.strip()if not user_input:raise HTTPException(status_code=400, detail="Text cannot be empty")# Check if there are at least two wordsword_count = len(user_input.split())if word_count < 2:raise HTTPException(status_code=400, detail="Text must contain at least two words")result, perplexity = await asyncio.to_thread(classify_text, user_input)return {"result": result,"perplexity": round(perplexity, 2),}# Health check route@app.get("/health")async def health_check():return {"status": "ok"}# Simple index route@app.get("/")def index():return {"message": "FastAPI API is up.","try": "/docs to test the API.","status": "OK"}1234567891011121314151617181920from fastapi import FastAPIfrom contextlib import asynccontextmanagerfrom features.text_classifier.routes import router as text_classifier_routerfrom features.text_classifier.model_loader import warmup@asynccontextmanagerasync def lifespan(app: FastAPI):warmup() # Download and load model at startupyield# Cleanup loapp = FastAPI()app.include_router(text_classifier_router, prefix="/text", tags=["Text Classification"])@app.get("/")def index():return {"Message": "Fast api is running... ", "Try": "/docs"}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354from .inferencer import classify_textimport asynciofrom fastapi import HTTPException, UploadFilefrom .preprocess import parse_docx, parse_pdf, parse_txt
from io import BytesIOimport logging
async def handle_text_analysis(text: str): text = text.strip() if not text or len(text.split()) < 2: raise HTTPException( status_code=400, detail="Text must contain at least two words" ) label, perplexity = await asyncio.to_thread(classify_text, text) return {"result": label, "perplexity": round(perplexity, 2)}
async def handle_file_upload(file: UploadFile): try: file_contents = await extract_file_contents(file) if len(file_contents) > 10000: return {"message": "File contains more than 10,000 characters."} cleaned_text = file_contents.replace("\n", "").replace("\t", "") label, perplexity = await asyncio.to_thread(classify_text, cleaned_text) return {"result": label, "perplexity": round(perplexity, 2)} except Exception as e: logging.error(f"Error processing file: {str(e)}") raise HTTPException(status_code=500, detail="Error processing the file")
async def extract_file_contents(file: UploadFile): content = await file.read() file_stream = BytesIO(content)
if ( file.content_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ): return parse_docx(file_stream) elif file.content_type == "application/pdf": return parse_pdf(file_stream) elif file.content_type == "text/plain": return parse_txt(file_stream) else: raise HTTPException( status_code=400, detail="Invalid file type. Only .docx, .pdf, and .txt are allowed.", )
def classify(text: str): return classify_text(text)123456789101112131415161718192021222324252627import torchfrom .model_loader import get_model_tokenizer
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def classify_text(text: str): model, tokenizer = get_model_tokenizer() inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True) input_ids = inputs["input_ids"].to(device) attention_mask = inputs["attention_mask"].to(device)
with torch.no_grad(): outputs = model( input_ids, attention_mask=attention_mask, labels=input_ids) loss = outputs.loss perplexity = torch.exp(loss).item()
if perplexity < 60: result = "AI-generated" elif perplexity < 80: result = "Probably AI-generated" else: result = "Human-written"
return result, perplexity1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import osimport shutilimport loggingfrom transformers import GPT2LMHeadModel, GPT2TokenizerFast, GPT2Configfrom huggingface_hub import snapshot_downloadimport torchfrom dotenv import load_dotenv
load_dotenv()REPO_ID = "Pujan-Dev/AI-Text-Detector"MODEL_DIR = "./models"TOKENIZER_DIR = os.path.join(MODEL_DIR, "model")WEIGHTS_PATH = os.path.join(MODEL_DIR, "model_weights.pth")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")_model, _tokenizer = None, None
def warmup(): global _model, _tokenizer download_model_repo() _model, _tokenizer = load_model() logging.info("Its ready")
def download_model_repo(): if os.path.exists(MODEL_DIR) and os.path.isdir(MODEL_DIR): logging.info("Model already exists, skipping download.") return snapshot_path = snapshot_download(repo_id=REPO_ID) os.makedirs(MODEL_DIR, exist_ok=True) shutil.copytree(snapshot_path, MODEL_DIR, dirs_exist_ok=True)
def load_model(): tokenizer = GPT2TokenizerFast.from_pretrained(TOKENIZER_DIR) config = GPT2Config.from_pretrained(TOKENIZER_DIR) model = GPT2LMHeadModel(config) model.load_state_dict(torch.load(WEIGHTS_PATH, map_location=device)) model.to(device) model.eval() return model, tokenizer
def get_model_tokenizer(): global _model, _tokenizer if _model is None or _tokenizer is None: download_model_repo() _model, _tokenizer = load_model() return _model, _tokenizer123456789101112131415161718192021222324252627282930import fitz # PyMuPDFimport docxfrom io import BytesIOimport loggingfrom fastapi import HTTPException
def parse_docx(file: BytesIO): doc = docx.Document(file) text = "" for para in doc.paragraphs: text += para.text + "\n" return text
def parse_pdf(file: BytesIO): try: doc = fitz.open(stream=file, filetype="pdf") text = "" for page_num in range(doc.page_count): page = doc.load_page(page_num) text += page.get_text() return text except Exception as e: logging.error(f"Error while processing PDF: {str(e)}") raise HTTPException(status_code=500, detail="Error processing PDF file")
def parse_txt(file: BytesIO): return file.read().decode("utf-8")12345678910111213141516171819202122232425262728from fastapi import APIRouter, Depends, HTTPException, UploadFile, Filefrom fastapi.security import HTTPBearerfrom pydantic import BaseModelfrom .controller import handle_text_analysis, handle_file_upload
router = APIRouter()bearer_scheme = HTTPBearer()
class TextInput(BaseModel): text: str
@router.post("/analyze")async def analyze(data: TextInput, token: str = Depends(bearer_scheme)): return await handle_text_analysis(data.text)
@router.post("/upload")async def upload_file( file: UploadFile = File(...), token: str = Depends(bearer_scheme)): return await handle_file_upload(file)
@router.get("/health")def health(): return {"status": "ok"}1# TESTING123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316### **FastAPI AI**This FastAPI app loads a GPT-2 model, tokenizes input text, classifies it, and returns whether the text is AI-generated or human-written.### **install Dependencies**```bashpip install -r requirements.txt```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.**NOTE: IF YOU HAVE DONE ANY CHANGES DON'NT FORGOT TO PUT IT IN THE REQUIREMENTS.TXT USING `bash pip freeze > requirements.txt `**---### Files STructure```βββ app.pyβββ featuresβΒ Β βββ text_classifierβΒ Β βββ controller.pyβΒ Β βββ inferencer.pyβΒ Β βββ __init__.pyβΒ Β βββ model_loader.pyβΒ Β βββ preprocess.pyβΒ Β βββ routes.pyβββ __init__.pyβββ Procfileβββ readme.mdβββ requirements.txt```**`app.py`**: Entry point initializing FastAPI app and routes**`Procfile`**: Tells Railway how to run the program**`requirements.txt`**:Have all the packages that we use in our project**`__init__.py`** : Package initializer for the root module**FOLDER :features/text_classifier****`controller.py`** :Handles logic between routes and model**`inferencer.py`** : Runs inference and returns predictions as well as files system**`__init__.py`** :Initializes the module as a package**`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### **Functions**1. **`load_model()`**Loads the GPT-2 model and tokenizer from specified paths.2. **`lifespan()`**Manages the app's lifecycle: loads the model at startup and handles cleanup on shutdown.3. **`classify_text_sync()`**Synchronously tokenizes input text and classifies it using the GPT-2 model. Returns the classification and perplexity.4. **`classify_text()`**Asynchronously executes `classify_text_sync()` in a thread pool to ensure non-blocking processing.5. **`analyze_text()`****POST** endpoint: accepts text input, classifies it using `classify_text()`, and returns the result with perplexity.6. **`health()`****GET** endpoint: simple health check to confirm the API is running.7. **`parse_docx() ,parse_pdf(),parse_txt()`**THis are the function that are used to convert the given docs, pdf or text files into the strings format so that we can classify them.8. **`warmup()`**This function is used to downlaod the repo and init the _model and _tokenizer from load_model() function9. **`download_model_repo()`**This function is use to download the model from the MODEL folder10. **`get_model_tokenizer()`**This function is similler to the warmup but it also check if the model is already exist or not if not exist then download it else let it be or use previous downloaded model11. **`handle_file_upload()`**This function is use to handle the file upload in the upload route and classify and returns the results.12. **`Extract_file_contents()`**This function is use to extract the contains from the files and return the text from the files.---### **Code Overview**### **Running and Load Balancing:**To run the app in production with load balancing:```bashuvicorn app:app --host 0.0.0.0 --port 8000```This command launches the FastAPI app.### **Endpoints**#### 1. **`/text/analyze`**- **Method:** `POST`- **Description:** Classifies whether the text is AI-generated or human-written.- **Request:**```json{ "text": "sample text" }```- **Response:**```json{ "result": "AI-generated", "perplexity": 55.67 }```#### 2. **`/health`**- **Method:** `GET`- **Description:** Returns the status of the API.- **Response:**```json{ "status": "ok" }```#### 3. **`/text/upload`**- **Method:** `POST`- **Description:** Takes the files and check the contains inside and returns the results- **Request:** Files- **Response:**```json{ "result": "AI-generated", "perplexity": 55.67 }```---### **Running the API**Start the server with:```bashuvicorn app:app --host 0.0.0.0 --port 8000 --workers 4```---### **π§ͺ Testing the API**You can test the FastAPI endpoint using `curl` like this:```bashcurl -X POST https://can-org-canspace.hf.space/analyze \-H "Authorization: Bearer SECRET_CODE" \-H "Content-Type: application/json" \-d '{"text": "This is a sample sentence for analysis."}'```- The `-H "Authorization: Bearer SECRET_CODE"` part is used to simulate the **handshake**.- FastAPI checks this token against the one loaded from the `.env` file.- If the token matches, the request is accepted and processed.- Otherwise, it responds with a `403 Unauthorized` error.---### **API Documentation**- **Swagger UI:** `https://can-org-canspace.hf.space/docs` -> `/docs`- **ReDoc:** `https://can-org-canspace.hf.space/redoc` -> `/redoc`### **π Handshake Mechanism**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:- We load a secret token from the `.env` file.- When a request is made to the FastAPI server, we extract the `Authorization` header and compare it with our expected secret token.- If the token does **not** match, we immediately return a **403 Forbidden** response with the message `"Unauthorized"`.- If the token **does** match, we allow the request to proceed to the next step.The verification function looks like this:```pythondef verify_token(auth: str):if auth != f"Bearer {EXPECTED_TOKEN}":raise HTTPException(status_code=403, detail="Unauthorized")```This provides a basic but effective layer of security to prevent unauthorized access to the API.### **Implement it with NEST.js**NOTE: Make an micro service in NEST.JS and implement it there and call it from app.controller.tsin fastapi.service.ts file what we have done is### Project Structure```filesnestjs-fastapi-bridge/βββ src/β βββ app.controller.tsβ βββ app.module.tsβ βββ fastapi.service.tsβββ .env```---### Step-by-Step Setup#### 1. `.env`Create a `.env` file at the root with the following:```environmentFASTAPI_BASE_URL=https://can-org-canspace.hf.space/SECRET_TOKEN="SECRET_CODE_TOKEN"```#### 2. `fastapi.service.ts````javascript// src/fastapi.service.tsimport { 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")}/analyze`;const token = this.config.get("SECRET_TOKEN");const response = await firstValueFrom(this.http.post(url,{ text },{headers: {Authorization: `Bearer ${token}`,},},),);return response.data;}}```#### 3. `app.module.ts````javascript// src/app.module.tsimport { 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 {}```---#### 4. `app.controller.ts````javascript// src/app.controller.tsimport { Body, Controller, Post, Get, Query } 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 ';}}```### π How to RunRun the server of flask and nest.js:- for nest.js```bashnpm run start```- for Fastapi```bashuvicorn app:app --reload```Make sure your FastAPI service is running at `http://localhost:8000`.### Test with CURLhttp://localhost:3000/-> Server of nest.js```bashcurl -X POST http://localhost:3000/analyze-text \-H 'Content-Type: application/json' \-d '{"text": "This is a test input"}'```
1234567torch==2.6.0transformers==4.51.3fastapi==0.103.0pydantic==1.10.12asyncio==3.4.3uvicorn[standard]==0.21.11234567891011fastapiuvicorntorchtransformershuggingface_hubpython-dotenvpython-docxPyMuPDFpydanticfitzpython-multipart
DockerfileDeleted-34
MODEL/app.pyDeleted-18
MODEL/readme.mdDeleted-61
MODEL/requirements.txtDeleted-1
ProcfileAdded+1
README.mdDeleted-268
__init__.pyAdded
app.py+8-90
features/text_classifier/__init__.pyAdded
features/text_classifier/controller.pyAdded+54
features/text_classifier/inferencer.pyAdded+27
features/text_classifier/model_loader.pyAdded+50
features/text_classifier/preprocess.pyAdded+30
features/text_classifier/routes.pyAdded+28
readme.md+316-1
requirements.txt+11-7