File size: 15,643 Bytes
7c956fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
"""

AI Humanizer API - Three-Pass Text Enhancement

Copyright (c) 2026



Three-pass humanization using internal rewriting system.

No external APIs - pure Python implementation.

"""

import os
import logging
import time
import tempfile
from typing import Optional, Dict
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
from fastapi.responses import Response
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from humanizer_three_pass import humanizer, passes_quality_check
from formatting_detector import preserve_formatting, formatting_detector
from markdown_converter import convert_for_copy, convert_for_display, analyze_formatting
try:
    from export_pipeline import export_pipeline
    HAS_EXPORT_PIPELINE = True
except ImportError as e:
    HAS_EXPORT_PIPELINE = False
    EXPORT_PIPELINE_ERROR = str(e)
    logger.warning(f"Export pipeline not available: {e}")

import config

# --- LOGGING CONFIGURATION ---

logging.basicConfig(level=getattr(logging, config.settings.log_level))
logger = logging.getLogger(__name__)

# --- APP INITIALIZATION ---

app = FastAPI(title="Three-Pass Humanizer API", version="3.0")

# ── CORS ──────────────────────────────────────────────────────
# allow_credentials MUST be False when allow_origins=["*"]
# Browser will block the request otherwise (CORS spec violation)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,       # ← IMPORTANT: False, not True
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- API MODELS ---

class HumanizeRequest(BaseModel):
    text: str
    style: Optional[str] = "neutral"  # Accept but ignore for now

class HumanizeResponse(BaseModel):
    output: str  # Formatted text with Markdown (for display)
    plain_text: str  # Plain text without Markdown (for copy/download)
    human_score: int
    ai_score: int
    uniqueness: int
    word_count_original: int
    word_count_output: int
    processing_time_ms: int
    passes: int = 3
    quality_check_passed: bool
    formatting_preserved: Optional[Dict] = None
    formatting_summary: Optional[Dict] = None

# --- QUALITY CHECK WITH RETRY ---

def humanize_with_quality_check(text: str, max_retries: int = config.settings.max_retries) -> str:
    """

    Humanize text with quality check and automatic retry

    Uses smart humanizer with formatting preservation

    """
    retry_count = 0
    
    while retry_count <= max_retries:
        # Perform humanization with formatting preservation
        humanized = preserve_formatting(text, humanizer.humanize)
        
        # Check quality (only on natural language parts)
        if passes_quality_check(humanized):
            logger.info(f"Quality check passed (attempt {retry_count + 1})")
            return humanized
        else:
            retry_count += 1
            if retry_count <= max_retries:
                logger.info(f"Quality check failed, retrying (attempt {retry_count})")
                # Use the humanized output as input for retry
                text = humanized
            else:
                logger.warning(f"Quality check failed after {max_retries} retries")
                return humanized  # Return the best we have
    
    return humanized

# --- SCORE CALCULATION ---

def compute_scores(original: str, humanized: str) -> dict:
    """Compute humanization scores"""
    import re
    import statistics
    
    # Split into sentences
    sentences = re.findall(r'[^.!?]+[.!?]+', humanized) or []
    
    if len(sentences) >= 2:
        try:
            # Calculate sentence length variation
            lens = [len(s.split()) for s in sentences]
            std = statistics.pstdev(lens)
            burst_score = min(int(std * 10), 60)
        except:
            burst_score = 0
    else:
        burst_score = 0
    
    # Contraction score
    contractions = len(re.findall(r"\b\w+'\w+\b", humanized))
    contr_score = min(contractions * 4, 25)
    
    # Vocabulary change score
    orig_words = set(original.lower().split())
    hum_words = set(humanized.lower().split())
    if orig_words:
        changed = len(orig_words - hum_words)
        vocab_score = min(int((changed / len(orig_words)) * 50), 35)
    else:
        vocab_score = 0
    
    # Quality check result
    quality_passed = passes_quality_check(humanized)
    
    # Base human score with quality bonus
    base_score = 75 if quality_passed else 60
    human_score = min(
        base_score + burst_score + contr_score + vocab_score,
        99
    )
    
    return {
        "human_score": human_score,
        "ai_score": 100 - human_score,
        "uniqueness": min(85 + vocab_score + burst_score, 99),
        "quality_check_passed": quality_passed
    }

