Spaces:
Running
Running
File size: 12,482 Bytes
d720fd0 1a070c8 d720fd0 37c0011 d720fd0 37c0011 d720fd0 37c0011 d720fd0 37c0011 d720fd0 37c0011 d720fd0 37c0011 d720fd0 37c0011 1a070c8 37c0011 1a070c8 37c0011 d720fd0 37c0011 d720fd0 37c0011 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | ---
title: Humanizer API
emoji: "๐"
colorFrom: indigo
colorTo: purple
sdk: docker
pinned: false
---
<div align="center">
<img src="logo.png" alt="SIDDWRITES" width="400"/>
**Production-grade AI Humanizer that transforms AI-generated text into bypass-ready human writing โ in seconds.**
[](https://github.com/EHEGUY/humanizer-frontend)
[](https://huggingface.co/spaces/eheguy/humanizer-api/tree/main)
[](https://fastapi.tiangolo.com)
[](https://supabase.com)
</div>
---
## What is SIDDWRITES AI Humanizer?
SIDDWRITES AI Humanizer is a full-stack SaaS platform designed to restructure AI-generated prose so that it bypasses modern AI detection engines. By analyzing syntactic structures and vocabulary choices, it dynamically adjusts perplexity and burstiness metrics to emulate organic human pacing.
---
## Features
| Feature | Details |
| :--- | :--- |
| **Two-Pass Engine** | Semantic and Syntactic restructuring pass + Burstiness and Flow control smoothing pass |
| **Readability Presets** | Casual, Neutral, Formal, and Academic prompt modifiers |
| **Purpose Profiles** | Specialized styling targets for Essays, Blogs, Professional Emails, Reports, and Social Media |
| **JWT Authorization** | Access validation verifying Supabase access tokens server-side |
| **Atomic Usage Count** | PostgreSQL RPC function (`increment_humanization_count`) prevents race-condition usage bypasses |
| **Payment Gateway** | Razorpay SDK order creation and cryptographic signature verification |
| **Rate Limiting** | slowapi-enforced IP-based rate limiting (10/min for humanizing, 5/min for order actions) |
| **Injection Sanitizer** | Dual-layered regex and Base64-decoded input checks against malicious prompts |
| **Database Security** | Profiles table row-level security (RLS) restricts client-side updates |
---
## System Architecture & Decoupled Data Flow
### 1. System Architecture (Component Layout)
The application architecture is divided into three distinct spaces: a static client-side layer, a containerized FastAPI compute engine, and managed serverless database/auth backends.
```mermaid
graph TD
subgraph Client ["Client Layer (Browser)"]
UI[Vanilla HTML/JS UI]
SB_Auth[Supabase Auth SDK]
end
subgraph CDN ["Edge / Routing Layer"]
Vercel[Vercel CDN - Frontend Host]
end
subgraph API ["Compute Layer (FastAPI on HuggingFace Spaces)"]
FAST[FastAPI ASGI Application]
Limiter[slowapi Rate Limiter]
JWT_Dep[verify_token JWT Dependency]
Sanitizer[sanitize_input prompt-injection filter]
GroqClient[Groq Client API]
SupaClient[Supabase Admin Client]
end
subgraph External ["Data & Inference Providers"]
Groq[Groq Llama 3.3 Inference Engine]
SupaAuth[Supabase Auth Service]
SupaDB[Supabase Postgres Database]
end
UI --> Vercel
UI --> SB_Auth
SB_Auth <--> SupaAuth
UI -- "POST /humanize (Bearer JWT)" --> FAST
FAST --> Limiter
Limiter --> JWT_Dep
JWT_Dep -- "Get JWKS keys" --> SupaAuth
JWT_Dep --> Sanitizer
Sanitizer --> GroqClient
GroqClient -- "Two-Pass Rewrite" --> Groq
FAST --> SupaClient
SupaClient -- "Database RPC Call" --> SupaDB
```
### 2. Decoupled Data Flow (Sequence Execution)
The sequence of events when processing text:
```mermaid
sequenceDiagram
autonumber
actor User as Client Browser
participant FE as Frontend (Vercel)
participant Auth as Supabase Auth
participant BE as FastAPI API (HuggingFace)
participant DB as Supabase DB (Profiles)
participant LLM as Groq (Llama 3.3 70B)
User->>FE: Input text & click "Humanize"
FE->>Auth: sb.auth.getSession()
Auth-->>FE: Return Access Token (JWT)
FE->>BE: POST /humanize [Auth: Bearer JWT]
rect rgb(245, 245, 245)
Note over BE,DB: Security & Authorization Validation
BE->>BE: Decode JWT & verify sub claim (user_id)
BE->>BE: Check IP rate limits (slowapi)
BE->>DB: Query profile (using Service Role Key)
DB-->>BE: Return plan & usage count
BE->>BE: Verify usage count < plan limit
end
rect rgb(238, 238, 238)
Note over BE,LLM: Input Sanitization & Pipeline
BE->>BE: Sanitize text (base64 & regex checks)
BE->>LLM: Two-Pass humanization prompt
LLM-->>BE: Return humanized text
end
BE->>DB: RPC: increment_humanization_count(user_id)
BE-->>FE: Return humanized text & updated usage
FE-->>User: Display output text
```
### 3. Low-Level Execution Lifecycle (Flowchart)
The logical execution flow of a single humanization request inside the FastAPI compute engine:
```mermaid
graph TD
classDef client fill:#ffffff,stroke:#000000,stroke-width:2px;
classDef api fill:#f5f5f5,stroke:#000000,stroke-width:2px;
classDef guard fill:#eeeeee,stroke:#000000,stroke-width:2px;
classDef pipeline fill:#e0e0e0,stroke:#000000,stroke-width:2px;
classDef database fill:#cccccc,stroke:#000000,stroke-width:2px;
subgraph UserAction ["1. Trigger Cycle (Client)"]
Click[User Clicks Humanize]:::client
JWT[Retrieve Supabase JWT]:::client
Payload[Build Payload: Text/Mode/Readability/Purpose]:::client
Click --> JWT --> Payload
end
subgraph APIRequest ["2. Gateway & Security (FastAPI)"]
Req[POST /humanize]:::api
CORS[CORS Domain Check]:::guard
Rate[slowapi Rate Limiter]:::guard
JWKS[Verify JWT Signature via JWKS]:::guard
Payload --> Req
Req --> CORS --> Rate --> JWKS
end
subgraph AuthChecking ["3. Authorization & Limits (Supabase)"]
SubClaim[Extract user_id from sub claim]:::guard
LimitQuery[Query Profile via Service Role Key]:::database
CheckLimit{Is usage < limit?}:::guard
UpgradeModal[Trigger Frontend Upgrade Modal]:::client
JWKS --> SubClaim --> LimitQuery --> CheckLimit
CheckLimit -- No --> UpgradeModal
end
subgraph SanitizeLayer ["4. Input Sanitization Filter"]
Regex[Run Regex Blacklist Checks]:::guard
B64[Run base64 Decode & Regex Checks]:::guard
FailBlock[Return 400 Bad Request]:::api
CheckLimit -- Yes --> Regex --> B64
Regex -- Matches --> FailBlock
B64 -- Matches --> FailBlock
end
subgraph LLMProcessing ["5. Two-Pass Heuristics Engine (Groq Llama 3.3)"]
Pass1[Pass 1: Semantic & Syntactic Restructuring]:::pipeline
Pass2[Pass 2: Burstiness Correction & Transition Smoothing]:::pipeline
VocabFilter[Post-process: Punctuation & Banned Words Filter]:::pipeline
B64 -- Clean --> Pass1 --> Pass2 --> VocabFilter
end
subgraph CompleteCycle ["6. Transaction & Output"]
AtomicRPC[Supabase RPC: increment_humanization_count]:::database
Res[Return JSON Output & Counter]:::api
UI[Update UI and Local Counter]:::client
VocabFilter --> AtomicRPC --> Res --> UI
end
```
---
## Detailed System Specifications
### 1. Two-Pass Heuristics Engine
To neutralize automatic classifiers, the text generation pipeline executes a sequence of transformations:
* **Pass 1: Syntactic Restructuring**: Passive clauses are converted to active format, complex sentences are split or merged, and natural sentence-length variation is introduced to boost the burstiness metric.
* **Pass 2: Smoothing & Flow Control**: The output of Pass 1 is processed to smooth out transitions. It strips repetitive AI-generated markers and phrases that trigger classification vectors.
* **Punctuation & Vocabulary Ban**: Em-dashes (`โ`), hyphens (`-`) for modifiers, and a custom list of AI-preferred filler words (e.g., *tapestry, delve, landscape, beacon, paramount, seamlessly, fostering*) are systematically filtered out.
### 2. Post-Audit Security Hardening
Following a security audit, the backend and database layers were hardened:
* **JWT Authorization & Signature Verification (JWKS)**: The server does not trust client-reported user IDs. It retrieves the current public signing key set from Supabase's JWKS endpoint dynamically and cryptographically verifies the token's signature, audience (`authenticated`), and expiration, before extracting the user ID from the `sub` claim. This guarantees zero-downtime key rotation support.
* **Atomic Usage Operations**: Reads and writes to user profiles are executed atomically on the database using a PostgreSQL database function. This prevents race conditions where a user executes multiple requests concurrently to bypass usage limits.
* **CORS Lockdowns**: Allowed origins are restricted to the production frontend domain and local development hosts.
* **Rate Limiting**: Integrated `slowapi` to enforce IP-based rate limiting:
* `/humanize`: 10 requests per minute.
* `/api/create-order`: 5 requests per minute.
* **Prompt Injection Sanitizer**: Checks user input against known jailbreak, developer-mode, and instruction-ignore patterns, running the validation on both raw and Base64-decoded inputs.
---
## Supabase Database Schema & Policies
The database is built on Supabase (PostgreSQL). The tables and policies are structured to prevent users from bypassing local checks.
### Profiles Table Schema
| Column Name | Data Type | Default Value | Description |
| :--- | :--- | :--- | :--- |
| `id` | `uuid` | `uuid_generate_v4()` | Primary key linked to auth.users |
| `plan` | `text` | `'free'` | Subscription tier (free, starter, pro) |
| `humanization_count` | `int4` | `0` | Total humanizations used during the billing cycle |
| `razorpay_subscription_id`| `text` | `NULL` | ID linked to active subscription |
---
## API Documentation
### `POST /humanize`
Rewrites input text to match human writing metrics. Requires JWT authentication.
* **Headers:**
* `Authorization: Bearer <supabase_jwt>`
* **Request Payload:**
```json
{
"text": "The implementation of AI systems in modern business processes has created significant efficiency...",
"mode": "enhanced",
"readability": "neutral",
"purpose": "professional"
}
```
* **Success Response (200 OK):**
```json
{
"humanized": "Integrating AI into business workflows speeds up tasks, but it shifts how teams collaborate...",
"mode": "enhanced",
"readability": "neutral",
"purpose": "professional",
"usage": {
"count": 3,
"limit": 8,
"plan": "free"
}
}
```
### `GET /user-plan`
Returns the active subscription plan tier for the verified user. Requires JWT authentication.
* **Headers:**
* `Authorization: Bearer <supabase_jwt>`
* **Success Response (200 OK):**
```json
{
"plan": "starter"
}
```
### `POST /api/create-order`
Initiates a Razorpay order for purchasing subscription access. Requires JWT authentication.
* **Headers:**
* `Authorization: Bearer <supabase_jwt>`
* **Request Payload:**
```json
{
"plan": "starter"
}
```
* **Success Response (200 OK):**
```json
{
"order_id": "order_OkJ18dhAsjS91",
"amount": 75000,
"currency": "INR",
"key_id": "rzp_test_..."
}
```
---
## Local Installation & Setup
1. **Clone and Install Dependencies**:
```bash
git clone <repository-url>
cd humanizer
pip install -r requirements.txt
```
2. **Configure Environment Variables**:
Create a `.env` file in the root folder:
```env
SUPABASE_URL=https://your-supabase-url.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-supabase-service-role-key
GROQ_API_KEY=your-groq-api-key
RAZORPAY_KEY_ID=your-razorpay-key-id
RAZORPAY_KEY_SECRET=your-razorpay-key-secret
```
3. **Start the API Server**:
```bash
uvicorn main:app --reload
```
The backend will start running on `http://127.0.0.1:8000`.
4. **Run the Static UI**:
Open `/frontend/index.html` using a local web server (e.g., Live Server or python http module). Make sure the `CONFIG` variables inside `index.html` point to your Supabase instance.
---
*Made with the help of Antigravity.*
|