Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from pydantic import BaseModel
|
|
|
|
| 4 |
import difflib
|
| 5 |
import spacy
|
| 6 |
import re
|
|
@@ -9,7 +10,7 @@ import nltk
|
|
| 9 |
from collections import Counter
|
| 10 |
import uvicorn
|
| 11 |
import os
|
| 12 |
-
import
|
| 13 |
|
| 14 |
# Download NLTK resources
|
| 15 |
try:
|
|
@@ -30,34 +31,14 @@ app.add_middleware(
|
|
| 30 |
allow_headers=["*"], # Allows all headers
|
| 31 |
)
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
token = os.getenv("HF_API_TOKEN")
|
| 36 |
-
if not token:
|
| 37 |
-
raise HTTPException(status_code=500, detail="Hugging Face API token not configured")
|
| 38 |
-
return token
|
| 39 |
-
|
| 40 |
-
# Function to call Hugging Face Inference API
|
| 41 |
-
def get_humanized_text(text, token):
|
| 42 |
-
API_URL = "https://api-inference.huggingface.co/models/danibor/flan-t5-base-humanizer"
|
| 43 |
-
headers = {"Authorization": f"Bearer {token}"}
|
| 44 |
-
|
| 45 |
-
try:
|
| 46 |
-
response = requests.post(API_URL, headers=headers, json={"inputs": text})
|
| 47 |
-
|
| 48 |
-
# Print more detailed error info
|
| 49 |
-
if response.status_code != 200:
|
| 50 |
-
print(f"Hugging Face API error: {response.status_code}")
|
| 51 |
-
print(f"Response content: {response.text}")
|
| 52 |
-
|
| 53 |
-
response.raise_for_status()
|
| 54 |
-
return response.json()[0]["generated_text"]
|
| 55 |
-
except Exception as e:
|
| 56 |
-
print(f"Error calling Hugging Face API: {e}")
|
| 57 |
-
return f"Error processing text with Hugging Face API: {str(e)}"
|
| 58 |
|
| 59 |
# Load NLP models
|
| 60 |
try:
|
|
|
|
|
|
|
|
|
|
| 61 |
# Load spaCy model
|
| 62 |
nlp = spacy.load("en_core_web_sm")
|
| 63 |
|
|
@@ -66,11 +47,57 @@ try:
|
|
| 66 |
|
| 67 |
print("NLP models loaded successfully!")
|
| 68 |
except Exception as e:
|
| 69 |
-
print(f"Error loading models: {e}")
|
| 70 |
# Create fallback functions if models fail to load
|
| 71 |
def mock_function(text):
|
| 72 |
return "Model could not be loaded. This is a fallback response."
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
# Define request models
|
| 75 |
class TextRequest(BaseModel):
|
| 76 |
text: str
|
|
@@ -93,12 +120,23 @@ class AnalyzeResponse(BaseModel):
|
|
| 93 |
complexity: dict
|
| 94 |
|
| 95 |
@app.post("/humanize", response_model=HumanizeResponse)
|
| 96 |
-
async def humanize_text(request: TextRequest
|
| 97 |
input_text = request.text
|
| 98 |
|
| 99 |
try:
|
| 100 |
-
#
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
# Get the differences
|
| 104 |
diff = get_diff(input_text, humanized_text)
|
|
@@ -115,6 +153,7 @@ async def humanize_text(request: TextRequest, hf_token: str = Depends(get_hf_api
|
|
| 115 |
'nlp_analysis': nlp_analysis
|
| 116 |
}
|
| 117 |
except Exception as e:
|
|
|
|
| 118 |
raise HTTPException(status_code=500, detail=f"Error processing text: {str(e)}")
|
| 119 |
|
| 120 |
def get_diff(text1, text2):
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from pydantic import BaseModel
|
| 4 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, pipeline
|
| 5 |
import difflib
|
| 6 |
import spacy
|
| 7 |
import re
|
|
|
|
| 10 |
from collections import Counter
|
| 11 |
import uvicorn
|
| 12 |
import os
|
| 13 |
+
import torch
|
| 14 |
|
| 15 |
# Download NLTK resources
|
| 16 |
try:
|
|
|
|
| 31 |
allow_headers=["*"], # Allows all headers
|
| 32 |
)
|
| 33 |
|
| 34 |
+
# Global variable for the pipeline
|
| 35 |
+
humanize_pipe = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
# Load NLP models
|
| 38 |
try:
|
| 39 |
+
# Initialize with a flag to ensure loading only happens once
|
| 40 |
+
model_loaded = False
|
| 41 |
+
|
| 42 |
# Load spaCy model
|
| 43 |
nlp = spacy.load("en_core_web_sm")
|
| 44 |
|
|
|
|
| 47 |
|
| 48 |
print("NLP models loaded successfully!")
|
| 49 |
except Exception as e:
|
| 50 |
+
print(f"Error loading NLP models: {e}")
|
| 51 |
# Create fallback functions if models fail to load
|
| 52 |
def mock_function(text):
|
| 53 |
return "Model could not be loaded. This is a fallback response."
|
| 54 |
|
| 55 |
+
def get_humanize_pipeline():
|
| 56 |
+
"""
|
| 57 |
+
Lazy-load the humanization pipeline on first use.
|
| 58 |
+
Ensures it runs on CPU with limited memory settings.
|
| 59 |
+
"""
|
| 60 |
+
global humanize_pipe
|
| 61 |
+
if humanize_pipe is None:
|
| 62 |
+
try:
|
| 63 |
+
print("Loading the humanizer model on CPU...")
|
| 64 |
+
|
| 65 |
+
# Force CPU usage
|
| 66 |
+
device = torch.device("cpu")
|
| 67 |
+
|
| 68 |
+
# Set low memory footprint
|
| 69 |
+
model_kwargs = {
|
| 70 |
+
"low_cpu_mem_usage": True,
|
| 71 |
+
"device_map": "cpu"
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
# Load model with specific settings for resource-constrained environments
|
| 75 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(
|
| 76 |
+
"danibor/flan-t5-base-humanizer",
|
| 77 |
+
**model_kwargs,
|
| 78 |
+
torch_dtype=torch.float32 # Use float32 instead of float16 for CPU
|
| 79 |
+
)
|
| 80 |
+
tokenizer = AutoTokenizer.from_pretrained("danibor/flan-t5-base-humanizer")
|
| 81 |
+
|
| 82 |
+
# Create pipeline with optimized settings
|
| 83 |
+
humanize_pipe = pipeline(
|
| 84 |
+
"text2text-generation",
|
| 85 |
+
model=model,
|
| 86 |
+
tokenizer=tokenizer,
|
| 87 |
+
device=device, # Explicitly specify CPU
|
| 88 |
+
framework="pt"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
print("Humanizer model loaded successfully!")
|
| 92 |
+
except Exception as e:
|
| 93 |
+
print(f"Error loading humanizer model: {e}")
|
| 94 |
+
# Return a simple function that just returns the input as fallback
|
| 95 |
+
def fallback_humanize(text, **kwargs):
|
| 96 |
+
return [{"generated_text": f"FALLBACK: {text} (Model loading failed: {str(e)})"}]
|
| 97 |
+
humanize_pipe = fallback_humanize
|
| 98 |
+
|
| 99 |
+
return humanize_pipe
|
| 100 |
+
|
| 101 |
# Define request models
|
| 102 |
class TextRequest(BaseModel):
|
| 103 |
text: str
|
|
|
|
| 120 |
complexity: dict
|
| 121 |
|
| 122 |
@app.post("/humanize", response_model=HumanizeResponse)
|
| 123 |
+
async def humanize_text(request: TextRequest):
|
| 124 |
input_text = request.text
|
| 125 |
|
| 126 |
try:
|
| 127 |
+
# Get or initialize the pipeline
|
| 128 |
+
pipeline = get_humanize_pipeline()
|
| 129 |
+
|
| 130 |
+
# Generate humanized text with memory-conscious settings
|
| 131 |
+
result = pipeline(
|
| 132 |
+
input_text,
|
| 133 |
+
max_length=min(500, len(input_text) * 2), # Limit max length
|
| 134 |
+
do_sample=True,
|
| 135 |
+
num_return_sequences=1,
|
| 136 |
+
batch_size=1 # Small batch size for memory constraints
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
humanized_text = result[0]['generated_text']
|
| 140 |
|
| 141 |
# Get the differences
|
| 142 |
diff = get_diff(input_text, humanized_text)
|
|
|
|
| 153 |
'nlp_analysis': nlp_analysis
|
| 154 |
}
|
| 155 |
except Exception as e:
|
| 156 |
+
print(f"Error in humanize endpoint: {str(e)}")
|
| 157 |
raise HTTPException(status_code=500, detail=f"Error processing text: {str(e)}")
|
| 158 |
|
| 159 |
def get_diff(text1, text2):
|