# --- ENDPOINTS ---

@app.get("/health")
async def health():
    """Health check endpoint"""
    return {
        "status": "ok", 
        "version": "3.0",
        "system": "Three-Pass Humanizer",
        "passes": config.settings.passes
    }

@app.get("/")
async def root():
    return {
        "message": "Three-Pass Humanizer API is running",
        "endpoint": "POST /humanize",
        "description": "Internal three-pass rewriting system"
    }

@app.post("/humanize", response_model=HumanizeResponse)
async def humanize_endpoint(req: HumanizeRequest):
    """

    Main endpoint for three-pass humanization.

    Uses internal rewriting system with quality check and retry.

    """
    try:
        # Validate
        text = req.text.strip() if req.text else ""
        if not text:
            raise HTTPException(status_code=400, detail="Text cannot be empty")
        
        word_count = len(text.split())
        if word_count > 10000:  # Increased limit for three-pass system
            raise HTTPException(status_code=400, detail="Text too long. Max 10,000 words.")
        
        # Process with three-pass humanization
        start = time.time()
        humanized = humanize_with_quality_check(text)
        scores = compute_scores(text, humanized)
        elapsed_ms = int((time.time() - start) * 1000)
        
        logger.info(f"Three-pass humanized {word_count} words β†’ {len(humanized.split())} words in {elapsed_ms}ms")
        logger.info(f"Quality check: {scores['quality_check_passed']}, Human score: {scores['human_score']}")
        
        # Get formatting preservation analysis
        formatting_analysis = analyze_formatting(text)
        
        # Convert to plain text for copy/download (without Markdown syntax)
        plain_text = convert_for_copy(humanized)
        
        return HumanizeResponse(
            output=humanized,  # Formatted text with Markdown (for display)
            plain_text=plain_text,  # Plain text without Markdown (for copy/download)
            word_count_original=word_count,
            word_count_output=len(humanized.split()),
            processing_time_ms=elapsed_ms,
            formatting_preserved=formatting_analysis,
            **scores,
        )
    
    except HTTPException:
        # Re-raise HTTP exceptions (validation errors)
        raise
    except Exception as e:
        # Catch all other exceptions, log with full traceback, and return 500
        logger.error(f"Humanization processing error: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")

