devilseye2004 commited on
Commit
7c956fc
·
verified ·
1 Parent(s): b843fab

Upload 10 files

Browse files
Files changed (10) hide show
  1. DEPLOYMENT_GUIDE.md +108 -0
  2. Dockerfile +25 -0
  3. app.py +399 -0
  4. config.py +70 -0
  5. export_pipeline.py +222 -0
  6. formatting_detector.py +288 -0
  7. humanizer_three_pass.py +335 -0
  8. main.py +54 -0
  9. markdown_converter.py +304 -0
  10. requirements.txt +13 -0
DEPLOYMENT_GUIDE.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Humanizer System Deployment Guide
2
+
3
+ ## System Architecture
4
+ - **Frontend**: Next.js on Vercel (`aquahumanizer.vercel.app`)
5
+ - **Backend**: FastAPI on Hugging Face Spaces (Docker)
6
+ - **Connection**: Frontend calls backend API
7
+
8
+ ## Files Cleaned Up
9
+ ✅ Removed old/unused files:
10
+ - `humanizer.py` (old version)
11
+ - `format_preserver.py` (old version)
12
+ - Test files (user removed manually)
13
+
14
+ ## Current Files Structure
15
+ ```
16
+ ├── app.py # Main FastAPI application
17
+ ├── config.py # Configuration (no .env needed)
18
+ ├── main.py # Entry point for HF Spaces
19
+ ├── Dockerfile # Docker configuration for HF Spaces
20
+ ├── requirements.txt # Python dependencies
21
+ ├── humanizer_three_pass.py # Three-pass humanizer engine
22
+ ├── formatting_detector.py # Formatting preservation
23
+ ├── markdown_converter.py # Markdown to plain text conversion
24
+ ├── export_pipeline.py # DOCX/PDF export (optional)
25
+ └── frontend/ # Next.js frontend (deployed separately)
26
+ ```
27
+
28
+ ## Key Features Implemented
29
+ 1. ✅ **No external AI APIs** - Uses internal three-pass humanizer
30
+ 2. ✅ **Formatting preservation** - Preserves code blocks, lists, tables, URLs, etc.
31
+ 3. ✅ **Markdown to plain text conversion** - Users get clean text for copy/download
32
+ 4. ✅ **Config without .env file** - Works on Hugging Face Spaces
33
+ 5. ✅ **Dockerfile fixed** - No syntax errors, proper main.py
34
+
35
+ ## Deployment Steps
36
+
37
+ ### 1. Backend (Hugging Face Spaces)
38
+ 1. Push this code to GitHub
39
+ 2. Go to [Hugging Face Spaces](https://huggingface.co/spaces)
40
+ 3. Click "Create new Space"
41
+ 4. Select:
42
+ - **Space name**: `humanizer-backend` (or your choice)
43
+ - **Space SDK**: `Docker`
44
+ - **Visibility**: Public or Private
45
+ 5. Connect your GitHub repository
46
+ 6. Deploy
47
+
48
+ ### 2. Frontend (Vercel)
49
+ 1. The frontend is already at `aquahumanizer.vercel.app`
50
+ 2. In Vercel dashboard, add environment variable:
51
+ - `BACKEND_URL` = `https://[your-username]-humanizer-backend.hf.space`
52
+ (Replace with your actual HF Spaces URL)
53
+
54
+ ### 3. Environment Variables
55
+ **Backend (HF Spaces)** - Uses defaults, no .env needed:
56
+ - `PORT` = 7860 (default)
57
+ - `PASSES` = 3 (default)
58
+ - `LOG_LEVEL` = INFO (default)
59
+
60
+ **Frontend (Vercel)**:
61
+ - `BACKEND_URL` = Your HF Spaces backend URL
62
+
63
+ ## Testing Locally
64
+ ```bash
65
+ # Install dependencies
66
+ pip install -r requirements.txt
67
+
68
+ # Run backend
69
+ uvicorn main:app --host 0.0.0.0 --port 7860
70
+
71
+ # Frontend (separate terminal)
72
+ cd frontend
73
+ npm install
74
+ npm run dev
75
+ ```
76
+
77
+ ## API Endpoints
78
+ - `POST /humanize` - Humanize text
79
+ - `POST /humanize-document` - Process document files
80
+ - `GET /health` - Health check
81
+ - `GET /` - Redirects to frontend
82
+ - `GET /info` - System information
83
+
84
+ ## Notes
85
+ - PDF export (`export_pipeline.py`) has weasyprint dependency issues on Windows but might work on HF Spaces (Linux)
86
+ - If PDF export fails, DOCX and TXT export still work
87
+ - The system handles 10,000+ word documents with formatting preservation
88
+ - No external API calls - all processing is internal
89
+
90
+ ## Troubleshooting
91
+ 1. **Docker build fails on HF Spaces**:
92
+ - Check Dockerfile syntax
93
+ - Ensure all required files are in repository
94
+
95
+ 2. **Frontend can't connect to backend**:
96
+ - Verify `BACKEND_URL` environment variable in Vercel
97
+ - Check CORS settings in `main.py`
98
+
99
+ 3. **PDF export not working**:
100
+ - WeasyPrint requires GTK3 on Linux
101
+ - Consider removing weasyprint from `export_pipeline.py` if not needed
102
+
103
+ ## Success Indicators
104
+ ✅ Backend runs on HF Spaces (Docker container starts)
105
+ ✅ Frontend connects to backend (API calls work)
106
+ ✅ Text humanization works (three-pass system)
107
+ ✅ Formatting preserved (code blocks, lists, etc.)
108
+ ✅ Copy/download gives plain text (no Markdown syntax)
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dockerfile for Hugging Face Spaces - Backend Only
2
+ # Frontend is deployed separately on Vercel
3
+ FROM python:3.11-slim
4
+
5
+ WORKDIR /app
6
+
7
+ # Install system dependencies
8
+ RUN apt-get update && apt-get install -y \
9
+ build-essential \
10
+ python3-dev \
11
+ && rm -rf /var/lib/apt/lists/*
12
+
13
+ # Copy Python requirements
14
+ COPY requirements.txt .
15
+
16
+ # Install Python dependencies
17
+ RUN pip install --no-cache-dir -r requirements.txt
18
+
19
+ # Copy all Python source files
20
+ COPY app.py config.py main.py ./
21
+ COPY *.py ./
22
+
23
+ EXPOSE 7860
24
+
25
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI Humanizer API - Three-Pass Text Enhancement
3
+ Copyright (c) 2026
4
+
5
+ Three-pass humanization using internal rewriting system.
6
+ No external APIs - pure Python implementation.
7
+ """
8
+
9
+ import os
10
+ import logging
11
+ import time
12
+ import tempfile
13
+ from typing import Optional, Dict
14
+ from fastapi import FastAPI, HTTPException, UploadFile, File, Form
15
+ from fastapi.responses import Response
16
+ from fastapi.middleware.cors import CORSMiddleware
17
+ from pydantic import BaseModel
18
+ from humanizer_three_pass import humanizer, passes_quality_check
19
+ from formatting_detector import preserve_formatting, formatting_detector
20
+ from markdown_converter import convert_for_copy, convert_for_display, analyze_formatting
21
+ try:
22
+ from export_pipeline import export_pipeline
23
+ HAS_EXPORT_PIPELINE = True
24
+ except ImportError as e:
25
+ HAS_EXPORT_PIPELINE = False
26
+ EXPORT_PIPELINE_ERROR = str(e)
27
+ logger.warning(f"Export pipeline not available: {e}")
28
+
29
+ import config
30
+
31
+ # --- LOGGING CONFIGURATION ---
32
+
33
+ logging.basicConfig(level=getattr(logging, config.settings.log_level))
34
+ logger = logging.getLogger(__name__)
35
+
36
+ # --- APP INITIALIZATION ---
37
+
38
+ app = FastAPI(title="Three-Pass Humanizer API", version="3.0")
39
+
40
+ # ── CORS ──────────────────────────────────────────────────────
41
+ # allow_credentials MUST be False when allow_origins=["*"]
42
+ # Browser will block the request otherwise (CORS spec violation)
43
+ app.add_middleware(
44
+ CORSMiddleware,
45
+ allow_origins=["*"],
46
+ allow_credentials=False, # ← IMPORTANT: False, not True
47
+ allow_methods=["*"],
48
+ allow_headers=["*"],
49
+ )
50
+
51
+ # --- API MODELS ---
52
+
53
+ class HumanizeRequest(BaseModel):
54
+ text: str
55
+ style: Optional[str] = "neutral" # Accept but ignore for now
56
+
57
+ class HumanizeResponse(BaseModel):
58
+ output: str # Formatted text with Markdown (for display)
59
+ plain_text: str # Plain text without Markdown (for copy/download)
60
+ human_score: int
61
+ ai_score: int
62
+ uniqueness: int
63
+ word_count_original: int
64
+ word_count_output: int
65
+ processing_time_ms: int
66
+ passes: int = 3
67
+ quality_check_passed: bool
68
+ formatting_preserved: Optional[Dict] = None
69
+ formatting_summary: Optional[Dict] = None
70
+
71
+ # --- QUALITY CHECK WITH RETRY ---
72
+
73
+ def humanize_with_quality_check(text: str, max_retries: int = config.settings.max_retries) -> str:
74
+ """
75
+ Humanize text with quality check and automatic retry
76
+ Uses smart humanizer with formatting preservation
77
+ """
78
+ retry_count = 0
79
+
80
+ while retry_count <= max_retries:
81
+ # Perform humanization with formatting preservation
82
+ humanized = preserve_formatting(text, humanizer.humanize)
83
+
84
+ # Check quality (only on natural language parts)
85
+ if passes_quality_check(humanized):
86
+ logger.info(f"Quality check passed (attempt {retry_count + 1})")
87
+ return humanized
88
+ else:
89
+ retry_count += 1
90
+ if retry_count <= max_retries:
91
+ logger.info(f"Quality check failed, retrying (attempt {retry_count})")
92
+ # Use the humanized output as input for retry
93
+ text = humanized
94
+ else:
95
+ logger.warning(f"Quality check failed after {max_retries} retries")
96
+ return humanized # Return the best we have
97
+
98
+ return humanized
99
+
100
+ # --- SCORE CALCULATION ---
101
+
102
+ def compute_scores(original: str, humanized: str) -> dict:
103
+ """Compute humanization scores"""
104
+ import re
105
+ import statistics
106
+
107
+ # Split into sentences
108
+ sentences = re.findall(r'[^.!?]+[.!?]+', humanized) or []
109
+
110
+ if len(sentences) >= 2:
111
+ try:
112
+ # Calculate sentence length variation
113
+ lens = [len(s.split()) for s in sentences]
114
+ std = statistics.pstdev(lens)
115
+ burst_score = min(int(std * 10), 60)
116
+ except:
117
+ burst_score = 0
118
+ else:
119
+ burst_score = 0
120
+
121
+ # Contraction score
122
+ contractions = len(re.findall(r"\b\w+'\w+\b", humanized))
123
+ contr_score = min(contractions * 4, 25)
124
+
125
+ # Vocabulary change score
126
+ orig_words = set(original.lower().split())
127
+ hum_words = set(humanized.lower().split())
128
+ if orig_words:
129
+ changed = len(orig_words - hum_words)
130
+ vocab_score = min(int((changed / len(orig_words)) * 50), 35)
131
+ else:
132
+ vocab_score = 0
133
+
134
+ # Quality check result
135
+ quality_passed = passes_quality_check(humanized)
136
+
137
+ # Base human score with quality bonus
138
+ base_score = 75 if quality_passed else 60
139
+ human_score = min(
140
+ base_score + burst_score + contr_score + vocab_score,
141
+ 99
142
+ )
143
+
144
+ return {
145
+ "human_score": human_score,
146
+ "ai_score": 100 - human_score,
147
+ "uniqueness": min(85 + vocab_score + burst_score, 99),
148
+ "quality_check_passed": quality_passed
149
+ }
150
+
151
+ # --- ENDPOINTS ---
152
+
153
+ @app.get("/health")
154
+ async def health():
155
+ """Health check endpoint"""
156
+ return {
157
+ "status": "ok",
158
+ "version": "3.0",
159
+ "system": "Three-Pass Humanizer",
160
+ "passes": config.settings.passes
161
+ }
162
+
163
+ @app.get("/")
164
+ async def root():
165
+ return {
166
+ "message": "Three-Pass Humanizer API is running",
167
+ "endpoint": "POST /humanize",
168
+ "description": "Internal three-pass rewriting system"
169
+ }
170
+
171
+ @app.post("/humanize", response_model=HumanizeResponse)
172
+ async def humanize_endpoint(req: HumanizeRequest):
173
+ """
174
+ Main endpoint for three-pass humanization.
175
+ Uses internal rewriting system with quality check and retry.
176
+ """
177
+ try:
178
+ # Validate
179
+ text = req.text.strip() if req.text else ""
180
+ if not text:
181
+ raise HTTPException(status_code=400, detail="Text cannot be empty")
182
+
183
+ word_count = len(text.split())
184
+ if word_count > 10000: # Increased limit for three-pass system
185
+ raise HTTPException(status_code=400, detail="Text too long. Max 10,000 words.")
186
+
187
+ # Process with three-pass humanization
188
+ start = time.time()
189
+ humanized = humanize_with_quality_check(text)
190
+ scores = compute_scores(text, humanized)
191
+ elapsed_ms = int((time.time() - start) * 1000)
192
+
193
+ logger.info(f"Three-pass humanized {word_count} words → {len(humanized.split())} words in {elapsed_ms}ms")
194
+ logger.info(f"Quality check: {scores['quality_check_passed']}, Human score: {scores['human_score']}")
195
+
196
+ # Get formatting preservation analysis
197
+ formatting_analysis = analyze_formatting(text)
198
+
199
+ # Convert to plain text for copy/download (without Markdown syntax)
200
+ plain_text = convert_for_copy(humanized)
201
+
202
+ return HumanizeResponse(
203
+ output=humanized, # Formatted text with Markdown (for display)
204
+ plain_text=plain_text, # Plain text without Markdown (for copy/download)
205
+ word_count_original=word_count,
206
+ word_count_output=len(humanized.split()),
207
+ processing_time_ms=elapsed_ms,
208
+ formatting_preserved=formatting_analysis,
209
+ **scores,
210
+ )
211
+
212
+ except HTTPException:
213
+ # Re-raise HTTP exceptions (validation errors)
214
+ raise
215
+ except Exception as e:
216
+ # Catch all other exceptions, log with full traceback, and return 500
217
+ logger.error(f"Humanization processing error: {str(e)}", exc_info=True)
218
+ raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")
219
+
220
+ @app.post("/humanize-document")
221
+ async def humanize_document(
222
+ file: UploadFile = File(..., description="Document file (TXT or DOCX)"),
223
+ style: str = Form("neutral"),
224
+ output_format: str = Form("json", description="Output format: json, txt, docx, or pdf")
225
+ ):
226
+ """
227
+ Handles file uploads and processes documents with three-pass humanization.
228
+ Supports TXT and DOCX input, returns JSON or file download.
229
+ """
230
+ try:
231
+ # Read file content
232
+ content = await file.read()
233
+
234
+ # Determine file type and extract text
235
+ filename = file.filename.lower()
236
+ if filename.endswith('.txt'):
237
+ try:
238
+ text = content.decode('utf-8')
239
+ except UnicodeDecodeError as e:
240
+ logger.error(f"Failed to decode TXT file: {str(e)}")
241
+ raise HTTPException(
242
+ status_code=400,
243
+ detail="Invalid TXT file encoding. Please ensure the file is UTF-8 encoded."
244
+ )
245
+ elif filename.endswith('.docx'):
246
+ # For DOCX, we need python-docx library
247
+ # For now, return error if not available
248
+ try:
249
+ from docx import Document
250
+ import io
251
+ doc = Document(io.BytesIO(content))
252
+ # Simple text extraction from DOCX
253
+ text = "\n".join([paragraph.text for paragraph in doc.paragraphs if paragraph.text.strip()])
254
+ except ImportError:
255
+ raise HTTPException(
256
+ status_code=400,
257
+ detail="DOCX support not available. Please upload TXT files or install python-docx."
258
+ )
259
+ except Exception as e:
260
+ logger.error(f"Failed to parse DOCX file: {str(e)}")
261
+ raise HTTPException(
262
+ status_code=400,
263
+ detail="Invalid or corrupted DOCX file. Please ensure the file is a valid DOCX document."
264
+ )
265
+ else:
266
+ raise HTTPException(status_code=400, detail="Unsupported file type. Use .txt or .docx")
267
+
268
+ # Validate text
269
+ if not text.strip():
270
+ raise HTTPException(status_code=400, detail="Document is empty")
271
+
272
+ word_count = len(text.split())
273
+ if word_count > 10000:
274
+ raise HTTPException(status_code=400, detail="Document too long. Max 10,000 words.")
275
+
276
+ # Process with three-pass humanization
277
+ start = time.time()
278
+ humanized = humanize_with_quality_check(text)
279
+ elapsed_ms = int((time.time() - start) * 1000)
280
+
281
+ logger.info(f"Three-pass humanized document: {word_count} words in {elapsed_ms}ms")
282
+
283
+ # Return based on requested format
284
+ if output_format == "json":
285
+ scores = compute_scores(text, humanized)
286
+ # Convert to plain text for copy/download (without Markdown syntax)
287
+ plain_text = convert_for_copy(humanized)
288
+ return {
289
+ "output": humanized, # Formatted text with Markdown (for display)
290
+ "plain_text": plain_text, # Plain text without Markdown (for copy/download)
291
+ "metrics": {
292
+ "word_count_original": word_count,
293
+ "word_count_output": len(humanized.split()),
294
+ "processing_time_ms": elapsed_ms,
295
+ "human_score": scores["human_score"],
296
+ "quality_check_passed": scores["quality_check_passed"],
297
+ "passes": 3
298
+ }
299
+ }
300
+
301
+ elif output_format == "txt":
302
+ # Convert to plain text for download (without Markdown syntax)
303
+ plain_text = convert_for_copy(humanized)
304
+ return Response(
305
+ content=plain_text.encode('utf-8'),
306
+ media_type="text/plain",
307
+ headers={"Content-Disposition": "attachment; filename=humanized.txt"}
308
+ )
309
+
310
+ elif output_format == "docx":
311
+ # For DOCX output, we need python-docx
312
+ try:
313
+ from docx import Document
314
+ import io
315
+
316
+ # Convert to plain text for DOCX export (without Markdown syntax)
317
+ plain_text = convert_for_copy(humanized)
318
+ doc = Document()
319
+ for paragraph in plain_text.split('\n\n'):
320
+ if paragraph.strip():
321
+ doc.add_paragraph(paragraph.strip())
322
+
323
+ # Save to bytes
324
+ docx_io = io.BytesIO()
325
+ doc.save(docx_io)
326
+ docx_io.seek(0)
327
+
328
+ return Response(
329
+ content=docx_io.getvalue(),
330
+ media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
331
+ headers={"Content-Disposition": "attachment; filename=humanized.docx"}
332
+ )
333
+ except ImportError:
334
+ raise HTTPException(
335
+ status_code=400,
336
+ detail="DOCX output not available. Please use 'json' or 'txt' format."
337
+ )
338
+ except Exception as e:
339
+ logger.error(f"Failed to create DOCX output: {str(e)}")
340
+ raise HTTPException(
341
+ status_code=500,
342
+ detail="Failed to generate DOCX output. Please try 'json' or 'txt' format."
343
+ )
344
+
345
+ elif output_format == "pdf":
346
+ # For PDF output, use export pipeline
347
+ if not HAS_EXPORT_PIPELINE:
348
+ raise HTTPException(
349
+ status_code=400,
350
+ detail="PDF export not available. Export pipeline failed to load."
351
+ )
352
+
353
+ try:
354
+ # Convert to plain text for PDF export (without Markdown syntax)
355
+ plain_text = convert_for_copy(humanized)
356
+ pdf_bytes = export_pipeline.to_pdf(plain_text)
357
+
358
+ return Response(
359
+ content=pdf_bytes,
360
+ media_type="application/pdf",
361
+ headers={"Content-Disposition": "attachment; filename=humanized.pdf"}
362
+ )
363
+ except ImportError as e:
364
+ logger.error(f"PDF export dependency error: {str(e)}")
365
+ raise HTTPException(
366
+ status_code=400,
367
+ detail=f"PDF output not available: {str(e)}"
368
+ )
369
+ except Exception as e:
370
+ logger.error(f"Failed to create PDF output: {str(e)}")
371
+ raise HTTPException(
372
+ status_code=500,
373
+ detail=f"Failed to generate PDF output: {str(e)}"
374
+ )
375
+ else:
376
+ raise HTTPException(status_code=400, detail="Invalid output format. Use: json, txt, docx, or pdf")
377
+
378
+ except HTTPException:
379
+ raise
380
+ except Exception as e:
381
+ logger.error(f"Document processing error: {str(e)}", exc_info=True)
382
+ raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")
383
+
384
+ @app.post("/humanize-stream")
385
+ async def humanize_stream(req: HumanizeRequest):
386
+ """
387
+ Streaming endpoint (legacy compatibility).
388
+ Returns same as /humanize endpoint.
389
+ """
390
+ return await humanize_endpoint(req)
391
+
392
+ # ── DO NOT add @app.options("/humanize") ──────────────────────
393
+ # CORSMiddleware handles OPTIONS preflight automatically.
394
+ # A manual OPTIONS handler conflicts with the middleware.
395
+
396
+ if __name__ == "__main__":
397
+ import uvicorn
398
+ port = int(os.getenv("PORT", config.settings.port))
399
+ uvicorn.run(app, host="0.0.0.0", port=port)
config.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration module for Humanizer System
3
+ Simplified for Hugging Face Spaces - No .env file needed
4
+ """
5
+
6
+ import os
7
+ from typing import Optional
8
+
9
+ # Simple configuration without pydantic-settings dependency
10
+ class Settings:
11
+ """Application settings - Simplified for HF Spaces"""
12
+
13
+ def __init__(self):
14
+ # Humanizer Configuration
15
+ self.passes = int(os.getenv("PASSES", "3"))
16
+ self.temperature = float(os.getenv("TEMPERATURE", "0.95")) # For random variation
17
+ self.top_p = float(os.getenv("TOP_P", "0.9")) # For vocabulary selection
18
+
19
+ # Quality Check Configuration
20
+ self.min_variety_score = float(os.getenv("MIN_VARIETY_SCORE", "0.7"))
21
+ self.max_ai_phrase_hits = int(os.getenv("MAX_AI_PHRASE_HITS", "0"))
22
+ self.max_retries = int(os.getenv("MAX_RETRIES", "1"))
23
+
24
+ # Export Configuration
25
+ self.pdf_use_browser = os.getenv("PDF_USE_BROWSER", "true").lower() == "true"
26
+ self.pdf_use_server = os.getenv("PDF_USE_SERVER", "false").lower() == "true"
27
+ self.docx_library = os.getenv("DOCX_LIBRARY", "docx")
28
+
29
+ # Server Configuration
30
+ self.port = int(os.getenv("PORT", "7860"))
31
+ self.cors_origins = os.getenv("CORS_ORIGINS", "*")
32
+ self.log_level = os.getenv("LOG_LEVEL", "INFO")
33
+
34
+
35
+ # System prompt for three-pass rewriting (conceptual, not for API)
36
+ THREE_PASS_SYSTEM = """Three-pass rewriting system:
37
+ Pass 1 → fix clarity and flow
38
+ Pass 2 → vary rhythm, remove robotic patterns
39
+ Pass 3 → deeply human tone: organic phrasing, natural variation, subtle conversational shifts, zero AI clichés
40
+
41
+ Rules:
42
+ - Perform three internal rewriting passes
43
+ - Preserve ALL Markdown formatting exactly
44
+ - Return ONLY the final Pass 3 output
45
+ - No labels, no commentary, no explanations"""
46
+
47
+
48
+ # AI phrases for quality check
49
+ AI_PHRASES = [
50
+ "it is important to note",
51
+ "in conclusion",
52
+ "furthermore",
53
+ "it is worth noting",
54
+ "as an ai",
55
+ "I'd be happy to",
56
+ "certainly",
57
+ "delve into",
58
+ "leverage",
59
+ "utilize",
60
+ "in today's world"
61
+ ]
62
+
63
+ # Create settings instance
64
+ settings = Settings()
65
+
66
+ # Add AI_PHRASES to settings for backward compatibility
67
+ settings.AI_PHRASES = AI_PHRASES
68
+
69
+ # Add THREE_PASS_SYSTEM to settings
70
+ settings.THREE_PASS_SYSTEM = THREE_PASS_SYSTEM
export_pipeline.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Export pipeline for Humanizer System
3
+ Handles Markdown to HTML, PDF, and DOCX conversion
4
+ """
5
+
6
+ import io
7
+ import markdown
8
+ from typing import Optional
9
+ import config
10
+
11
+ try:
12
+ from docx import Document
13
+ HAS_DOCX = True
14
+ except ImportError:
15
+ HAS_DOCX = False
16
+
17
+ try:
18
+ from weasyprint import HTML
19
+ HAS_WEASYPRINT = True
20
+ except (ImportError, OSError) as e:
21
+ # OSError can occur on Windows if GTK3 is not installed
22
+ HAS_WEASYPRINT = False
23
+ WEAZYPRINT_ERROR = str(e)
24
+
25
+
26
+ class ExportPipeline:
27
+ """Export pipeline for converting humanized text to various formats"""
28
+
29
+ def __init__(self):
30
+ self.settings = config.settings
31
+
32
+ def to_html(self, markdown_text: str) -> str:
33
+ """
34
+ Convert Markdown to HTML
35
+ Preserves formatting as specified in requirements
36
+ """
37
+ # Use markdown library with extensions for better formatting
38
+ html = markdown.markdown(
39
+ markdown_text,
40
+ extensions=[
41
+ 'extra', # Adds tables, footnotes, etc.
42
+ 'codehilite', # Syntax highlighting for code blocks
43
+ 'toc', # Table of contents
44
+ 'nl2br', # Convert newlines to <br>
45
+ 'sane_lists', # Better list handling
46
+ ],
47
+ output_format='html5'
48
+ )
49
+
50
+ # Wrap in basic HTML structure for better rendering
51
+ html_template = f"""
52
+ <!DOCTYPE html>
53
+ <html>
54
+ <head>
55
+ <meta charset="UTF-8">
56
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
57
+ <title>Humanized Text</title>
58
+ <style>
59
+ body {{
60
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
61
+ line-height: 1.6;
62
+ color: #333;
63
+ max-width: 800px;
64
+ margin: 0 auto;
65
+ padding: 20px;
66
+ }}
67
+ h1, h2, h3, h4, h5, h6 {{
68
+ margin-top: 1.5em;
69
+ margin-bottom: 0.5em;
70
+ font-weight: 600;
71
+ line-height: 1.25;
72
+ }}
73
+ p {{
74
+ margin-top: 0;
75
+ margin-bottom: 1em;
76
+ }}
77
+ ul, ol {{
78
+ margin-top: 0;
79
+ margin-bottom: 1em;
80
+ padding-left: 2em;
81
+ }}
82
+ li {{
83
+ margin-bottom: 0.5em;
84
+ }}
85
+ code {{
86
+ background-color: #f6f8fa;
87
+ padding: 0.2em 0.4em;
88
+ border-radius: 3px;
89
+ font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
90
+ font-size: 0.9em;
91
+ }}
92
+ pre {{
93
+ background-color: #f6f8fa;
94
+ padding: 1em;
95
+ border-radius: 5px;
96
+ overflow: auto;
97
+ }}
98
+ blockquote {{
99
+ margin: 0;
100
+ padding-left: 1em;
101
+ border-left: 3px solid #ddd;
102
+ color: #666;
103
+ }}
104
+ hr {{
105
+ border: 0;
106
+ height: 1px;
107
+ background-color: #ddd;
108
+ margin: 2em 0;
109
+ }}
110
+ table {{
111
+ border-collapse: collapse;
112
+ width: 100%;
113
+ margin-bottom: 1em;
114
+ }}
115
+ th, td {{
116
+ border: 1px solid #ddd;
117
+ padding: 0.5em;
118
+ text-align: left;
119
+ }}
120
+ th {{
121
+ background-color: #f6f8fa;
122
+ font-weight: 600;
123
+ }}
124
+ </style>
125
+ </head>
126
+ <body>
127
+ {html}
128
+ </body>
129
+ </html>
130
+ """
131
+
132
+ return html_template
133
+
134
+ def to_pdf(self, markdown_text: str, filename: Optional[str] = None) -> bytes:
135
+ """
136
+ Convert Markdown to PDF using WeasyPrint
137
+ Returns PDF bytes
138
+ """
139
+ if not HAS_WEASYPRINT:
140
+ error_msg = "WeasyPrint is not available. "
141
+ if 'WEAZYPRINT_ERROR' in globals():
142
+ error_msg += f"Error: {WEAZYPRINT_ERROR}. "
143
+ error_msg += "On Windows, you may need to install GTK3. Alternatively, use DOCX or TXT export."
144
+ raise ImportError(error_msg)
145
+
146
+ # Convert Markdown to HTML
147
+ html = self.to_html(markdown_text)
148
+
149
+ # Generate PDF
150
+ pdf_bytes = HTML(string=html).write_pdf()
151
+
152
+ return pdf_bytes
153
+
154
+ def to_docx(self, markdown_text: str, filename: Optional[str] = None) -> bytes:
155
+ """
156
+ Convert Markdown to DOCX using python-docx
157
+ Returns DOCX bytes
158
+ """
159
+ if not HAS_DOCX:
160
+ raise ImportError("python-docx is not installed. Install with: pip install python-docx")
161
+
162
+ # Create a new Document
163
+ doc = Document()
164
+
165
+ # Split text into paragraphs (using double newlines as paragraph separators)
166
+ paragraphs = markdown_text.split('\n\n')
167
+
168
+ for paragraph in paragraphs:
169
+ if paragraph.strip():
170
+ # Clean up the paragraph (remove single newlines within paragraphs)
171
+ clean_paragraph = ' '.join(paragraph.split('\n'))
172
+
173
+ # Check if it's a heading
174
+ if clean_paragraph.startswith('# '):
175
+ doc.add_heading(clean_paragraph[2:], level=1)
176
+ elif clean_paragraph.startswith('## '):
177
+ doc.add_heading(clean_paragraph[3:], level=2)
178
+ elif clean_paragraph.startswith('### '):
179
+ doc.add_heading(clean_paragraph[4:], level=3)
180
+ elif clean_paragraph.startswith('#### '):
181
+ doc.add_heading(clean_paragraph[5:], level=4)
182
+ elif clean_paragraph.startswith('##### '):
183
+ doc.add_heading(clean_paragraph[6:], level=5)
184
+ elif clean_paragraph.startswith('###### '):
185
+ doc.add_heading(clean_paragraph[7:], level=6)
186
+ # Check if it's a list item
187
+ elif clean_paragraph.startswith('- ') or clean_paragraph.startswith('* ') or clean_paragraph.startswith('+ '):
188
+ doc.add_paragraph(clean_paragraph[2:], style='List Bullet')
189
+ elif clean_paragraph[0].isdigit() and clean_paragraph[1] == '.' and clean_paragraph[2] == ' ':
190
+ doc.add_paragraph(clean_paragraph[3:], style='List Number')
191
+ # Regular paragraph
192
+ else:
193
+ doc.add_paragraph(clean_paragraph)
194
+
195
+ # Save to bytes
196
+ docx_io = io.BytesIO()
197
+ doc.save(docx_io)
198
+ docx_io.seek(0)
199
+
200
+ return docx_io.getvalue()
201
+
202
+ def export(self, markdown_text: str, format_type: str, filename: Optional[str] = None) -> bytes:
203
+ """
204
+ Main export method
205
+ Returns file bytes based on format type
206
+ """
207
+ format_type = format_type.lower()
208
+
209
+ if format_type == 'pdf':
210
+ return self.to_pdf(markdown_text, filename)
211
+ elif format_type == 'docx':
212
+ return self.to_docx(markdown_text, filename)
213
+ elif format_type == 'html':
214
+ return self.to_html(markdown_text).encode('utf-8')
215
+ elif format_type == 'txt':
216
+ return markdown_text.encode('utf-8')
217
+ else:
218
+ raise ValueError(f"Unsupported format: {format_type}. Use: pdf, docx, html, txt")
219
+
220
+
221
+ # Create global instance
222
+ export_pipeline = ExportPipeline()
formatting_detector.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Smart Formatting Detector
3
+ Detects and preserves structured elements in text
4
+ """
5
+
6
+ import re
7
+ from typing import List, Tuple, Dict, Any
8
+ import json
9
+
10
+
11
+ class FormattingDetector:
12
+ """Detects structured elements in text for preservation"""
13
+
14
+ def __init__(self):
15
+ # Compile regex patterns for efficiency
16
+ self.patterns = {
17
+ # Code blocks (triple backticks with optional language)
18
+ 'code_block': re.compile(r'```(?:\w+)?\n.*?\n```', re.DOTALL | re.MULTILINE),
19
+
20
+ # Inline code (single backticks)
21
+ 'inline_code': re.compile(r'`[^`\n]+`'),
22
+
23
+ # Headers (Markdown headers)
24
+ 'header': re.compile(r'^(#{1,6})\s+(.+)$', re.MULTILINE),
25
+
26
+ # Lists (bullet points and numbered)
27
+ 'bullet_list': re.compile(r'^[\s]*[-*+]\s+.+$', re.MULTILINE),
28
+ 'numbered_list': re.compile(r'^[\s]*\d+[.)]\s+.+$', re.MULTILINE),
29
+
30
+ # Tables (Markdown tables)
31
+ 'table': re.compile(r'^\|.+\|\s*$[\n\r]^\|[-:|]+\|\s*$[\n\r]^(\|.+\|\s*$)+', re.MULTILINE),
32
+
33
+ # Blockquotes
34
+ 'blockquote': re.compile(r'^>\s+.+$', re.MULTILINE),
35
+
36
+ # Horizontal rules
37
+ 'horizontal_rule': re.compile(r'^[-*_]{3,}\s*$', re.MULTILINE),
38
+
39
+ # JSON blocks (detect JSON-like structures)
40
+ 'json_block': re.compile(r'^\s*\{.*?\}\s*$', re.DOTALL | re.MULTILINE),
41
+
42
+ # XML/HTML blocks
43
+ 'xml_block': re.compile(r'^\s*<[^>]+>.*?</[^>]+>\s*$', re.DOTALL | re.MULTILINE),
44
+
45
+ # URLs
46
+ 'url': re.compile(r'https?://[^\s<>"\']+[^\s<>"\'.)]'),
47
+
48
+ # Email addresses
49
+ 'email': re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'),
50
+
51
+ # File paths (Unix and Windows)
52
+ 'file_path': re.compile(r'(?:/[^/\s]+)+/?(?:\s|$)|(?:[A-Za-z]:\\(?:[^\\\s]+\\)*[^\\\s]+)'),
53
+
54
+ # Code-like patterns (function calls, variable assignments)
55
+ 'code_like': re.compile(r'\b(?:def|class|import|from|if|else|for|while|return|function|var|let|const)\b[^.!?]*[.;]?'),
56
+ }
57
+
58
+ def detect_structured_elements(self, text: str) -> List[Dict[str, Any]]:
59
+ """
60
+ Detect all structured elements in text
61
+ Returns list of elements with type, content, and position
62
+ """
63
+ elements = []
64
+
65
+ # Check each pattern
66
+ for element_type, pattern in self.patterns.items():
67
+ for match in pattern.finditer(text):
68
+ element = {
69
+ 'type': element_type,
70
+ 'content': match.group(),
71
+ 'start': match.start(),
72
+ 'end': match.end(),
73
+ 'preserve': True # All detected elements should be preserved
74
+ }
75
+ elements.append(element)
76
+
77
+ # Sort by start position
78
+ elements.sort(key=lambda x: x['start'])
79
+
80
+ # Remove overlapping elements (keep the first/largest)
81
+ cleaned_elements = []
82
+ last_end = 0
83
+
84
+ for element in elements:
85
+ if element['start'] >= last_end:
86
+ cleaned_elements.append(element)
87
+ last_end = element['end']
88
+ # If overlap, keep the larger element
89
+ elif element['end'] - element['start'] > (last_end - element['start']):
90
+ if cleaned_elements:
91
+ cleaned_elements.pop()
92
+ cleaned_elements.append(element)
93
+ last_end = element['end']
94
+
95
+ return cleaned_elements
96
+
97
+ def tag_text(self, text: str) -> str:
98
+ """
99
+ Tag structured elements in text with special markers
100
+ Returns tagged text where structured elements are wrapped
101
+ """
102
+ elements = self.detect_structured_elements(text)
103
+
104
+ # Build tagged text by replacing elements with tags
105
+ tagged_parts = []
106
+ last_pos = 0
107
+
108
+ for element in elements:
109
+ # Add text before element
110
+ if element['start'] > last_pos:
111
+ tagged_parts.append(text[last_pos:element['start']])
112
+
113
+ # Add tagged element
114
+ tag = f"[[{element['type']}:{len(tagged_parts)}]]"
115
+ tagged_parts.append(element['content'])
116
+ tagged_parts.append(f"[[/{element['type']}]]")
117
+
118
+ last_pos = element['end']
119
+
120
+ # Add remaining text
121
+ if last_pos < len(text):
122
+ tagged_parts.append(text[last_pos:])
123
+
124
+ return ''.join(tagged_parts)
125
+
126
+ def extract_segments(self, text: str) -> List[Tuple[str, str]]:
127
+ """
128
+ Extract segments from text
129
+ Returns list of (segment_type, content)
130
+ """
131
+ elements = self.detect_structured_elements(text)
132
+ segments = []
133
+ last_pos = 0
134
+
135
+ for element in elements:
136
+ # Add natural language segment before element
137
+ if element['start'] > last_pos:
138
+ natural_text = text[last_pos:element['start']].strip()
139
+ if natural_text:
140
+ segments.append(('natural_language', natural_text))
141
+
142
+ # Add structured element
143
+ segments.append((element['type'], element['content']))
144
+
145
+ last_pos = element['end']
146
+
147
+ # Add remaining natural language
148
+ if last_pos < len(text):
149
+ natural_text = text[last_pos:].strip()
150
+ if natural_text:
151
+ segments.append(('natural_language', natural_text))
152
+
153
+ return segments
154
+
155
+ def is_structured_element(self, text: str) -> bool:
156
+ """
157
+ Check if text contains structured elements
158
+ Quick check without full detection
159
+ """
160
+ # Quick checks for common structured patterns
161
+ quick_checks = [
162
+ r'```', # Code blocks
163
+ r'`[^`]`', # Inline code
164
+ r'^#{1,6}\s', # Headers
165
+ r'^[\s]*[-*+]\s', # Bullet lists
166
+ r'^\|', # Tables
167
+ r'^>\s', # Blockquotes
168
+ r'^[-*_]{3,}$', # Horizontal rules
169
+ r'https?://', # URLs
170
+ r'@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}', # Emails
171
+ r'\{.*\}', # JSON-like
172
+ r'<[^>]+>.*</[^>]+>', # XML/HTML
173
+ ]
174
+
175
+ for pattern in quick_checks:
176
+ if re.search(pattern, text, re.MULTILINE | re.DOTALL):
177
+ return True
178
+
179
+ return False
180
+
181
+ def get_preservation_rules(self) -> Dict[str, str]:
182
+ """
183
+ Get rules for what to preserve for each element type
184
+ """
185
+ return {
186
+ 'code_block': 'preserve_exactly',
187
+ 'inline_code': 'preserve_exactly',
188
+ 'header': 'humanize_text_only', # Humanize header text, keep #
189
+ 'bullet_list': 'humanize_items', # Humanize list items, keep bullets
190
+ 'numbered_list': 'humanize_items', # Humanize list items, keep numbers
191
+ 'table': 'preserve_structure', # Keep table structure
192
+ 'blockquote': 'humanize_text_only', # Humanize quote text, keep >
193
+ 'horizontal_rule': 'preserve_exactly',
194
+ 'json_block': 'preserve_exactly',
195
+ 'xml_block': 'preserve_exactly',
196
+ 'url': 'preserve_exactly',
197
+ 'email': 'preserve_exactly',
198
+ 'file_path': 'preserve_exactly',
199
+ 'code_like': 'preserve_exactly',
200
+ }
201
+
202
+
203
+ # Helper functions
204
+ def preserve_formatting(text: str, humanizer_func) -> str:
205
+ """
206
+ Main function to preserve formatting while humanizing
207
+ """
208
+ detector = FormattingDetector()
209
+ segments = detector.extract_segments(text)
210
+ preservation_rules = detector.get_preservation_rules()
211
+
212
+ processed_segments = []
213
+
214
+ for segment_type, content in segments:
215
+ if segment_type == 'natural_language':
216
+ # Humanize natural language
217
+ processed_segments.append(humanizer_func(content))
218
+ else:
219
+ # Apply preservation rule
220
+ rule = preservation_rules.get(segment_type, 'preserve_exactly')
221
+
222
+ if rule == 'preserve_exactly':
223
+ processed_segments.append(content)
224
+ elif rule == 'humanize_text_only':
225
+ # For headers: humanize text after #
226
+ if segment_type == 'header':
227
+ match = re.match(r'^(#{1,6}\s+)(.+)$', content)
228
+ if match:
229
+ prefix = match.group(1)
230
+ header_text = match.group(2)
231
+ humanized_text = humanizer_func(header_text)
232
+ processed_segments.append(f"{prefix}{humanized_text}")
233
+ else:
234
+ processed_segments.append(content)
235
+ # For blockquotes: humanize text after >
236
+ elif segment_type == 'blockquote':
237
+ lines = content.split('\n')
238
+ humanized_lines = []
239
+ for line in lines:
240
+ match = re.match(r'^(>\s*)(.+)$', line)
241
+ if match:
242
+ prefix = match.group(1)
243
+ quote_text = match.group(2)
244
+ humanized_text = humanizer_func(quote_text)
245
+ humanized_lines.append(f"{prefix}{humanized_text}")
246
+ else:
247
+ humanized_lines.append(line)
248
+ processed_segments.append('\n'.join(humanized_lines))
249
+ else:
250
+ processed_segments.append(content)
251
+ elif rule == 'humanize_items':
252
+ # For lists: humanize each item
253
+ lines = content.split('\n')
254
+ humanized_lines = []
255
+ for line in lines:
256
+ # Bullet lists
257
+ match = re.match(r'^([\s]*[-*+]\s+)(.+)$', line)
258
+ if match:
259
+ prefix = match.group(1)
260
+ item_text = match.group(2)
261
+ humanized_text = humanizer_func(item_text)
262
+ humanized_lines.append(f"{prefix}{humanized_text}")
263
+ continue
264
+
265
+ # Numbered lists
266
+ match = re.match(r'^([\s]*\d+[.)]\s+)(.+)$', line)
267
+ if match:
268
+ prefix = match.group(1)
269
+ item_text = match.group(2)
270
+ humanized_text = humanizer_func(item_text)
271
+ humanized_lines.append(f"{prefix}{humanized_text}")
272
+ continue
273
+
274
+ # Keep line as is (indentation, etc.)
275
+ humanized_lines.append(line)
276
+ processed_segments.append('\n'.join(humanized_lines))
277
+ elif rule == 'preserve_structure':
278
+ # For tables: preserve structure
279
+ processed_segments.append(content)
280
+ else:
281
+ processed_segments.append(content)
282
+
283
+ # Reconstruct text
284
+ return '\n'.join(processed_segments)
285
+
286
+
287
+ # Create global instance
288
+ formatting_detector = FormattingDetector()
humanizer_three_pass.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Three-Pass Humanization Engine
3
+ Self-contained rewriting system with three internal passes
4
+ """
5
+
6
+ import re
7
+ import random
8
+ import statistics
9
+ from typing import List, Tuple
10
+ from config import settings
11
+
12
+
13
+ class ThreePassHumanizer:
14
+ """Three-pass humanization engine"""
15
+
16
+ def __init__(self):
17
+ self.passes = settings.passes
18
+ self.temperature = settings.temperature
19
+ self.top_p = settings.top_p
20
+
21
+ # Vocabulary transformations for different passes
22
+ self.pass1_transforms = self._get_pass1_transforms()
23
+ self.pass2_transforms = self._get_pass2_transforms()
24
+ self.pass3_transforms = self._get_pass3_transforms()
25
+
26
+ def _get_pass1_transforms(self) -> List[Tuple[re.Pattern, str]]:
27
+ """Pass 1: Fix clarity and flow"""
28
+ transforms = [
29
+ # Remove redundant phrases
30
+ (r'\bremains a challenge\b', 'stays difficult'),
31
+ (r'\bcontinues to be\b', 'stays'),
32
+ (r'\brequire knowledge of\b', 'need to know'),
33
+ (r'\brequire understanding of\b', 'need to know'),
34
+ (r'\baddresses these challenges\b', 'solves these problems'),
35
+ (r'\btackles these challenges\b', 'handles these issues'),
36
+
37
+ # Simplify complex words
38
+ (r'\butilizing\b', 'using'),
39
+ (r'\binterprets\b', 'reads'),
40
+ (r'\bunderstands\b', 'gets'),
41
+ (r'\bgenerate\b', 'make'),
42
+ (r'\bcreate\b', 'build'),
43
+ (r'\bautomatically selects\b', 'picks'),
44
+ (r'\bappropriate\b', 'right'),
45
+ (r'\bsuitable\b', 'fitting'),
46
+ (r'\bintegrates\b', 'adds'),
47
+ (r'\brelevant\b', 'related'),
48
+ (r'\bcustomizes\b', 'changes'),
49
+ (r'\badjusts\b', 'tweaks'),
50
+
51
+ # Improve flow
52
+ (r'\bIn today\'s modern online environment\b', 'In the current digital world'),
53
+ (r'\bIn the modern digital landscape\b', 'In today\'s online space'),
54
+ (r'\bnon-technical users\b', 'people without tech skills'),
55
+ (r'\balong with\b', 'and'),
56
+ ]
57
+ return [(re.compile(p, re.IGNORECASE), r) for p, r in transforms]
58
+
59
+ def _get_pass2_transforms(self) -> List[Tuple[re.Pattern, str]]:
60
+ """Pass 2: Vary rhythm, remove robotic patterns"""
61
+ transforms = [
62
+ # Vary sentence structure
63
+ (r'\bsimply describe\b', 'just say'),
64
+ (r'\bjust explain\b', 'just tell'),
65
+ (r'\bfully functional\b', 'working'),
66
+ (r'\bcomplete\b', 'full'),
67
+ (r'\bvisual elements\b', 'design bits'),
68
+ (r'\bdesign features\b', 'design parts'),
69
+ (r'\binteract with\b', 'work with'),
70
+ (r'\bimproving\b', 'boosting'),
71
+ (r'\benhancing\b', 'improving'),
72
+
73
+ # Remove robotic patterns
74
+ (r'\bpersonalization\b', 'personal touch'),
75
+ (r'\bcustomization\b', 'personal setup'),
76
+ (r'\bover time\b', 'bit by bit'),
77
+ (r'\bgradually\b', 'step by step'),
78
+ (r'\badaptability\b', 'flexibility'),
79
+ (r'\bensures\b', 'makes sure'),
80
+ (r'\bguarantees\b', 'ensures'),
81
+ (r'\bincreasingly\b', 'more and more'),
82
+
83
+ # Add variation
84
+ (r'\bintuitive\b', 'easy'),
85
+ (r'\buser-friendly\b', 'simple'),
86
+ (r'\beffective\b', 'useful'),
87
+ (r'\befficient\b', 'effective'),
88
+ (r'\boffers\b', 'gives'),
89
+ (r'\bprovides\b', 'offers'),
90
+ ]
91
+ return [(re.compile(p, re.IGNORECASE), r) for p, r in transforms]
92
+
93
+ def _get_pass3_transforms(self) -> List[Tuple[re.Pattern, str]]:
94
+ """Pass 3: Deeply human tone, organic phrasing"""
95
+ transforms = [
96
+ # Organic phrasing
97
+ (r'\bcost-effective\b', 'affordable'),
98
+ (r'\baffordable\b', 'budget-friendly'),
99
+ (r'\bscalable\b', 'flexible'),
100
+ (r'\balternative\b', 'option'),
101
+ (r'\btraditional\b', 'standard'),
102
+ (r'\bconventional\b', 'traditional'),
103
+ (r'\benhancements\b', 'upgrades'),
104
+ (r'\bimprovements\b', 'enhancements'),
105
+
106
+ # Conversational shifts
107
+ (r'\bdemocratizing\b', 'opening up'),
108
+ (r'\bmaking accessible\b', 'democratizing'),
109
+ (r'\bplain English processing\b', 'natural language processing'),
110
+ (r'\beveryday language\b', 'plain language'),
111
+ (r'\bBuilt for\b', 'Made for'),
112
+ (r'\bUpcoming features\b', 'Future additions'),
113
+
114
+ # Contractions for natural speech
115
+ (r'\bcannot\b', "can't"),
116
+ (r'\bdo not\b', "don't"),
117
+ (r'\bdoes not\b', "doesn't"),
118
+ (r'\bwill not\b', "won't"),
119
+ (r'\bis not\b', "isn't"),
120
+ (r'\bare not\b', "aren't"),
121
+ (r'\bwould not\b', "wouldn't"),
122
+ (r'\bcould not\b', "couldn't"),
123
+ (r'\bshould not\b', "shouldn't"),
124
+ (r'\bit is\b', "it's"),
125
+ (r'\bthat is\b', "that's"),
126
+ (r'\bwhat is\b', "what's"),
127
+ ]
128
+ return [(re.compile(p, re.IGNORECASE), r) for p, r in transforms]
129
+
130
+ def _apply_transforms(self, text: str, transforms: List[Tuple[re.Pattern, str]]) -> str:
131
+ """Apply transformations to text"""
132
+ for pattern, repl in transforms:
133
+ text = pattern.sub(repl, text)
134
+ return text
135
+
136
+ def _pass1_clarity_flow(self, text: str) -> str:
137
+ """Pass 1: Fix clarity and flow"""
138
+ # Apply clarity transforms
139
+ text = self._apply_transforms(text, self.pass1_transforms)
140
+
141
+ # Improve sentence structure
142
+ sentences = self._split_sentences(text)
143
+ sentences = self._improve_clarity(sentences)
144
+
145
+ return self._join_sentences(sentences)
146
+
147
+ def _pass2_rhythm_variation(self, text: str) -> str:
148
+ """Pass 2: Vary rhythm, remove robotic patterns"""
149
+ # Apply rhythm transforms
150
+ text = self._apply_transforms(text, self.pass2_transforms)
151
+
152
+ # Vary sentence length and structure
153
+ sentences = self._split_sentences(text)
154
+ sentences = self._vary_rhythm(sentences)
155
+
156
+ return self._join_sentences(sentences)
157
+
158
+ def _pass3_human_tone(self, text: str) -> str:
159
+ """Pass 3: Deeply human tone, organic phrasing"""
160
+ # Apply human tone transforms
161
+ text = self._apply_transforms(text, self.pass3_transforms)
162
+
163
+ # Add organic phrasing and natural variation
164
+ sentences = self._split_sentences(text)
165
+ sentences = self._add_human_touch(sentences)
166
+
167
+ return self._join_sentences(sentences)
168
+
169
+ def _split_sentences(self, text: str) -> List[str]:
170
+ """Split text into sentences"""
171
+ if not text.strip():
172
+ return []
173
+ sentences = re.split(r'(?<=[.!?])\s+(?=[A-Z])', text.strip())
174
+ return [s.strip() for s in sentences if s.strip()]
175
+
176
+ def _join_sentences(self, sentences: List[str]) -> str:
177
+ """Join sentences into text"""
178
+ return ' '.join(sentences)
179
+
180
+ def _improve_clarity(self, sentences: List[str]) -> List[str]:
181
+ """Improve clarity of sentences"""
182
+ result = []
183
+ for sentence in sentences:
184
+ # Remove redundant words
185
+ sentence = re.sub(r'\bvery\s+', '', sentence, flags=re.IGNORECASE)
186
+ sentence = re.sub(r'\breally\s+', '', sentence, flags=re.IGNORECASE)
187
+ sentence = re.sub(r'\bquite\s+', '', sentence, flags=re.IGNORECASE)
188
+
189
+ # Simplify complex structures
190
+ sentence = re.sub(r'\bin order to\b', 'to', sentence, flags=re.IGNORECASE)
191
+ sentence = re.sub(r'\bwith the purpose of\b', 'to', sentence, flags=re.IGNORECASE)
192
+
193
+ result.append(sentence)
194
+ return result
195
+
196
+ def _vary_rhythm(self, sentences: List[str]) -> List[str]:
197
+ """Vary sentence rhythm"""
198
+ if len(sentences) < 2:
199
+ return sentences
200
+
201
+ result = []
202
+ i = 0
203
+
204
+ while i < len(sentences):
205
+ current = sentences[i]
206
+ word_count = len(current.split())
207
+
208
+ # Merge short sentences (30% chance)
209
+ if word_count < 10 and i + 1 < len(sentences) and random.random() < 0.3:
210
+ next_sent = sentences[i + 1]
211
+ connectors = ['; ', ', and ', ', while ', ', but ']
212
+ connector = random.choice(connectors)
213
+
214
+ # Lowercase first letter of second sentence
215
+ next_lower = next_sent[0].lower() + next_sent[1:] if len(next_sent) > 1 else next_sent
216
+ merged = current.rstrip('.!?') + connector + next_lower
217
+ result.append(merged)
218
+ i += 2
219
+ else:
220
+ result.append(current)
221
+ i += 1
222
+
223
+ return result
224
+
225
+ def _add_human_touch(self, sentences: List[str]) -> List[str]:
226
+ """Add human touch to sentences"""
227
+ result = []
228
+ for i, sentence in enumerate(sentences):
229
+ words = sentence.split()
230
+
231
+ # Add occasional em-dash for dramatic pause (15% chance)
232
+ if len(words) > 12 and random.random() < 0.15:
233
+ split_point = len(words) // 2
234
+ first_part = ' '.join(words[:split_point])
235
+ second_part = ' '.join(words[split_point:])
236
+ sentence = f"{first_part} — {second_part}"
237
+
238
+ # Add conversational transitions (20% chance for non-first sentences)
239
+ if i > 0 and random.random() < 0.2:
240
+ transitions = ['In fact, ', 'Notably, ', 'Essentially, ', 'What\'s more, ']
241
+ transition = random.choice(transitions)
242
+ sentence = transition + sentence[0].lower() + sentence[1:]
243
+
244
+ result.append(sentence)
245
+ return result
246
+
247
+ def humanize(self, text: str) -> str:
248
+ """
249
+ Perform three-pass humanization
250
+ Returns ONLY the final Pass 3 output
251
+ """
252
+ if not text.strip():
253
+ return text
254
+
255
+ # Preserve Markdown formatting by processing line by line
256
+ lines = text.split('\n')
257
+ result_lines = []
258
+
259
+ for line in lines:
260
+ if not line.strip():
261
+ result_lines.append('')
262
+ continue
263
+
264
+ # Skip Markdown headers, lists, etc.
265
+ if self._is_markdown_element(line):
266
+ result_lines.append(line)
267
+ continue
268
+
269
+ # Perform three-pass rewriting
270
+ pass1 = self._pass1_clarity_flow(line)
271
+ pass2 = self._pass2_rhythm_variation(pass1)
272
+ pass3 = self._pass3_human_tone(pass2)
273
+
274
+ result_lines.append(pass3)
275
+
276
+ return '\n'.join(result_lines)
277
+
278
+ def _is_markdown_element(self, line: str) -> bool:
279
+ """Check if line is a Markdown element that should be preserved"""
280
+ line = line.strip()
281
+
282
+ # Markdown headers
283
+ if re.match(r'^#{1,6}\s', line):
284
+ return True
285
+
286
+ # Lists
287
+ if re.match(r'^[•\-*+]\s', line) or re.match(r'^\d+[.)]\s', line):
288
+ return True
289
+
290
+ # Code blocks
291
+ if line.startswith('```') or line.startswith('`'):
292
+ return True
293
+
294
+ # Horizontal rules
295
+ if re.match(r'^[-*_]{3,}$', line):
296
+ return True
297
+
298
+ # Blockquotes
299
+ if line.startswith('>'):
300
+ return True
301
+
302
+ return False
303
+
304
+
305
+ # Quality check functions
306
+ def passes_quality_check(text: str) -> bool:
307
+ """Check if text passes quality thresholds"""
308
+ sentences = re.findall(r'[^.!?]+[.!?]+', text) or []
309
+
310
+ if len(sentences) < 2:
311
+ return True # Short texts pass by default
312
+
313
+ # Calculate variety score
314
+ unique_starts = set()
315
+ for sent in sentences:
316
+ start = sent.strip()[:30]
317
+ unique_starts.add(start)
318
+
319
+ variety_score = len(unique_starts) / len(sentences)
320
+
321
+ # Check for AI phrases
322
+ ai_phrase_hits = 0
323
+ text_lower = text.lower()
324
+ for phrase in settings.AI_PHRASES:
325
+ if phrase in text_lower:
326
+ ai_phrase_hits += 1
327
+
328
+ return variety_score > settings.min_variety_score and ai_phrase_hits <= settings.max_ai_phrase_hits
329
+
330
+
331
+ # Create global instance
332
+ humanizer = ThreePassHumanizer()
333
+
334
+ # Export the quality check function
335
+ __all__ = ['humanizer', 'passes_quality_check']
main.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Main entry point for Hugging Face Spaces deployment
3
+ Combines API with root redirect to frontend
4
+ """
5
+ from fastapi import FastAPI
6
+ from fastapi.responses import RedirectResponse
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ import os
9
+
10
+ # Import our existing app
11
+ from app import app as api_app
12
+
13
+ # Create main app
14
+ app = FastAPI(title="Humanizer System API", version="3.0")
15
+
16
+ # CORS middleware - allow Vercel frontend
17
+ app.add_middleware(
18
+ CORSMiddleware,
19
+ allow_origins=[
20
+ "https://aquahumanizer.vercel.app",
21
+ "http://localhost:3000", # For local development
22
+ "*" # For testing
23
+ ],
24
+ allow_credentials=True,
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
28
+
29
+ # Redirect root to frontend
30
+ @app.get("/")
31
+ async def read_root():
32
+ return RedirectResponse(url="https://aquahumanizer.vercel.app")
33
+
34
+ # Simple info endpoint
35
+ @app.get("/info")
36
+ async def get_info():
37
+ return {
38
+ "name": "Humanizer System API",
39
+ "version": "3.0",
40
+ "description": "Rule-based text humanization backend",
41
+ "frontend": "https://aquahumanizer.vercel.app",
42
+ "endpoints": {
43
+ "POST /humanize": "Humanize text",
44
+ "POST /humanize-document": "Process document files",
45
+ "GET /health": "Health check"
46
+ }
47
+ }
48
+
49
+ # Mount the API app
50
+ app.mount("/", api_app)
51
+
52
+ if __name__ == "__main__":
53
+ import uvicorn
54
+ uvicorn.run(app, host="0.0.0.0", port=7860)
markdown_converter.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Markdown to Plain Text Converter
3
+ Converts Markdown formatting to user-friendly plain text
4
+ """
5
+
6
+ import re
7
+ from typing import Optional
8
+
9
+
10
+ class MarkdownConverter:
11
+ """Converts Markdown to plain text for copy/download"""
12
+
13
+ def __init__(self):
14
+ # Compile regex patterns for efficiency
15
+ self.patterns = {
16
+ # Headers: # Header → Header (with underline for H1)
17
+ 'header': [
18
+ (re.compile(r'^#{6}\s+(.+)$', re.MULTILINE), r'\1'), # H6
19
+ (re.compile(r'^#{5}\s+(.+)$', re.MULTILINE), r'\1'), # H5
20
+ (re.compile(r'^#{4}\s+(.+)$', re.MULTILINE), r'\1'), # H4
21
+ (re.compile(r'^#{3}\s+(.+)$', re.MULTILINE), r'\1'), # H3
22
+ (re.compile(r'^#{2}\s+(.+)$', re.MULTILINE), r'\1'), # H2
23
+ (re.compile(r'^#{1}\s+(.+)$', re.MULTILINE), r'\1\n' + '=' * 50), # H1 with underline
24
+ ],
25
+
26
+ # Bold/Italic: **bold** → bold, *italic* → italic
27
+ 'bold_italic': [
28
+ (re.compile(r'\*\*\*(.+?)\*\*\*'), r'\1'), # ***bold italic***
29
+ (re.compile(r'\*\*(.+?)\*\*'), r'\1'), # **bold**
30
+ (re.compile(r'\*(.+?)\*'), r'\1'), # *italic*
31
+ (re.compile(r'_(.+?)_'), r'\1'), # _italic_
32
+ ],
33
+
34
+ # Code: `code` → "code", ```code``` → code block
35
+ 'code': [
36
+ (re.compile(r'```(?:\w+)?\n?(.*?)\n?```', re.DOTALL), r'\1'), # Code blocks
37
+ (re.compile(r'`([^`]+)`'), r'"\1"'), # Inline code
38
+ ],
39
+
40
+ # Lists: - item → • item, 1. item → 1. item
41
+ 'lists': [
42
+ (re.compile(r'^[\s]*[-*+]\s+(.+)$', re.MULTILINE), r'• \1'), # Bullet lists
43
+ # Numbered lists keep numbers
44
+ ],
45
+
46
+ # Links: [text](url) → text (url)
47
+ 'links': [
48
+ (re.compile(r'\[([^\]]+)\]\(([^)]+)\)'), r'\1 (\2)'),
49
+ ],
50
+
51
+ # Images: ![alt](src) → [Image: alt]
52
+ 'images': [
53
+ (re.compile(r'!\[([^\]]*)\]\(([^)]+)\)'), r'[Image: \1]'),
54
+ ],
55
+
56
+ # Blockquotes: > quote → "quote"
57
+ 'blockquotes': [
58
+ (re.compile(r'^>\s+(.+)$', re.MULTILINE), r'"\1"'),
59
+ ],
60
+
61
+ # Horizontal rules: --- → ----------
62
+ 'horizontal_rules': [
63
+ (re.compile(r'^[-*_]{3,}\s*$', re.MULTILINE), '-' * 50),
64
+ ],
65
+
66
+ # Tables: | Header | → Header (tab-separated)
67
+ 'tables': self._convert_table,
68
+ }
69
+
70
+ def _convert_table(self, text: str) -> str:
71
+ """Convert Markdown tables to plain text"""
72
+ lines = text.split('\n')
73
+ if not lines or '|' not in lines[0]:
74
+ return text
75
+
76
+ # Find table rows
77
+ table_rows = []
78
+ for line in lines:
79
+ if '|' in line and not re.match(r'^\|?[-:|]+\|?$', line):
80
+ # Extract cells, remove leading/trailing |
81
+ cells = [cell.strip() for cell in line.split('|') if cell.strip()]
82
+ table_rows.append(cells)
83
+
84
+ if not table_rows:
85
+ return text
86
+
87
+ # Convert to plain text (tab-separated)
88
+ plain_rows = []
89
+ for row in table_rows:
90
+ plain_rows.append('\t'.join(row))
91
+
92
+ return '\n'.join(plain_rows)
93
+
94
+ def to_plain_text(self, markdown_text: str) -> str:
95
+ """
96
+ Convert Markdown to user-friendly plain text
97
+ """
98
+ if not markdown_text:
99
+ return ''
100
+
101
+ text = markdown_text
102
+
103
+ # Apply conversions in order
104
+ conversion_order = [
105
+ 'code', # Code first (preserve content)
106
+ 'links', # Links before bold/italic
107
+ 'images', # Images
108
+ 'bold_italic', # Bold/italic
109
+ 'header', # Headers
110
+ 'lists', # Lists
111
+ 'blockquotes', # Blockquotes
112
+ 'horizontal_rules', # Horizontal rules
113
+ ]
114
+
115
+ for pattern_type in conversion_order:
116
+ if pattern_type == 'tables':
117
+ # Tables need special handling
118
+ text = self._convert_table(text)
119
+ else:
120
+ patterns = self.patterns.get(pattern_type, [])
121
+ for pattern, replacement in patterns:
122
+ text = pattern.sub(replacement, text)
123
+
124
+ # Clean up extra whitespace
125
+ text = re.sub(r'\n{3,}', '\n\n', text) # Max 2 blank lines
126
+ text = text.strip()
127
+
128
+ return text
129
+
130
+ def to_rich_text(self, markdown_text: str) -> str:
131
+ """
132
+ Convert Markdown to rich text (preserves some formatting)
133
+ Returns text with minimal markup
134
+ """
135
+ if not markdown_text:
136
+ return ''
137
+
138
+ text = markdown_text
139
+
140
+ # Keep only essential formatting
141
+ # Headers: Add underline for H1
142
+ text = re.sub(r'^#\s+(.+)$', r'\1\n' + '=' * 50, text, flags=re.MULTILINE)
143
+
144
+ # Remove other header markers
145
+ for i in range(2, 7):
146
+ text = re.sub(r'^' + '#' * i + r'\s+(.+)$', r'\1', text, flags=re.MULTILINE)
147
+
148
+ # Convert bold/italic to uppercase for emphasis
149
+ text = re.sub(r'\*\*(.+?)\*\*', r'\1', text)
150
+ text = re.sub(r'\*(.+?)\*', r'\1', text)
151
+
152
+ # Convert code blocks with indentation
153
+ def indent_code(match):
154
+ code = match.group(1)
155
+ lines = code.split('\n')
156
+ indented = [' ' + line for line in lines]
157
+ return '\n'.join(indented)
158
+
159
+ text = re.sub(r'```(?:\w+)?\n?(.*?)\n?```', indent_code, text, flags=re.DOTALL)
160
+
161
+ # Inline code with quotes
162
+ text = re.sub(r'`([^`]+)`', r'"\1"', text)
163
+
164
+ # Bullet lists with • (keep)
165
+ text = re.sub(r'^[\s]*[-*+]\s+(.+)$', r'• \1', text, flags=re.MULTILINE)
166
+
167
+ # Remove link markup, keep text
168
+ text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
169
+
170
+ # Blockquotes with >
171
+ text = re.sub(r'^>\s+(.+)$', r'"\1"', text, flags=re.MULTILINE)
172
+
173
+ # Clean up
174
+ text = re.sub(r'\n{3,}', '\n\n', text)
175
+ text = text.strip()
176
+
177
+ return text
178
+
179
+ def get_formatting_summary(self, markdown_text: str) -> dict:
180
+ """
181
+ Analyze Markdown content and return formatting summary
182
+ """
183
+ if not markdown_text:
184
+ return {}
185
+
186
+ patterns = {
187
+ 'headers': re.compile(r'^#{1,6}\s', re.MULTILINE),
188
+ 'bold': re.compile(r'\*\*.+?\*\*'),
189
+ 'italic': re.compile(r'\*.+?\*'),
190
+ 'code_blocks': re.compile(r'```'),
191
+ 'inline_code': re.compile(r'`[^`]+`'),
192
+ 'lists': re.compile(r'^[\s]*[-*+]\s', re.MULTILINE),
193
+ 'numbered_lists': re.compile(r'^[\s]*\d+[.)]\s', re.MULTILINE),
194
+ 'links': re.compile(r'\[.+?\]\(.+?\)'),
195
+ 'images': re.compile(r'!\[.+?\]\(.+?\)'),
196
+ 'blockquotes': re.compile(r'^>\s', re.MULTILINE),
197
+ 'tables': re.compile(r'^\|.+\|$', re.MULTILINE),
198
+ }
199
+
200
+ summary = {}
201
+ for name, pattern in patterns.items():
202
+ matches = pattern.findall(markdown_text)
203
+ summary[name] = len(matches)
204
+
205
+ # Calculate formatting percentage
206
+ total_chars = len(markdown_text)
207
+ formatting_chars = 0
208
+
209
+ # Estimate formatting characters (markup)
210
+ formatting_patterns = [
211
+ (r'#{1,6}\s', 2), # Headers: # + space
212
+ (r'\*\*', 2), # Bold: **
213
+ (r'\*[^*]', 1), # Italic: *
214
+ (r'```', 3), # Code blocks: ```
215
+ (r'`[^`]', 1), # Inline code: `
216
+ (r'\[.*?\]\(.*?\)', 4), # Links: []()
217
+ (r'^>\s', 2), # Blockquotes: > + space
218
+ (r'^\|', 1), # Tables: |
219
+ ]
220
+
221
+ for pattern, char_weight in formatting_patterns:
222
+ matches = re.findall(pattern, markdown_text, re.MULTILINE)
223
+ formatting_chars += len(matches) * char_weight
224
+
225
+ if total_chars > 0:
226
+ summary['formatting_percentage'] = round((formatting_chars / total_chars) * 100, 2)
227
+ else:
228
+ summary['formatting_percentage'] = 0
229
+
230
+ return summary
231
+
232
+
233
+ # Create global instance
234
+ markdown_converter = MarkdownConverter()
235
+
236
+
237
+ # Helper functions
238
+ def convert_for_copy(markdown_text: str) -> str:
239
+ """Convert Markdown to plain text suitable for copying"""
240
+ return markdown_converter.to_plain_text(markdown_text)
241
+
242
+
243
+ def convert_for_display(markdown_text: str) -> str:
244
+ """Convert Markdown to display-friendly text (keeps some formatting)"""
245
+ return markdown_converter.to_rich_text(markdown_text)
246
+
247
+
248
+ def analyze_formatting(markdown_text: str) -> dict:
249
+ """Analyze Markdown formatting in text"""
250
+ return markdown_converter.get_formatting_summary(markdown_text)
251
+
252
+
253
+ # Test function
254
+ def test_converter():
255
+ """Test the Markdown converter"""
256
+
257
+ test_markdown = """# Project Report
258
+
259
+ ## Executive Summary
260
+ This **important** report contains *critical* data.
261
+
262
+ ### Key Findings
263
+ 1. Revenue increased by 25%
264
+ 2. User engagement improved
265
+ 3. Customer satisfaction is high
266
+
267
+ ## Technical Details
268
+ Use `print("hello")` in your code:
269
+
270
+ ```python
271
+ def calculate():
272
+ return 42 * 3.14
273
+ ```
274
+
275
+ Visit [our website](https://example.com) for more.
276
+
277
+ > Note: All data is confidential.
278
+ """
279
+
280
+ print("🧪 Testing Markdown to Plain Text Converter")
281
+ print("=" * 60)
282
+
283
+ print("\n📋 Original Markdown:")
284
+ print(test_markdown)
285
+
286
+ print("\n📝 Plain Text (for copy/download):")
287
+ plain = convert_for_copy(test_markdown)
288
+ print(plain)
289
+
290
+ print("\n🎨 Rich Text (for display):")
291
+ rich = convert_for_display(test_markdown)
292
+ print(rich)
293
+
294
+ print("\n📊 Formatting Analysis:")
295
+ analysis = analyze_formatting(test_markdown)
296
+ for key, value in analysis.items():
297
+ print(f" {key}: {value}")
298
+
299
+ print("\n" + "=" * 60)
300
+ print("✅ Converter test completed!")
301
+
302
+
303
+ if __name__ == "__main__":
304
+ test_converter()
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.104.1
2
+ uvicorn[standard]==0.24.0
3
+ pydantic==2.5.0
4
+ python-multipart==0.0.6
5
+ python-docx==1.1.2
6
+ markdown==3.5.2
7
+ # weasyprint==61.0 # Removed for HF Spaces compatibility
8
+ httpx>=0.25.0
9
+
10
+ # Testing dependencies (optional, can be removed for production)
11
+ # hypothesis>=6.0.0
12
+ # pytest>=7.0.0
13
+ # pytest-asyncio>=0.21.0