sonyps1928
commited on
Commit
Β·
8511f5e
1
Parent(s):
5b97012
update app6
Browse files- app.py +117 -183
- requirements.txt +4 -7
app.py
CHANGED
@@ -1,6 +1,5 @@
|
|
1 |
import gradio as gr
|
2 |
import os
|
3 |
-
import hashlib
|
4 |
import time
|
5 |
from collections import defaultdict
|
6 |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
@@ -11,20 +10,22 @@ HF_TOKEN = os.getenv("HF_TOKEN")
|
|
11 |
API_KEY = os.getenv("API_KEY")
|
12 |
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD")
|
13 |
|
14 |
-
print(
|
15 |
print(f" HF_TOKEN: {'β
Set' if HF_TOKEN else 'β Not set'}")
|
16 |
print(f" API_KEY: {'β
Set' if API_KEY else 'β Not set'}")
|
17 |
print(f" ADMIN_PASSWORD: {'β
Set' if ADMIN_PASSWORD else 'β Not set'}")
|
18 |
|
19 |
-
#
|
20 |
request_counts = defaultdict(list)
|
21 |
|
22 |
-
# Load model
|
23 |
model_name = "gpt2"
|
|
|
|
|
24 |
try:
|
25 |
if HF_TOKEN:
|
26 |
-
tokenizer = GPT2Tokenizer.from_pretrained(model_name,
|
27 |
-
model = GPT2LMHeadModel.from_pretrained(model_name,
|
28 |
print("β
Model loaded with HF token")
|
29 |
else:
|
30 |
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
@@ -32,240 +33,173 @@ try:
|
|
32 |
print("β
Model loaded without token")
|
33 |
|
34 |
tokenizer.pad_token = tokenizer.eos_token
|
35 |
-
print("β
Model
|
36 |
|
37 |
except Exception as e:
|
38 |
print(f"β Model loading failed: {e}")
|
39 |
-
raise
|
40 |
|
41 |
-
def
|
42 |
-
"""
|
43 |
if not API_KEY:
|
44 |
-
return True, "
|
45 |
-
|
46 |
-
if not provided_key:
|
47 |
-
return False, "API key required but not provided"
|
48 |
|
49 |
-
if provided_key != API_KEY:
|
50 |
-
return False, "Invalid API key"
|
51 |
|
52 |
-
#
|
53 |
now = time.time()
|
54 |
-
|
55 |
|
56 |
-
# Clean old requests
|
57 |
-
request_counts[
|
58 |
-
|
59 |
-
if now - req_time < 3600
|
60 |
]
|
61 |
|
62 |
-
|
63 |
-
|
64 |
-
return False, "Rate limit exceeded (100 requests/hour)"
|
65 |
|
66 |
-
|
67 |
-
request_counts[
|
68 |
-
return True, f"Authenticated (Requests: {len(request_counts[key_hash])}/100)"
|
69 |
|
70 |
-
def generate_text(prompt, max_length
|
71 |
-
"""Generate text with
|
72 |
|
73 |
-
#
|
74 |
-
|
75 |
-
if not
|
76 |
-
return f"π
|
77 |
|
78 |
-
# Input validation
|
79 |
-
if not prompt
|
80 |
-
return "β
|
81 |
|
82 |
if len(prompt) > 1000:
|
83 |
-
return "β
|
84 |
|
85 |
try:
|
86 |
-
print(f"π {
|
87 |
-
print(f"π Generating
|
88 |
|
89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
|
|
|
91 |
with torch.no_grad():
|
92 |
outputs = model.generate(
|
93 |
inputs,
|
94 |
-
max_length=min(
|
95 |
temperature=max(0.1, min(2.0, temperature)),
|
96 |
top_p=max(0.1, min(1.0, top_p)),
|
97 |
top_k=max(1, min(100, top_k)),
|
98 |
do_sample=True,
|
99 |
pad_token_id=tokenizer.eos_token_id,
|
100 |
-
num_return_sequences=1
|
|
|
101 |
)
|
102 |
|
103 |
-
|
104 |
-
|
|
|
105 |
|
106 |
-
print(f"β
|
107 |
-
return result
|
108 |
|
109 |
except Exception as e:
|
110 |
-
|
111 |
-
print(
|
112 |
-
return
|
113 |
|
114 |
-
# Create
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
max-width: 1200px !important;
|
121 |
-
}
|
122 |
-
.security-status {
|
123 |
-
background: linear-gradient(45deg, #f0f8ff, #e6f3ff);
|
124 |
-
padding: 15px;
|
125 |
-
border-radius: 8px;
|
126 |
-
margin: 10px 0;
|
127 |
-
}
|
128 |
-
"""
|
129 |
-
) as demo:
|
130 |
-
|
131 |
-
# Header
|
132 |
-
gr.HTML("<h1>π Secure GPT-2 Text Generator</h1>")
|
133 |
|
134 |
-
# Security
|
135 |
-
security_status = []
|
136 |
-
if HF_TOKEN:
|
137 |
-
security_status.append("π HF Token Active")
|
138 |
if API_KEY:
|
139 |
-
|
140 |
-
if ADMIN_PASSWORD:
|
141 |
-
security_status.append("π€ Admin Protection Active")
|
142 |
-
|
143 |
-
if security_status:
|
144 |
-
gr.HTML(f"""
|
145 |
-
<div class="security-status">
|
146 |
-
<strong>Active Security Features:</strong><br>
|
147 |
-
{' β’ '.join(security_status)}
|
148 |
-
</div>
|
149 |
-
""")
|
150 |
else:
|
151 |
-
gr.
|
152 |
-
<div class="security-status">
|
153 |
-
β οΈ <strong>No security features enabled</strong> - running in public mode
|
154 |
-
</div>
|
155 |
-
""")
|
156 |
|
157 |
with gr.Row():
|
158 |
-
with gr.Column(
|
159 |
-
|
160 |
-
|
161 |
-
|
|
|
162 |
lines=3
|
163 |
)
|
164 |
|
165 |
-
#
|
166 |
if API_KEY:
|
167 |
-
|
168 |
-
label="
|
169 |
type="password",
|
170 |
-
placeholder="Enter
|
171 |
)
|
172 |
-
gr.HTML("<p><em>API authentication is enabled for this Space</em></p>")
|
173 |
else:
|
174 |
-
|
175 |
-
gr.HTML("<p>π <strong>Public Access:</strong> No API key required</p>")
|
176 |
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
maximum=1.0,
|
195 |
-
value=0.9,
|
196 |
-
step=0.1,
|
197 |
-
label="π― Top-p"
|
198 |
-
)
|
199 |
-
top_k = gr.Slider(
|
200 |
-
minimum=1,
|
201 |
-
maximum=100,
|
202 |
-
value=50,
|
203 |
-
step=1,
|
204 |
-
label="π’ Top-k"
|
205 |
-
)
|
206 |
|
207 |
-
|
|
|
208 |
|
209 |
-
with gr.Column(
|
210 |
-
|
211 |
-
|
212 |
-
|
|
|
213 |
placeholder="Generated text will appear here..."
|
214 |
)
|
215 |
-
|
216 |
-
# Rate limit info
|
217 |
-
if API_KEY:
|
218 |
-
gr.HTML("<p><strong>Rate Limits:</strong> 100 requests per hour per API key</p>")
|
219 |
|
220 |
# Examples
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
["In the heart of the ancient forest,"],
|
227 |
-
["The detective walked into the room and noticed"],
|
228 |
-
["Write a short story about a robot who dreams of"],
|
229 |
-
],
|
230 |
-
inputs=prompt_input,
|
231 |
-
label="π‘ Example Prompts"
|
232 |
-
)
|
233 |
|
234 |
-
# Connect
|
235 |
generate_btn.click(
|
236 |
-
|
237 |
-
inputs=[
|
238 |
-
outputs=
|
239 |
)
|
240 |
|
241 |
-
#
|
242 |
if __name__ == "__main__":
|
243 |
-
|
244 |
-
auth_tuple = None
|
245 |
-
if ADMIN_PASSWORD:
|
246 |
-
auth_tuple = ("admin", ADMIN_PASSWORD)
|
247 |
-
print("π Admin authentication enabled")
|
248 |
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
inbrowser=False, # Don't try to open browser
|
259 |
-
prevent_thread_lock=False,
|
260 |
-
ssr_mode=False # Disable SSR to prevent i18n issues
|
261 |
-
)
|
262 |
-
print("π Secure GPT-2 Generator is running!")
|
263 |
-
except Exception as e:
|
264 |
-
print(f"β Launch error: {e}")
|
265 |
-
# Fallback launch configuration
|
266 |
-
print("π Trying fallback configuration...")
|
267 |
-
demo.launch(
|
268 |
-
auth=auth_tuple,
|
269 |
-
show_api=True,
|
270 |
-
ssr_mode=False
|
271 |
-
)
|
|
|
1 |
import gradio as gr
|
2 |
import os
|
|
|
3 |
import time
|
4 |
from collections import defaultdict
|
5 |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
|
|
10 |
API_KEY = os.getenv("API_KEY")
|
11 |
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD")
|
12 |
|
13 |
+
print("π Security Status:")
|
14 |
print(f" HF_TOKEN: {'β
Set' if HF_TOKEN else 'β Not set'}")
|
15 |
print(f" API_KEY: {'β
Set' if API_KEY else 'β Not set'}")
|
16 |
print(f" ADMIN_PASSWORD: {'β
Set' if ADMIN_PASSWORD else 'β Not set'}")
|
17 |
|
18 |
+
# Simple rate limiting
|
19 |
request_counts = defaultdict(list)
|
20 |
|
21 |
+
# Load model
|
22 |
model_name = "gpt2"
|
23 |
+
print("π¦ Loading model...")
|
24 |
+
|
25 |
try:
|
26 |
if HF_TOKEN:
|
27 |
+
tokenizer = GPT2Tokenizer.from_pretrained(model_name, token=HF_TOKEN)
|
28 |
+
model = GPT2LMHeadModel.from_pretrained(model_name, token=HF_TOKEN)
|
29 |
print("β
Model loaded with HF token")
|
30 |
else:
|
31 |
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
|
|
33 |
print("β
Model loaded without token")
|
34 |
|
35 |
tokenizer.pad_token = tokenizer.eos_token
|
36 |
+
print("β
Model ready!")
|
37 |
|
38 |
except Exception as e:
|
39 |
print(f"β Model loading failed: {e}")
|
40 |
+
raise
|
41 |
|
42 |
+
def check_api_key(provided_key):
|
43 |
+
"""Simple API key validation with rate limiting"""
|
44 |
if not API_KEY:
|
45 |
+
return True, "Public access"
|
|
|
|
|
|
|
46 |
|
47 |
+
if not provided_key or provided_key != API_KEY:
|
48 |
+
return False, "Invalid or missing API key"
|
49 |
|
50 |
+
# Simple rate limiting (100 requests per hour)
|
51 |
now = time.time()
|
52 |
+
hour_ago = now - 3600
|
53 |
|
54 |
+
# Clean old requests
|
55 |
+
request_counts[provided_key] = [
|
56 |
+
t for t in request_counts[provided_key] if t > hour_ago
|
|
|
57 |
]
|
58 |
|
59 |
+
if len(request_counts[provided_key]) >= 100:
|
60 |
+
return False, "Rate limit exceeded (100/hour)"
|
|
|
61 |
|
62 |
+
request_counts[provided_key].append(now)
|
63 |
+
return True, f"Authenticated ({len(request_counts[provided_key])}/100)"
|
|
|
64 |
|
65 |
+
def generate_text(prompt, max_length, temperature, top_p, top_k, api_key):
|
66 |
+
"""Generate text with GPT-2"""
|
67 |
|
68 |
+
# API key check
|
69 |
+
valid, msg = check_api_key(api_key)
|
70 |
+
if not valid:
|
71 |
+
return f"π Error: {msg}"
|
72 |
|
73 |
+
# Input validation
|
74 |
+
if not prompt.strip():
|
75 |
+
return "β Please enter a prompt"
|
76 |
|
77 |
if len(prompt) > 1000:
|
78 |
+
return "β Prompt too long (max 1000 chars)"
|
79 |
|
80 |
try:
|
81 |
+
print(f"π {msg}")
|
82 |
+
print(f"π Generating: {prompt[:50]}...")
|
83 |
|
84 |
+
# Encode input
|
85 |
+
inputs = tokenizer.encode(
|
86 |
+
prompt,
|
87 |
+
return_tensors="pt",
|
88 |
+
max_length=400,
|
89 |
+
truncation=True
|
90 |
+
)
|
91 |
|
92 |
+
# Generate
|
93 |
with torch.no_grad():
|
94 |
outputs = model.generate(
|
95 |
inputs,
|
96 |
+
max_length=min(inputs.shape[1] + max_length, 500),
|
97 |
temperature=max(0.1, min(2.0, temperature)),
|
98 |
top_p=max(0.1, min(1.0, top_p)),
|
99 |
top_k=max(1, min(100, top_k)),
|
100 |
do_sample=True,
|
101 |
pad_token_id=tokenizer.eos_token_id,
|
102 |
+
num_return_sequences=1,
|
103 |
+
no_repeat_ngram_size=2
|
104 |
)
|
105 |
|
106 |
+
# Decode result
|
107 |
+
generated = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
108 |
+
result = generated[len(prompt):].strip()
|
109 |
|
110 |
+
print(f"β
Generated {len(result)} characters")
|
111 |
+
return result if result else "β No text generated"
|
112 |
|
113 |
except Exception as e:
|
114 |
+
error = f"β Generation failed: {str(e)}"
|
115 |
+
print(error)
|
116 |
+
return error
|
117 |
|
118 |
+
# Create simple interface - NO COMPLEX THEMES OR CSS
|
119 |
+
demo = gr.Blocks(title="GPT-2 Text Generator")
|
120 |
+
|
121 |
+
with demo:
|
122 |
+
# Simple header
|
123 |
+
gr.Markdown("# π€ GPT-2 Text Generator")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
|
125 |
+
# Security info
|
|
|
|
|
|
|
126 |
if API_KEY:
|
127 |
+
gr.Markdown("π **API Authentication Required**")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
else:
|
129 |
+
gr.Markdown("π **Public Access Mode**")
|
|
|
|
|
|
|
|
|
130 |
|
131 |
with gr.Row():
|
132 |
+
with gr.Column():
|
133 |
+
# Input section
|
134 |
+
prompt = gr.Textbox(
|
135 |
+
label="Prompt",
|
136 |
+
placeholder="Enter your text prompt...",
|
137 |
lines=3
|
138 |
)
|
139 |
|
140 |
+
# API key input (only if needed)
|
141 |
if API_KEY:
|
142 |
+
api_key = gr.Textbox(
|
143 |
+
label="API Key",
|
144 |
type="password",
|
145 |
+
placeholder="Enter API key..."
|
146 |
)
|
|
|
147 |
else:
|
148 |
+
api_key = gr.Textbox(value="", visible=False)
|
|
|
149 |
|
150 |
+
# Parameters
|
151 |
+
max_length = gr.Slider(
|
152 |
+
10, 200, 100,
|
153 |
+
label="Max Length"
|
154 |
+
)
|
155 |
+
temperature = gr.Slider(
|
156 |
+
0.1, 2.0, 0.7,
|
157 |
+
label="Temperature"
|
158 |
+
)
|
159 |
+
top_p = gr.Slider(
|
160 |
+
0.1, 1.0, 0.9,
|
161 |
+
label="Top-p"
|
162 |
+
)
|
163 |
+
top_k = gr.Slider(
|
164 |
+
1, 100, 50,
|
165 |
+
label="Top-k"
|
166 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
167 |
|
168 |
+
# Generate button
|
169 |
+
generate_btn = gr.Button("Generate", variant="primary")
|
170 |
|
171 |
+
with gr.Column():
|
172 |
+
# Output
|
173 |
+
output = gr.Textbox(
|
174 |
+
label="Generated Text",
|
175 |
+
lines=10,
|
176 |
placeholder="Generated text will appear here..."
|
177 |
)
|
|
|
|
|
|
|
|
|
178 |
|
179 |
# Examples
|
180 |
+
gr.Examples([
|
181 |
+
["Once upon a time"],
|
182 |
+
["The future of AI is"],
|
183 |
+
["In a world where technology"],
|
184 |
+
], inputs=prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
185 |
|
186 |
+
# Connect function
|
187 |
generate_btn.click(
|
188 |
+
generate_text,
|
189 |
+
inputs=[prompt, max_length, temperature, top_p, top_k, api_key],
|
190 |
+
outputs=output
|
191 |
)
|
192 |
|
193 |
+
# Simple launch - MINIMAL CONFIGURATION
|
194 |
if __name__ == "__main__":
|
195 |
+
auth = ("admin", ADMIN_PASSWORD) if ADMIN_PASSWORD else None
|
|
|
|
|
|
|
|
|
196 |
|
197 |
+
if auth:
|
198 |
+
print("π Admin auth enabled")
|
199 |
+
|
200 |
+
print("π Starting server...")
|
201 |
+
|
202 |
+
# MINIMAL launch config that works on HF Spaces
|
203 |
+
demo.launch(auth=auth)
|
204 |
+
|
205 |
+
print("β
Server running!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
@@ -1,7 +1,4 @@
|
|
1 |
-
gradio
|
2 |
-
transformers
|
3 |
-
torch
|
4 |
-
|
5 |
-
uvicorn>=0.15.0
|
6 |
-
pydantic>=1.8.0
|
7 |
-
python-multipart>=0.0.5
|
|
|
1 |
+
gradio
|
2 |
+
transformers
|
3 |
+
torch
|
4 |
+
tokenizers
|
|
|
|
|
|