@app.post("/humanize-document")
async def humanize_document(

    file: UploadFile = File(..., description="Document file (TXT or DOCX)"),

    style: str = Form("neutral"),

    output_format: str = Form("json", description="Output format: json, txt, docx, or pdf")

):
    """

    Handles file uploads and processes documents with three-pass humanization.

    Supports TXT and DOCX input, returns JSON or file download.

    """
    try:
        # Read file content
        content = await file.read()
        
        # Determine file type and extract text
        filename = file.filename.lower()
        if filename.endswith('.txt'):
            try:
                text = content.decode('utf-8')
            except UnicodeDecodeError as e:
                logger.error(f"Failed to decode TXT file: {str(e)}")
                raise HTTPException(
                    status_code=400,
                    detail="Invalid TXT file encoding. Please ensure the file is UTF-8 encoded."
                )
        elif filename.endswith('.docx'):
            # For DOCX, we need python-docx library
            # For now, return error if not available
            try:
                from docx import Document
                import io
                doc = Document(io.BytesIO(content))
                # Simple text extraction from DOCX
                text = "\n".join([paragraph.text for paragraph in doc.paragraphs if paragraph.text.strip()])
            except ImportError:
                raise HTTPException(
                    status_code=400,
                    detail="DOCX support not available. Please upload TXT files or install python-docx."
                )
            except Exception as e:
                logger.error(f"Failed to parse DOCX file: {str(e)}")
                raise HTTPException(
                    status_code=400,
                    detail="Invalid or corrupted DOCX file. Please ensure the file is a valid DOCX document."
                )
        else:
            raise HTTPException(status_code=400, detail="Unsupported file type. Use .txt or .docx")
        
        # Validate text
        if not text.strip():
            raise HTTPException(status_code=400, detail="Document is empty")
        
        word_count = len(text.split())
        if word_count > 10000:
            raise HTTPException(status_code=400, detail="Document too long. Max 10,000 words.")
        
        # Process with three-pass humanization
        start = time.time()
        humanized = humanize_with_quality_check(text)
        elapsed_ms = int((time.time() - start) * 1000)
        
        logger.info(f"Three-pass humanized document: {word_count} words in {elapsed_ms}ms")
        
        # Return based on requested format
        if output_format == "json":
            scores = compute_scores(text, humanized)
            # Convert to plain text for copy/download (without Markdown syntax)
            plain_text = convert_for_copy(humanized)
            return {
                "output": humanized,  # Formatted text with Markdown (for display)
                "plain_text": plain_text,  # Plain text without Markdown (for copy/download)
                "metrics": {
                    "word_count_original": word_count,
                    "word_count_output": len(humanized.split()),
                    "processing_time_ms": elapsed_ms,
                    "human_score": scores["human_score"],
                    "quality_check_passed": scores["quality_check_passed"],
                    "passes": 3
                }
            }
        
        elif output_format == "txt":
            # Convert to plain text for download (without Markdown syntax)
            plain_text = convert_for_copy(humanized)
            return Response(
                content=plain_text.encode('utf-8'),
                media_type="text/plain",
                headers={"Content-Disposition": "attachment; filename=humanized.txt"}
            )
        
        elif output_format == "docx":
            # For DOCX output, we need python-docx
            try:
                from docx import Document
                import io
                
                # Convert to plain text for DOCX export (without Markdown syntax)
                plain_text = convert_for_copy(humanized)
                doc = Document()
                for paragraph in plain_text.split('\n\n'):
                    if paragraph.strip():
                        doc.add_paragraph(paragraph.strip())
                
                # Save to bytes
                docx_io = io.BytesIO()
                doc.save(docx_io)
                docx_io.seek(0)
                
                return Response(
                    content=docx_io.getvalue(),
                    media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    headers={"Content-Disposition": "attachment; filename=humanized.docx"}
                )
            except ImportError:
                raise HTTPException(
                    status_code=400,
                    detail="DOCX output not available. Please use 'json' or 'txt' format."
                )
            except Exception as e:
                logger.error(f"Failed to create DOCX output: {str(e)}")
                raise HTTPException(
                    status_code=500,
                    detail="Failed to generate DOCX output. Please try 'json' or 'txt' format."
                )
        
        elif output_format == "pdf":
            # For PDF output, use export pipeline
            if not HAS_EXPORT_PIPELINE:
                raise HTTPException(
                    status_code=400,
                    detail="PDF export not available. Export pipeline failed to load."
                )
            
            try:
                # Convert to plain text for PDF export (without Markdown syntax)
                plain_text = convert_for_copy(humanized)
                pdf_bytes = export_pipeline.to_pdf(plain_text)
                
                return Response(
                    content=pdf_bytes,
                    media_type="application/pdf",
                    headers={"Content-Disposition": "attachment; filename=humanized.pdf"}
                )
            except ImportError as e:
                logger.error(f"PDF export dependency error: {str(e)}")
                raise HTTPException(
                    status_code=400,
                    detail=f"PDF output not available: {str(e)}"
                )
            except Exception as e:
                logger.error(f"Failed to create PDF output: {str(e)}")
                raise HTTPException(
                    status_code=500,
                    detail=f"Failed to generate PDF output: {str(e)}"
                )
        else:
            raise HTTPException(status_code=400, detail="Invalid output format. Use: json, txt, docx, or pdf")
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Document processing error: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")

@app.post("/humanize-stream")
async def humanize_stream(req: HumanizeRequest):
    """

    Streaming endpoint (legacy compatibility).

    Returns same as /humanize endpoint.

    """
    return await humanize_endpoint(req)

# ── DO NOT add @app.options("/humanize") ──────────────────────
# CORSMiddleware handles OPTIONS preflight automatically.
# A manual OPTIONS handler conflicts with the middleware.

if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", config.settings.port))
    uvicorn.run(app, host="0.0.0.0", port=port)