Spaces:
Sleeping
Sleeping
Pujan Neupane commited on
Commit ·
7098c2e
1
Parent(s): 869a4ba
Refact: ADDED DOCKER FILE and updated requirement.txt and app.py for hugging face
Browse filesFiles changed (6)
- DockerfileAdded+34
- HuggingFace/main.pyDeleted-18
- HuggingFace/readme.mdDeleted-61
- app.py+35-51
- requirements.txt+6-209
- test.shDeleted-1
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 = "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.**
---12345678910111213141516171819202122232425262728293031323334353637383940414243441 unmodified line46474849505152535455565758596061626364654 unmodified lines70717273747576777879808182838485868788899091929394959697989910010110210310414 unmodified lines119120121122123124125126127128129import 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 tokenizerdef load_model():model_path = "./Ai-Text-Detector/model"weights_path = "./Ai-Text-Detector/model_weights.pth"tokenizer = GPT2TokenizerFast.from_pretrained(model_path)model = GPT2LMHeadModel.from_pretrained("gpt2")model.load_state_dict(torch.load(weights_path, map_location=torch.device("cpu")))model.eval() # Set the model to evaluation modereturn model, tokenizer@asynccontextmanagerasync def lifespan(app: FastAPI):global model, tokenizer1 unmodified lineyield# 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):inputs = tokenizer(sentence, return_tensors="pt", truncation=True, padding=True)input_ids = inputs["input_ids"]attention_mask = inputs["attention_mask"]4 unmodified linesperplexity = torch.exp(loss).item()if perplexity < 60:result = "AI-generated*"elif perplexity < 80:result = "Probably AI-generated*"else:result = "Human-written*"return 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:raise HTTPException(status_code=400, detail="Text cannot be empty")result, perplexity = await classify_text(user_input)return {"result": result,14 unmodified lines@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)123456789101112131415161718192021222324252627282930313233343536373839401 unmodified line42434445464748495051525354555657585960614 unmodified lines666768697071727374757677787980818283848586878889909114 unmodified lines106107108109110111112113import torchfrom transformers import GPT2LMHeadModel, GPT2TokenizerFast, GPT2Configfrom fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom contextlib import asynccontextmanagerimport asyncio# FastAPI app instanceapp = FastAPI()# Global model and tokenizer variablesmodel, tokenizer = None, None# 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() # Set model to evaluation modeexcept 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, tokenizer1 unmodified lineyield# 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"]4 unmodified linesperplexity = 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@app.post("/analyze")async def analyze_text(data: TextInput):user_input = data.text.strip()if not user_input:raise HTTPException(status_code=400, detail="Text cannot be empty")# Run classification asynchronously to prevent blockingresult, perplexity = await asyncio.to_thread(classify_text, user_input)return {"result": result,14 unmodified lines@app.get("/")def index():return {"message": "FastAPI API is up.","try": "/docs to test the API.","status": "OK",}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210absl-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.21234567torch==2.6.0transformers==4.51.3fastapi==0.103.0pydantic==1.10.12asyncio==3.4.3uvicorn[standard]==0.21.1
1echo "ok"DockerfileAdded+34
HuggingFace/main.pyDeleted-18
HuggingFace/readme.mdDeleted-61
app.py+35-51
requirements.txt+6-209
test.shDeleted-1