Spaces:
Sleeping
Sleeping
Pujan Neupane commited on
Commit ·
b5008e5
1
Parent(s): b42863e
written the handshake part
Browse filesFiles changed (3)
- README.md+33-7
- app.py+38-6
- requirements.txt+189-28
112 unmodified lines1131141151161161171181191201211181191201211221231241251261271281291301311321332 unmodified lines136137138130139140141142132143144145146147148149150151152153154155156157158112 unmodified lines
---
### **Testing the API**### **🧪 Testing the API**
- Use `curl` for testing: ```bash curl -X 'POST' 'http://127.0.0.1:8000/analyze' -H 'accept: application/json' -H 'Content-Type: application/json' -d '{"text": "sample text"}' ```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`
### **Implement it with NEST.js**### **🔐 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:
will be updated- 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**1233456789101111121314151617181920212223242526272829303114 unmodified lines46474849505152535455565758415960616216 unmodified lines7980818283848586878889909192937094959697987 unmodified lines1061071081091101111121131141151161171181191201219112212312412512612712897129import torchfrom transformers import GPT2LMHeadModel, GPT2TokenizerFastfrom fastapi import FastAPI, HTTPExceptionfrom fastapi import FastAPI, HTTPException, Headerfrom pydantic import BaseModelimport asynciofrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanagerfrom dotenv import dotenv_values
# FastAPI instanceapp = FastAPI()model, tokenizer = None, Noneexecutor = 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 token
def verify_token(auth: str): if auth != f"Bearer {EXPECTED_TOKEN}": raise HTTPException(status_code=403, detail="Unauthorized")
# Function to load model and tokenizer
14 unmodified lines yield
# Attach the lifespan context managerapp = FastAPI(lifespan=lifespan)
# Request body for input data
class TextInput(BaseModel): text: str
# Function to classify the text# Sync function to classify text
def classify_text_sync(sentence: str):16 unmodified lines return result, perplexity
# Async wrapper for text classification
async 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):async def analyze_text(data: TextInput, authorization: str = Header(default="")): verify_token(authorization) # Token verification user_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 {"Its an API"} return {"message": "It's an API"}
# Start the app (run with uvicorn)if __name__ == "__main__": import uvicorn
uvicorn.run("app:app", host="0.0.0.0", port=8000, workers=4) # Specify 4 workers uvicorn.run("main:app", host="0.0.0.0", port=8000, workers=4)12345678910111213141516171819202122423242526272829303132333435363778383940414243444546474849505152535455565758596061626364656667686970717273127475767778798081828384858687888990919293949596979899151617181920212223242526272829303132100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170371711721731741751761771781791801811821831841854218618718818919019119219319446474849195196197198199200201202203204205206207208209210absl-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==3.4.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.12filelock==3.18.0fsspec==2025.3.2fastjsonschema==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.6Jinja2==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.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.1multidict==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==79.0.0setuptools==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.1torch==2.6.0toml==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.0typing-inspection==0.4.0typing_extensions==4.13.2urllib3==2.4.0uvicorn==0.34.2types-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.2README.md+33-7
app.py+38-6
requirements.txt+189-28