Merge pull request #1 from cyberalertnepal/Pujan
Browse filesfeat: Handshake is added in fastapi and Nest.js implementation snippet
Files changed (7)
- .gitignore+57-2
- HuggingFace/main.pyAdded+18
- HuggingFace/readme.mdAdded+61
- README.md+165-8
- app.py+38-6
- requirements.txt+189-28
- test.shAdded+1
12./venv/./__pycache__/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657# ---- Python Environment ----venv/.venv/env/ENV/*.pyc*.pyo*.pyd__pycache__/**/__pycache__/# ---- VS Code / IDEs ----.vscode/.idea/*.swp# ---- Jupyter / IPython ----.ipynb_checkpoints/*.ipynb# ---- Model & Data Artifacts ----*.pth*.pt*.h5*.ckpt*.onnx*.joblib*.pkl# ---- Hugging Face Cache ----~/.cache/huggingface/huggingface_cache/# ---- Logs and Dumps ----*.log*.out*.err# ---- Build Artifacts ----build/dist/*.egg-info/# ---- System Files ----.DS_StoreThumbs.db# ---- Environment Configs ----.env.env.*# ---- Project-specific ----Ai-Text-Detector/HuggingFace/model/# ---- Node Projects (if applicable) ----node_modules/
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 = "Pujan-Dev/test" 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.**
---1 unmodified line23456789103 unmodified lines1131141151161171181191201211221231242 unmodified lines1271281291301311321 unmodified lineThis 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**```bash103 unmodified lines---### **Testing the API**- Use `curl` for testing:```bashcurl -X 'POST' 'http://127.0.0.1:8000/analyze' -H 'accept: application/json' -H 'Content-Type: application/json' -d '{"text": "sample text"}'```---2 unmodified lines- **Swagger UI:** `http://127.0.0.1:8000/docs` -> `/docs`- **ReDoc:** `http://127.0.0.1:8000/redoc` -> `/redoc`### **Implement it with NEST.js**will be updated1 unmodified line234567103 unmodified lines1111121131141151161171181191201211221231241251261271281291301312 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882891 unmodified lineThis 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**```bash103 unmodified lines---### **🧪 Testing the API**You can test the FastAPI endpoint using `curl` like this:```bashcurl -X POST http://127.0.0.1:8000/analyze \-H "Authorization: Bearer HelloThere" \-H "Content-Type: application/json" \-d '{"text": "This is a sample sentence for analysis."}'```- The `-H "Authorization: Bearer HelloThere"` 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.---2 unmodified lines- **Swagger UI:** `http://127.0.0.1:8000/docs` -> `/docs`- **ReDoc:** `http://127.0.0.1:8000/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=http://localhost:8000SECRET_TOKEN="HelloThere"```#### 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 CURL```bashcurl -X POST http://localhost:3000/analyze-text \-H 'Content-Type: application/json' \-d '{"text": "This is a test input"}'```
1234567891011121314151614 unmodified lines313233343536373839404142434416 unmodified lines616263646566676869707172737 unmodified lines8182838485868788899091929394959697import torchfrom transformers import GPT2LMHeadModel, GPT2TokenizerFastfrom fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelimport asynciofrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanager# FastAPI instanceapp = FastAPI()model, tokenizer = None, Noneexecutor = ThreadPoolExecutor(max_workers=20)# Function to load model and tokenizer14 unmodified linesyieldapp = FastAPI(lifespan=lifespan)class TextInput(BaseModel):text: str# Function to classify the textdef classify_text_sync(sentence: str):16 unmodified linesreturn result, perplexityasync def classify_text(sentence: str):loop = asyncio.get_event_loop()return await loop.run_in_executor(executor, classify_text_sync, sentence)@app.post("/analyze")async def analyze_text(data: TextInput):user_input = data.text.strip()if not user_input:7 unmodified lines}@app.get("/health")async def health_check():return {"status": "ok"}@app.get("/")def index():return {"Its an API"}if __name__ == "__main__":import uvicornuvicorn.run("app:app", host="0.0.0.0", port=8000, workers=4) # Specify 4 workers1234567891011121314151617181920212223242526272829303114 unmodified lines464748495051525354555657585960616216 unmodified lines79808182838485868788899091929394959697987 unmodified lines106107108109110111112113114115116117118119120121122123124125126127128129import torchfrom transformers import GPT2LMHeadModel, GPT2TokenizerFastfrom fastapi import FastAPI, HTTPException, Headerfrom pydantic import BaseModelimport asynciofrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanagerfrom dotenv import dotenv_values# FastAPI instanceapp = FastAPI()executor = ThreadPoolExecutor(max_workers=20)# Load .env fileenv = dotenv_values(".env")EXPECTED_TOKEN = env.get("SECRET_TOKEN")# Global variables for model and tokenizermodel, tokenizer = None, None# Function to verify tokendef verify_token(auth: str):if auth != f"Bearer {EXPECTED_TOKEN}":raise HTTPException(status_code=403, detail="Unauthorized")# Function to load model and tokenizer14 unmodified linesyield# Attach the lifespan context managerapp = FastAPI(lifespan=lifespan)# Request body for input dataclass TextInput(BaseModel):text: str# Sync function to classify textdef classify_text_sync(sentence: str):16 unmodified linesreturn result, perplexity# Async wrapper for text classificationasync def classify_text(sentence: str):loop = asyncio.get_event_loop()return await loop.run_in_executor(executor, classify_text_sync, sentence)# POST route to analyze text@app.post("/analyze")async def analyze_text(data: TextInput, authorization: str = Header(default="")):verify_token(authorization) # Token verificationuser_input = data.text.strip()if not user_input:7 unmodified lines}# Health check route@app.get("/health")async def health_check():return {"status": "ok"}# Simple index route@app.get("/")def index():return {"message": "It's an API"}# Start the app (run with uvicorn)if __name__ == "__main__":import uvicornuvicorn.run("main:app", host="0.0.0.0", port=8000, workers=4)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849annotated-types==0.7.0anyio==4.9.0certifi==2025.1.31charset-normalizer==3.4.1click==8.1.8fastapi==0.115.12filelock==3.18.0fsspec==2025.3.2h11==0.14.0huggingface-hub==0.30.2idna==3.10Jinja2==3.1.6MarkupSafe==3.0.2mpmath==1.3.0networkx==3.4.2numpy==2.2.5nvidia-cublas-cu12==12.4.5.8nvidia-cuda-cupti-cu12==12.4.127nvidia-cuda-nvrtc-cu12==12.4.127nvidia-cuda-runtime-cu12==12.4.127nvidia-cudnn-cu12==9.1.0.70nvidia-cufft-cu12==11.2.1.3nvidia-curand-cu12==10.3.5.147nvidia-cusolver-cu12==11.6.1.9nvidia-cusparse-cu12==12.3.1.170nvidia-cusparselt-cu12==0.6.2nvidia-nccl-cu12==2.21.5nvidia-nvjitlink-cu12==12.4.127nvidia-nvtx-cu12==12.4.127packaging==25.0pydantic==2.11.3pydantic_core==2.33.1PyYAML==6.0.2regex==2024.11.6requests==2.32.3safetensors==0.5.3setuptools==79.0.0sniffio==1.3.1starlette==0.46.2sympy==1.13.1tokenizers==0.21.1torch==2.6.0tqdm==4.67.1transformers==4.51.3triton==3.2.0typing-inspection==0.4.0typing_extensions==4.13.2urllib3==2.4.0uvicorn==0.34.2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210absl-py==2.2.2accelerate==1.6.0aiohappyeyeballs==2.6.1aiohttp==3.11.16aiosignal==1.3.2altair==5.5.0annotated-types==0.7.0anyio==4.9.0argon2-cffi==23.1.0argon2-cffi-bindings==21.2.0arrow==1.3.0asgiref==3.8.1asttokens==3.0.0async-lru==2.0.5attrs==25.3.0babel==2.17.0beautifulsoup4==4.13.4bleach==6.2.0blinker==1.9.0cachetools==5.5.2certifi==2025.1.31cffi==1.17.1charset-normalizer==2.1.1click==8.1.8comm==0.2.2contourpy==1.3.1cycler==0.12.1datasets==3.5.0DateTime==4.7debugpy==1.8.13decorator==5.2.1defusedxml==0.7.1dill==0.3.8Django==5.2dotenv==0.9.9executing==2.2.0fastapi==0.115.12fastjsonschema==2.21.1filelock==3.13.1Flask==3.1.0flask-cors==5.0.1fonttools==4.56.0fqdn==1.5.1frozenlist==1.6.0fsspec==2024.6.1generativeai==0.0.1gitdb==4.0.12GitPython==3.1.44google-ai-generativelanguage==0.6.15google-api-core==2.24.2google-api-python-client==2.165.0google-auth==2.38.0google-auth-httplib2==0.2.0google-genai==1.7.0google-generativeai==0.8.4googleapis-common-protos==1.69.2grpcio==1.71.0grpcio-status==1.71.0h11==0.14.0h5py==3.13.0html5lib==1.1httpcore==1.0.7httplib2==0.22.0httpx==0.28.1huggingface-hub==0.30.2idna==3.10inquirerpy==0.3.4ipykernel==6.29.5ipython==9.0.2ipython_pygments_lexers==1.1.1isoduration==20.11.0itsdangerous==2.2.0jedi==0.19.2Jinja2==3.1.4joblib==1.4.2json5==0.12.0jsonpointer==3.0.0jsonschema==4.23.0jsonschema-specifications==2024.10.1jupyter-events==0.12.0jupyter-lsp==2.2.5jupyter_client==8.6.3jupyter_core==5.7.2jupyter_server==2.15.0jupyter_server_terminals==0.5.3jupyterlab==4.4.0jupyterlab_pygments==0.3.0jupyterlab_server==2.27.3keras==3.9.2kiwisolver==1.4.8markdown-it-py==3.0.0MarkupSafe==3.0.2matplotlib==3.10.1matplotlib-inline==0.1.7mdurl==0.1.2mechanize==0.4.10mistune==3.1.3ml_dtypes==0.5.1mpmath==1.3.0multidict==6.4.3multiprocess==0.70.16namex==0.0.8narwhals==1.35.0nbclient==0.10.2nbconvert==7.16.6nbformat==5.10.4nest-asyncio==1.6.0networkx==3.3notebook==7.4.0notebook_shim==0.2.4numpy==2.2.4nvidia-cublas-cu11==11.11.3.6nvidia-cuda-cupti-cu11==11.8.87nvidia-cuda-nvrtc-cu11==11.8.89nvidia-cuda-runtime-cu11==11.8.89nvidia-cudnn-cu11==9.1.0.70nvidia-cufft-cu11==10.9.0.58nvidia-curand-cu11==10.3.0.86nvidia-cusolver-cu11==11.4.1.48nvidia-cusparse-cu11==11.7.5.86nvidia-nccl-cu11==2.21.5nvidia-nvtx-cu11==11.8.86optree==0.15.0overrides==7.7.0packaging==24.2pandas==2.2.3pandocfilters==1.5.1parso==0.8.4pexpect==4.9.0pfzy==0.3.4pillow==11.1.0platformdirs==4.3.7prometheus_client==0.21.1prompt_toolkit==3.0.50propcache==0.3.1proto-plus==1.26.1protobuf==5.29.4psutil==7.0.0ptyprocess==0.7.0pure_eval==0.2.3pyarrow==19.0.1pyasn1==0.6.1pyasn1_modules==0.4.1pycparser==2.22pydantic==2.10.6pydantic_core==2.27.2pydeck==0.9.1pygame==2.6.1Pygments==2.19.1pyparsing==3.2.2pystyle==2.0python-dateutil==2.9.0.post0python-dotenv==1.1.0python-json-logger==3.3.0pytz==2025.1PyYAML==6.0.2pyzmq==26.3.0referencing==0.36.2regex==2024.11.6requests==2.32.3rfc3339-validator==0.1.4rfc3986-validator==0.1.1rich==14.0.0rpds-py==0.24.0rsa==4.9safetensors==0.5.3scikit-learn==1.6.1scipy==1.15.2seaborn==0.13.2Send2Trash==1.8.3setuptools==70.2.0six==1.17.0smmap==5.0.2sniffio==1.3.1soupsieve==2.6sqlparse==0.5.3stack-data==0.6.3starlette==0.46.2streamlit==1.44.1sympy==1.13.1tenacity==9.1.2terminado==0.18.1threadpoolctl==3.6.0tinycss2==1.4.0tokenizers==0.21.1toml==0.10.2torch==2.6.0+cu118torchaudio==2.6.0+cu118torchvision==0.21.0+cu118tornado==6.4.2tqdm==4.67.1traitlets==5.14.3transformers==4.51.3triton==3.2.0types-python-dateutil==2.9.0.20241206typing_extensions==4.12.2tzdata==2025.2uri-template==1.3.0uritemplate==4.1.1urllib3==1.26.20watchdog==6.0.0wcwidth==0.2.13webcolors==24.11.1webencodings==0.5.1websocket-client==1.8.0websockets==15.0.1Werkzeug==3.1.3xxhash==3.5.0yarl==1.20.0zope.interface==7.2
1echo "ok".gitignore+57-2
HuggingFace/main.pyAdded+18
HuggingFace/readme.mdAdded+61
README.md+165-8
app.py+38-6
requirements.txt+189-28
test.shAdded+1