Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234562 unmodified lines910111213141514 unmodified lines303132333435363738394041424344454647484950515253545556575859606162632 unmodified lines666768697071727374757616 unmodified lines9394959697989910010110210310410 unmodified lines115116117118119120from fastapi import FastAPI, HTTPException, Dependsfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport difflibimport spacyimport re2 unmodified linesfrom collections import Counterimport uvicornimport osimport requests# Download NLTK resourcestry:14 unmodified linesallow_headers=["*"], # Allows all headers)# Function to get API tokendef get_hf_api_token():token = os.getenv("HF_API_TOKEN")if not token:raise HTTPException(status_code=500, detail="Hugging Face API token not configured")return token# Function to call Hugging Face Inference APIdef get_humanized_text(text, token):API_URL = "https://api-inference.huggingface.co/models/danibor/flan-t5-base-humanizer"headers = {"Authorization": f"Bearer {token}"}try:response = requests.post(API_URL, headers=headers, json={"inputs": text})# Print more detailed error infoif response.status_code != 200:print(f"Hugging Face API error: {response.status_code}")print(f"Response content: {response.text}")response.raise_for_status()return response.json()[0]["generated_text"]except Exception as e:print(f"Error calling Hugging Face API: {e}")return f"Error processing text with Hugging Face API: {str(e)}"# Load NLP modelstry:# Load spaCy modelnlp = spacy.load("en_core_web_sm")2 unmodified linesprint("NLP models loaded successfully!")except Exception as e:print(f"Error loading models: {e}")# Create fallback functions if models fail to loaddef mock_function(text):return "Model could not be loaded. This is a fallback response."# Define request modelsclass TextRequest(BaseModel):text: str16 unmodified linescomplexity: dict@app.post("/humanize", response_model=HumanizeResponse)async def humanize_text(request: TextRequest, hf_token: str = Depends(get_hf_api_token)):input_text = request.texttry:# Generate humanized text using Hugging Face APIhumanized_text = get_humanized_text(input_text, hf_token)# Get the differencesdiff = get_diff(input_text, humanized_text)10 unmodified lines'nlp_analysis': nlp_analysis}except Exception as e:raise HTTPException(status_code=500, detail=f"Error processing text: {str(e)}")def get_diff(text1, text2):12345672 unmodified lines1011121314151614 unmodified lines31323334353637383940414243442 unmodified lines474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210316 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114210 unmodified lines153154155156157158159from fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom transformers import AutoModelForSeq2SeqLM, AutoTokenizer, pipelineimport difflibimport spacyimport re2 unmodified linesfrom collections import Counterimport uvicornimport osimport torch# Download NLTK resourcestry:14 unmodified linesallow_headers=["*"], # Allows all headers)# Global variable for the pipelinehumanize_pipe = None# Load NLP modelstry:# Initialize with a flag to ensure loading only happens oncemodel_loaded = False# Load spaCy modelnlp = spacy.load("en_core_web_sm")2 unmodified linesprint("NLP models loaded successfully!")except Exception as e:print(f"Error loading NLP models: {e}")# Create fallback functions if models fail to loaddef mock_function(text):return "Model could not be loaded. This is a fallback response."def get_humanize_pipeline():"""Lazy-load the humanization pipeline on first use.Ensures it runs on CPU with limited memory settings."""global humanize_pipeif humanize_pipe is None:try:print("Loading the humanizer model on CPU...")# Force CPU usagedevice = torch.device("cpu")# Set low memory footprintmodel_kwargs = {"low_cpu_mem_usage": True,"device_map": "cpu"}# Load model with specific settings for resource-constrained environmentsmodel = AutoModelForSeq2SeqLM.from_pretrained("danibor/flan-t5-base-humanizer",**model_kwargs,torch_dtype=torch.float32 # Use float32 instead of float16 for CPU)tokenizer = AutoTokenizer.from_pretrained("danibor/flan-t5-base-humanizer")# Create pipeline with optimized settingshumanize_pipe = pipeline("text2text-generation",model=model,tokenizer=tokenizer,device=device, # Explicitly specify CPUframework="pt")print("Humanizer model loaded successfully!")except Exception as e:print(f"Error loading humanizer model: {e}")# Return a simple function that just returns the input as fallbackdef fallback_humanize(text, **kwargs):return [{"generated_text": f"FALLBACK: {text} (Model loading failed: {str(e)})"}]humanize_pipe = fallback_humanizereturn humanize_pipe# Define request modelsclass TextRequest(BaseModel):text: str16 unmodified linescomplexity: dict@app.post("/humanize", response_model=HumanizeResponse)async def humanize_text(request: TextRequest):input_text = request.texttry:# Get or initialize the pipelinepipeline = get_humanize_pipeline()# Generate humanized text with memory-conscious settingsresult = pipeline(input_text,max_length=min(500, len(input_text) * 2), # Limit max lengthdo_sample=True,num_return_sequences=1,batch_size=1 # Small batch size for memory constraints)humanized_text = result[0]['generated_text']# Get the differencesdiff = get_diff(input_text, humanized_text)10 unmodified lines'nlp_analysis': nlp_analysis}except Exception as e:print(f"Error in humanize endpoint: {str(e)}")raise HTTPException(status_code=500, detail=f"Error processing text: {str(e)}")def get_diff(text1, text2):
app.py+70-31