devilseye2004 commited on
Commit
8956c4d
·
verified ·
1 Parent(s): 3cc5ce0

commit changes to main.

Browse files
Files changed (3) hide show
  1. Dockerfile +31 -0
  2. app.py +187 -0
  3. requirements.txt +6 -0
Dockerfile ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Production Dockerfile for Hugging Face Spaces
2
+ # CPU-optimized T5 Paraphrasing API
3
+
4
+ FROM python:3.10-slim
5
+
6
+ # Set working directory
7
+ WORKDIR /app
8
+
9
+ # Install system dependencies (minimal)
10
+ RUN apt-get update && apt-get install -y --no-install-recommends \
11
+ build-essential \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
+ # Copy requirements first for better caching
15
+ COPY requirements.txt .
16
+
17
+ # Install Python dependencies
18
+ RUN pip install --no-cache-dir -r requirements.txt
19
+
20
+ # Copy application code
21
+ COPY app.py .
22
+
23
+ # Expose port 7860 (Hugging Face Spaces default)
24
+ EXPOSE 7860
25
+
26
+ # Set environment variables
27
+ ENV PORT=7860
28
+ ENV PYTHONUNBUFFERED=1
29
+
30
+ # Run the application
31
+ CMD ["python", "app.py"]
app.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from typing import Optional
4
+ import torch
5
+ from fastapi import FastAPI, HTTPException
6
+ from pydantic import BaseModel, Field, field_validator
7
+ from transformers import T5ForConditionalGeneration, T5Tokenizer
8
+
9
+ # Configure logging
10
+ logging.basicConfig(
11
+ level=logging.INFO,
12
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
13
+ )
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # FastAPI app
17
+ app = FastAPI(
18
+ title="T5 Paraphrasing API",
19
+ description="Production-ready paraphrasing service using T5 model",
20
+ version="1.0.0"
21
+ )
22
+
23
+ # Global model and tokenizer (loaded once on startup)
24
+ model: Optional[T5ForConditionalGeneration] = None
25
+ tokenizer: Optional[T5Tokenizer] = None
26
+
27
+ # Configuration constants
28
+ MIN_WORDS = 5
29
+ MAX_INPUT_LENGTH = 512 # Protect CPU from very long inputs
30
+ MAX_OUTPUT_LENGTH = 128
31
+ NUM_BEAMS = 4
32
+ NO_REPEAT_NGRAM_SIZE = 3
33
+
34
+
35
+ class ParaphraseRequest(BaseModel):
36
+ """Input schema for paraphrasing request"""
37
+ text: str = Field(..., min_length=1, description="Text to paraphrase")
38
+
39
+ @field_validator('text')
40
+ @classmethod
41
+ def validate_text(cls, v: str) -> str:
42
+ """Validate and clean input text"""
43
+ if not v or not v.strip():
44
+ raise ValueError("Text cannot be empty")
45
+
46
+ # Clean text lightly (remove extra whitespace, preserve punctuation)
47
+ cleaned = ' '.join(v.strip().split())
48
+
49
+ # Check word count
50
+ word_count = len(cleaned.split())
51
+ if word_count < MIN_WORDS:
52
+ raise ValueError(f"Text must contain at least {MIN_WORDS} words")
53
+
54
+ # Check length
55
+ if len(cleaned) > MAX_INPUT_LENGTH:
56
+ raise ValueError(f"Text exceeds maximum length of {MAX_INPUT_LENGTH} characters")
57
+
58
+ return cleaned
59
+
60
+
61
+ class ParaphraseResponse(BaseModel):
62
+ """Output schema for paraphrasing response"""
63
+ output: str = Field(..., description="Paraphrased text")
64
+
65
+
66
+ @app.on_event("startup")
67
+ async def load_model():
68
+ """Load model and tokenizer once on startup"""
69
+ global model, tokenizer
70
+
71
+ model_name = "Vamsi/T5_Paraphrase_Paws"
72
+ logger.info(f"Loading model: {model_name}")
73
+
74
+ try:
75
+ # Load tokenizer
76
+ logger.info("Loading tokenizer...")
77
+ tokenizer = T5Tokenizer.from_pretrained(model_name)
78
+
79
+ # Load model
80
+ logger.info("Loading model...")
81
+ model = T5ForConditionalGeneration.from_pretrained(model_name)
82
+
83
+ # Set to evaluation mode
84
+ model.eval()
85
+
86
+ # Move to CPU (explicit for clarity)
87
+ device = torch.device("cpu")
88
+ model.to(device)
89
+
90
+ logger.info("Model loaded successfully on CPU")
91
+
92
+ except Exception as e:
93
+ logger.error(f"Failed to load model: {str(e)}")
94
+ raise
95
+
96
+
97
+ @app.get("/")
98
+ async def root():
99
+ """Health check endpoint"""
100
+ return {
101
+ "status": "healthy",
102
+ "model_loaded": model is not None and tokenizer is not None
103
+ }
104
+
105
+
106
+ @app.get("/health")
107
+ async def health():
108
+ """Health check endpoint"""
109
+ return {
110
+ "status": "healthy",
111
+ "model_loaded": model is not None and tokenizer is not None
112
+ }
113
+
114
+
115
+ @app.post("/humanize", response_model=ParaphraseResponse)
116
+ async def humanize(request: ParaphraseRequest) -> ParaphraseResponse:
117
+ """
118
+ Paraphrase input text using T5 model.
119
+
120
+ Args:
121
+ request: ParaphraseRequest containing text to paraphrase
122
+
123
+ Returns:
124
+ ParaphraseResponse with paraphrased text
125
+
126
+ Raises:
127
+ HTTPException: If model is not loaded or inference fails
128
+ """
129
+ if model is None or tokenizer is None:
130
+ logger.error("Model not loaded")
131
+ raise HTTPException(status_code=503, detail="Model not loaded")
132
+
133
+ input_text = request.text
134
+ logger.info(f"Received request: {len(input_text)} characters, {len(input_text.split())} words")
135
+
136
+ try:
137
+ # Prepare input with T5 prefix
138
+ input_text_prepared = f"paraphrase: {input_text}"
139
+
140
+ # Tokenize
141
+ input_ids = tokenizer.encode(
142
+ input_text_prepared,
143
+ return_tensors="pt",
144
+ max_length=MAX_INPUT_LENGTH,
145
+ truncation=True,
146
+ padding=True
147
+ )
148
+
149
+ # Inference with no_grad for efficiency
150
+ with torch.no_grad():
151
+ # Generate with beam search for accuracy
152
+ outputs = model.generate(
153
+ input_ids,
154
+ max_length=MAX_OUTPUT_LENGTH,
155
+ num_beams=NUM_BEAMS,
156
+ no_repeat_ngram_size=NO_REPEAT_NGRAM_SIZE,
157
+ early_stopping=True,
158
+ do_sample=False, # Deterministic, no randomness
159
+ temperature=None, # Not used when do_sample=False
160
+ )
161
+
162
+ # Decode output
163
+ paraphrased_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
164
+
165
+ # Clean output
166
+ paraphrased_text = paraphrased_text.strip()
167
+
168
+ # Fallback: if output is empty or too short, return original
169
+ if not paraphrased_text or len(paraphrased_text.split()) < MIN_WORDS:
170
+ logger.warning("Generated output too short, returning original text")
171
+ paraphrased_text = input_text
172
+
173
+ logger.info(f"Generated paraphrase: {len(paraphrased_text)} characters")
174
+
175
+ return ParaphraseResponse(output=paraphrased_text)
176
+
177
+ except Exception as e:
178
+ logger.error(f"Inference error: {str(e)}")
179
+ # Return original text on error (graceful degradation)
180
+ logger.warning("Returning original text due to inference error")
181
+ return ParaphraseResponse(output=input_text)
182
+
183
+
184
+ if __name__ == "__main__":
185
+ import uvicorn
186
+ port = int(os.getenv("PORT", 7860))
187
+ uvicorn.run(app, host="0.0.0.0", port=port)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi==0.104.1
2
+ uvicorn[standard]==0.24.0
3
+ torch==2.1.0
4
+ transformers==4.35.0
5
+ sentencepiece==0.1.99
6
+ pydantic==2.5.0