sonyps1928
commited on
Commit
·
6ad91fc
1
Parent(s):
7fe97c0
update app3333
Browse files
app.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
from flask import Flask, request, jsonify
|
2 |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
3 |
import torch
|
4 |
import logging
|
@@ -50,184 +50,30 @@ def generate_text(prompt, max_length=100, temperature=0.7, top_p=0.9, top_k=50):
|
|
50 |
return f"Error: {str(e)}"
|
51 |
|
52 |
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
textarea { width: 100%; height: 100px; font-family: monospace; }
|
75 |
-
button {
|
76 |
-
background: #007bff;
|
77 |
-
color: white;
|
78 |
-
border: none;
|
79 |
-
padding: 10px 20px;
|
80 |
-
cursor: pointer;
|
81 |
-
border-radius: 5px;
|
82 |
-
}
|
83 |
-
button:hover { background: #0056b3; }
|
84 |
-
button:disabled { background: #ccc; cursor: not-allowed; }
|
85 |
-
.output {
|
86 |
-
background: #f8f9fa;
|
87 |
-
padding: 15px;
|
88 |
-
border-radius: 5px;
|
89 |
-
min-height: 100px;
|
90 |
-
border: 1px solid #e9ecef;
|
91 |
-
font-family: monospace;
|
92 |
-
white-space: pre-wrap;
|
93 |
-
}
|
94 |
-
.controls { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin: 15px 0; }
|
95 |
-
label { font-weight: bold; display: block; margin-bottom: 5px; }
|
96 |
-
.slider-container { margin: 10px 0; }
|
97 |
-
input[type="range"] { width: 100%; }
|
98 |
-
.value-display { font-weight: normal; color: #666; }
|
99 |
-
h1 { color: #333; text-align: center; }
|
100 |
-
.description { text-align: center; color: #666; margin-bottom: 30px; }
|
101 |
-
.examples { margin: 20px 0; }
|
102 |
-
.example-btn {
|
103 |
-
background: #28a745;
|
104 |
-
margin: 5px;
|
105 |
-
padding: 5px 10px;
|
106 |
-
font-size: 12px;
|
107 |
-
}
|
108 |
-
.example-btn:hover { background: #218838; }
|
109 |
-
</style>
|
110 |
-
</head>
|
111 |
-
<body>
|
112 |
-
<div class="container">
|
113 |
-
<h1>🤖 GPT-2 Text Generator</h1>
|
114 |
-
<p class="description">Enter a prompt and generate text using GPT-2. Powered by Hugging Face Transformers!</p>
|
115 |
-
|
116 |
-
<div>
|
117 |
-
<label for="prompt">Prompt:</label>
|
118 |
-
<textarea id="prompt" placeholder="Enter your text prompt here...">Once upon a time in a distant galaxy,</textarea>
|
119 |
-
</div>
|
120 |
-
|
121 |
-
<div class="examples">
|
122 |
-
<label>Quick Examples:</label><br>
|
123 |
-
<button class="example-btn" onclick="setPrompt('Once upon a time in a distant galaxy,')">Sci-Fi Story</button>
|
124 |
-
<button class="example-btn" onclick="setPrompt('The future of artificial intelligence is')">AI Future</button>
|
125 |
-
<button class="example-btn" onclick="setPrompt('In the heart of the ancient forest,')">Fantasy</button>
|
126 |
-
<button class="example-btn" onclick="setPrompt('The detective walked into the room and noticed')">Mystery</button>
|
127 |
-
</div>
|
128 |
-
|
129 |
-
<div class="controls">
|
130 |
-
<div class="slider-container">
|
131 |
-
<label for="maxLength">Max Length: <span id="maxLengthValue" class="value-display">100</span></label>
|
132 |
-
<input type="range" id="maxLength" min="10" max="200" value="100" step="10">
|
133 |
-
</div>
|
134 |
-
<div class="slider-container">
|
135 |
-
<label for="temperature">Temperature: <span id="temperatureValue" class="value-display">0.7</span></label>
|
136 |
-
<input type="range" id="temperature" min="0.1" max="2.0" value="0.7" step="0.1">
|
137 |
-
</div>
|
138 |
-
<div class="slider-container">
|
139 |
-
<label for="topP">Top-p: <span id="topPValue" class="value-display">0.9</span></label>
|
140 |
-
<input type="range" id="topP" min="0.1" max="1.0" value="0.9" step="0.1">
|
141 |
-
</div>
|
142 |
-
<div class="slider-container">
|
143 |
-
<label for="topK">Top-k: <span id="topKValue" class="value-display">50</span></label>
|
144 |
-
<input type="range" id="topK" min="1" max="100" value="50" step="1">
|
145 |
-
</div>
|
146 |
-
</div>
|
147 |
-
|
148 |
-
<div style="text-align: center;">
|
149 |
-
<button onclick="generateText()" id="generateBtn">🚀 Generate Text</button>
|
150 |
-
</div>
|
151 |
-
</div>
|
152 |
-
|
153 |
-
<div class="container">
|
154 |
-
<label>Generated Text:</label>
|
155 |
-
<div id="output" class="output">Generated text will appear here...</div>
|
156 |
-
</div>
|
157 |
-
|
158 |
-
<script>
|
159 |
-
// Update slider value displays
|
160 |
-
document.getElementById('maxLength').oninput = function() {
|
161 |
-
document.getElementById('maxLengthValue').textContent = this.value;
|
162 |
-
}
|
163 |
-
document.getElementById('temperature').oninput = function() {
|
164 |
-
document.getElementById('temperatureValue').textContent = this.value;
|
165 |
-
}
|
166 |
-
document.getElementById('topP').oninput = function() {
|
167 |
-
document.getElementById('topPValue').textContent = this.value;
|
168 |
-
}
|
169 |
-
document.getElementById('topK').oninput = function() {
|
170 |
-
document.getElementById('topKValue').textContent = this.value;
|
171 |
-
}
|
172 |
-
|
173 |
-
function setPrompt(text) {
|
174 |
-
document.getElementById('prompt').value = text;
|
175 |
-
}
|
176 |
-
|
177 |
-
async function generateText() {
|
178 |
-
const btn = document.getElementById('generateBtn');
|
179 |
-
const output = document.getElementById('output');
|
180 |
-
|
181 |
-
btn.disabled = true;
|
182 |
-
btn.textContent = '⏳ Generating...';
|
183 |
-
output.textContent = 'Generating text, please wait...';
|
184 |
-
|
185 |
-
const data = {
|
186 |
-
prompt: document.getElementById('prompt').value,
|
187 |
-
max_length: parseInt(document.getElementById('maxLength').value),
|
188 |
-
temperature: parseFloat(document.getElementById('temperature').value),
|
189 |
-
top_p: parseFloat(document.getElementById('topP').value),
|
190 |
-
top_k: parseInt(document.getElementById('topK').value)
|
191 |
-
};
|
192 |
-
|
193 |
-
try {
|
194 |
-
const response = await fetch('/generate', {
|
195 |
-
method: 'POST',
|
196 |
-
headers: {'Content-Type': 'application/json'},
|
197 |
-
body: JSON.stringify(data)
|
198 |
-
});
|
199 |
-
|
200 |
-
const result = await response.json();
|
201 |
-
|
202 |
-
if (result.error) {
|
203 |
-
output.textContent = '❌ Error: ' + result.error;
|
204 |
-
} else {
|
205 |
-
output.textContent = result.generated_text || 'No text generated';
|
206 |
-
}
|
207 |
-
} catch (error) {
|
208 |
-
output.textContent = '❌ Network Error: ' + error.message;
|
209 |
}
|
210 |
-
|
211 |
-
btn.disabled = false;
|
212 |
-
btn.textContent = '🚀 Generate Text';
|
213 |
}
|
214 |
-
|
215 |
-
// Allow Enter key to generate (Ctrl+Enter for textarea)
|
216 |
-
document.getElementById('prompt').addEventListener('keydown', function(e) {
|
217 |
-
if (e.ctrlKey && e.key === 'Enter') {
|
218 |
-
generateText();
|
219 |
-
}
|
220 |
-
});
|
221 |
-
</script>
|
222 |
-
</body>
|
223 |
-
</html>
|
224 |
-
'''
|
225 |
-
|
226 |
-
|
227 |
-
@app.route('/')
|
228 |
-
def home():
|
229 |
-
"""Serve the web interface"""
|
230 |
-
return render_template_string(HTML_TEMPLATE)
|
231 |
|
232 |
|
233 |
@app.route('/health')
|
@@ -236,7 +82,8 @@ def health():
|
|
236 |
return jsonify({
|
237 |
'status': 'healthy',
|
238 |
'model': model_name,
|
239 |
-
'framework': 'flask'
|
|
|
240 |
})
|
241 |
|
242 |
|
@@ -244,12 +91,16 @@ def health():
|
|
244 |
def generate():
|
245 |
"""Text generation API endpoint"""
|
246 |
try:
|
|
|
|
|
|
|
247 |
data = request.get_json()
|
248 |
|
249 |
if not data:
|
250 |
-
|
|
|
251 |
|
252 |
-
# Extract parameters
|
253 |
prompt = data.get('prompt', '')
|
254 |
max_length = data.get('max_length', 100)
|
255 |
temperature = data.get('temperature', 0.7)
|
@@ -257,28 +108,72 @@ def generate():
|
|
257 |
top_k = data.get('top_k', 50)
|
258 |
|
259 |
if not prompt:
|
260 |
-
|
|
|
261 |
|
262 |
-
# Validate parameters
|
263 |
max_length = max(10, min(200, int(max_length)))
|
264 |
temperature = max(0.1, min(2.0, float(temperature)))
|
265 |
top_p = max(0.1, min(1.0, float(top_p)))
|
266 |
top_k = max(1, min(100, int(top_k)))
|
267 |
|
|
|
|
|
268 |
# Generate text
|
269 |
-
logger.info(f"Generating text for prompt: {prompt[:50]}...")
|
270 |
generated_text = generate_text(prompt, max_length, temperature, top_p, top_k)
|
271 |
|
272 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
273 |
|
|
|
|
|
|
|
274 |
except Exception as e:
|
275 |
logger.error(f"Error in /generate: {str(e)}")
|
276 |
-
return jsonify({'error': str(e)}), 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
277 |
|
278 |
|
279 |
@app.errorhandler(404)
|
280 |
def not_found(error):
|
281 |
-
return jsonify({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
282 |
|
283 |
|
284 |
@app.errorhandler(500)
|
@@ -289,4 +184,12 @@ def internal_error(error):
|
|
289 |
if __name__ == "__main__":
|
290 |
# For Hugging Face Spaces
|
291 |
port = int(os.environ.get("PORT", 7860))
|
292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
3 |
import torch
|
4 |
import logging
|
|
|
50 |
return f"Error: {str(e)}"
|
51 |
|
52 |
|
53 |
+
@app.route('/')
|
54 |
+
def root():
|
55 |
+
"""API information endpoint"""
|
56 |
+
return jsonify({
|
57 |
+
"message": "GPT-2 Text Generation API",
|
58 |
+
"model": model_name,
|
59 |
+
"endpoints": {
|
60 |
+
"/": "API information",
|
61 |
+
"/health": "Health check",
|
62 |
+
"/generate": "POST - Generate text"
|
63 |
+
},
|
64 |
+
"example_request": {
|
65 |
+
"url": "/generate",
|
66 |
+
"method": "POST",
|
67 |
+
"headers": {"Content-Type": "application/json"},
|
68 |
+
"body": {
|
69 |
+
"prompt": "Once upon a time",
|
70 |
+
"max_length": 100,
|
71 |
+
"temperature": 0.7,
|
72 |
+
"top_p": 0.9,
|
73 |
+
"top_k": 50
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
}
|
|
|
|
|
|
|
75 |
}
|
76 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
|
78 |
|
79 |
@app.route('/health')
|
|
|
82 |
return jsonify({
|
83 |
'status': 'healthy',
|
84 |
'model': model_name,
|
85 |
+
'framework': 'flask',
|
86 |
+
'endpoints_available': ['/health', '/generate', '/']
|
87 |
})
|
88 |
|
89 |
|
|
|
91 |
def generate():
|
92 |
"""Text generation API endpoint"""
|
93 |
try:
|
94 |
+
# Log the request
|
95 |
+
logger.info(f"Received generate request from {request.remote_addr}")
|
96 |
+
|
97 |
data = request.get_json()
|
98 |
|
99 |
if not data:
|
100 |
+
logger.warning("No JSON data provided")
|
101 |
+
return jsonify({'error': 'No JSON data provided', 'received_content_type': request.content_type}), 400
|
102 |
|
103 |
+
# Extract parameters with defaults
|
104 |
prompt = data.get('prompt', '')
|
105 |
max_length = data.get('max_length', 100)
|
106 |
temperature = data.get('temperature', 0.7)
|
|
|
108 |
top_k = data.get('top_k', 50)
|
109 |
|
110 |
if not prompt:
|
111 |
+
logger.warning("Empty prompt provided")
|
112 |
+
return jsonify({'error': 'Prompt is required and cannot be empty'}), 400
|
113 |
|
114 |
+
# Validate and clamp parameters
|
115 |
max_length = max(10, min(200, int(max_length)))
|
116 |
temperature = max(0.1, min(2.0, float(temperature)))
|
117 |
top_p = max(0.1, min(1.0, float(top_p)))
|
118 |
top_k = max(1, min(100, int(top_k)))
|
119 |
|
120 |
+
logger.info(f"Generating text for prompt: '{prompt[:50]}...' with params: max_length={max_length}, temperature={temperature}")
|
121 |
+
|
122 |
# Generate text
|
|
|
123 |
generated_text = generate_text(prompt, max_length, temperature, top_p, top_k)
|
124 |
|
125 |
+
result = {
|
126 |
+
'generated_text': generated_text,
|
127 |
+
'prompt': prompt,
|
128 |
+
'parameters': {
|
129 |
+
'max_length': max_length,
|
130 |
+
'temperature': temperature,
|
131 |
+
'top_p': top_p,
|
132 |
+
'top_k': top_k
|
133 |
+
}
|
134 |
+
}
|
135 |
+
|
136 |
+
logger.info("Text generation successful")
|
137 |
+
return jsonify(result)
|
138 |
|
139 |
+
except ValueError as e:
|
140 |
+
logger.error(f"Parameter validation error: {str(e)}")
|
141 |
+
return jsonify({'error': f'Invalid parameter: {str(e)}'}), 400
|
142 |
except Exception as e:
|
143 |
logger.error(f"Error in /generate: {str(e)}")
|
144 |
+
return jsonify({'error': f'Internal server error: {str(e)}'}), 500
|
145 |
+
|
146 |
+
|
147 |
+
@app.route('/generate', methods=['GET'])
|
148 |
+
def generate_get():
|
149 |
+
"""GET endpoint for /generate with usage information"""
|
150 |
+
return jsonify({
|
151 |
+
'error': 'Method not allowed',
|
152 |
+
'message': 'This endpoint only accepts POST requests',
|
153 |
+
'usage': 'Send a POST request with JSON body containing "prompt" field',
|
154 |
+
'example': {
|
155 |
+
'method': 'POST',
|
156 |
+
'headers': {'Content-Type': 'application/json'},
|
157 |
+
'body': {'prompt': 'Once upon a time', 'max_length': 100}
|
158 |
+
}
|
159 |
+
}), 405
|
160 |
|
161 |
|
162 |
@app.errorhandler(404)
|
163 |
def not_found(error):
|
164 |
+
return jsonify({
|
165 |
+
'error': 'Not found',
|
166 |
+
'available_endpoints': ['/', '/health', '/generate'],
|
167 |
+
'message': 'Check the available endpoints above'
|
168 |
+
}), 404
|
169 |
+
|
170 |
+
|
171 |
+
@app.errorhandler(405)
|
172 |
+
def method_not_allowed(error):
|
173 |
+
return jsonify({
|
174 |
+
'error': 'Method not allowed',
|
175 |
+
'message': 'Check the allowed methods for this endpoint'
|
176 |
+
}), 405
|
177 |
|
178 |
|
179 |
@app.errorhandler(500)
|
|
|
184 |
if __name__ == "__main__":
|
185 |
# For Hugging Face Spaces
|
186 |
port = int(os.environ.get("PORT", 7860))
|
187 |
+
host = "0.0.0.0"
|
188 |
+
|
189 |
+
logger.info(f"Starting GPT-2 API server on {host}:{port}")
|
190 |
+
logger.info("Available endpoints:")
|
191 |
+
logger.info(" GET / - API information")
|
192 |
+
logger.info(" GET /health - Health check")
|
193 |
+
logger.info(" POST /generate - Text generation")
|
194 |
+
|
195 |
+
app.run(host=host, port=port, debug=False)
|