File size: 12,695 Bytes
b1b97e5 ff1160b b1b97e5 5a9deb5 7f87f37 ff1160b 9baab51 b1b97e5 7f87f37 ff1160b 5a9deb5 412f761 03a50e1 412f761 03a50e1 412f761 03a50e1 b16a3cd a71e240 b16a3cd b1b97e5 b16a3cd b1b97e5 b16a3cd 5a9deb5 b16a3cd 5a9deb5 9baab51 5a9deb5 b16a3cd 5a9deb5 1e6be46 5a9deb5 b16a3cd 5a9deb5 9baab51 5a9deb5 b16a3cd 5a9deb5 b16a3cd 5a9deb5 b16a3cd 5a9deb5 7f87f37 1e6be46 7f87f37 9baab51 b16a3cd 7f87f37 fa69230 9baab51 7f87f37 b16a3cd fa69230 b16a3cd fa69230 3290a27 fa69230 b16a3cd 3f47c6e 7f87f37 fa69230 7f87f37 ff1160b fa69230 7f87f37 fa69230 7f87f37 fa69230 7f87f37 fa69230 7f87f37 fa69230 7f87f37 fa69230 7f87f37 fa69230 7f87f37 3290a27 fa69230 ff1160b b16a3cd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 |
import os
import gradio as gr
import requests
import json
from datetime import datetime
# Load secrets
PAYWALLS_API_KEY = os.environ.get("PAYWALLS_API_KEY")
PAYWALLS_API_URL = os.environ.get("PAYWALLS_API_URL", "https://api.paywalls.ai/v1")
# Free tier limits
FREE_MAX_TOKENS = 150
PREMIUM_MAX_TOKENS = 2048
# Style presets (premium feature)
STYLE_PRESETS = {
"neutral": "You are a creative writing assistant.",
"poetic": "You are a poetic writing assistant. Write in lyrical, expressive language with vivid imagery.",
"dramatic": "You are a dramatic writing assistant. Create tension, conflict, and emotional depth.",
"comedic": "You are a comedic writing assistant. Use humor, wit, and light-hearted tone.",
"horror": "You are a horror writing assistant. Build suspense and create eerie, unsettling atmospheres."
}
def check_paywall(user_id: str):
"""Check user payment status and generate wallet topup link"""
headers = {
"Authorization": f"Bearer {PAYWALLS_API_KEY}",
"Content-Type": "application/json"
}
# Check if user has active balance/subscription
try:
check_response = requests.get(
f"{PAYWALLS_API_URL}/payments/check",
headers=headers,
params={"user_id": user_id},
timeout=10
)
is_paid = check_response.status_code == 200 and check_response.json().get("paid", False)
except:
is_paid = False
# Direct users to AI Wallet topup page
paywall_url = f"https://wallet.paywalls.ai/topup?user={user_id}"
return is_paid, paywall_url
def free_tier_generation(system_message, history, user_message, max_tokens, temperature):
try:
from huggingface_hub import InferenceClient
client = InferenceClient()
messages = [{"role": "system", "content": system_message}] + history + [{"role": "user", "content": user_message}]
reply = client.chat_completion(
messages=messages,
max_tokens=max_tokens,
temperature=temperature,
model="meta-llama/Llama-3.2-3B-Instruct"
).choices[0].message.content
return reply
except Exception as e:
print(f"[Free Tier] Error: {e}")
return f"β οΈ Free tier service error: {str(e)}"
def premium_generation(user_id, system_message, history, user_message, max_tokens, temperature, top_p):
"""Premium tier using Paywalls proxy"""
headers = {
"Authorization": f"Bearer {PAYWALLS_API_KEY}",
"Content-Type": "application/json"
}
messages = [{"role": "system", "content": system_message}] + history + [{"role": "user", "content": user_message}]
payload = {
"model": "gpt-3.5-turbo",
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
"top_p": top_p,
"user": user_id
}
try:
response = requests.post(
f"{PAYWALLS_API_URL}/chat/completions",
headers=headers,
json=payload,
timeout=60
)
response.raise_for_status()
data = response.json()
if data.get("choices"):
return data["choices"][0]["message"]["content"]
return "No response from premium model."
except requests.exceptions.HTTPError as e:
print(f"[Premium] HTTP Error: {e.response.status_code} - {e.response.text}")
return f"β οΈ Premium service error: {e.response.status_code}"
except Exception as e:
print(f"[Premium] Error: {e}")
return f"β οΈ Premium service error: {str(e)}"
def respond(message, history, style, max_tokens, temperature, top_p):
user_id = "demo_user"
is_premium, paywall_url = check_paywall(user_id)
# Check style restriction for free users
if not is_premium:
max_tokens = min(max_tokens, FREE_MAX_TOKENS)
if style != "neutral":
return history + [{"role": "assistant", "content": f"π **Premium Feature Locked**\n\nStyle customization is available for Premium users only.\n\n[β¨ Upgrade to Premium]({paywall_url})"}]
system_message = STYLE_PRESETS.get(style, STYLE_PRESETS["neutral"])
# Generate response based on tier
if is_premium:
reply = premium_generation(user_id, system_message, history, message, max_tokens, temperature, top_p)
tier_badge = "β¨ **PREMIUM**"
else:
reply = free_tier_generation(system_message, history, message, max_tokens, temperature)
tier_badge = f"π **FREE TIER** β’ 150 tokens limit\n\nπ [Unlock Premium Features]({paywall_url}) β’ Longer stories β’ Custom styles β’ Export"
full_reply = f"{reply}\n\n---\n{tier_badge}"
return history + [{"role": "user", "content": message}, {"role": "assistant", "content": full_reply}]
def export_conversation(history):
user_id = "demo_user"
is_premium, paywall_url = check_paywall(user_id)
if not is_premium:
return None, f"π Export feature requires Premium.\n\n[Upgrade Now]({paywall_url})"
content = f"Creative Writing Session - {datetime.now().strftime('%Y-%m-%d %H:%M')}\n\n"
for msg in history:
role = msg["role"].upper()
content += f"{role}: {msg['content']}\n\n"
filepath = "/tmp/creative_writing.txt"
with open(filepath, "w") as f:
f.write(content)
return filepath, "β
Exported successfully!"
# Custom CSS for elegant design
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
* {
font-family: 'Inter', sans-serif !important;
}
.gradio-container {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
}
.main-header {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(10px);
border-radius: 20px;
padding: 30px;
margin-bottom: 25px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
text-align: center;
}
.main-header h1 {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 2.5em;
font-weight: 700;
margin-bottom: 10px;
}
.main-header p {
color: #64748b;
font-size: 1.1em;
}
.chat-container {
background: rgba(255, 255, 255, 0.98);
border-radius: 20px;
padding: 25px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
.controls-container {
background: rgba(255, 255, 255, 0.98);
border-radius: 20px;
padding: 25px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
.premium-badge {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
padding: 8px 16px;
border-radius: 20px;
font-weight: 600;
font-size: 0.85em;
display: inline-block;
margin-left: 10px;
}
.feature-card {
background: rgba(102, 126, 234, 0.1);
border-radius: 12px;
padding: 15px;
margin-bottom: 15px;
border-left: 4px solid #667eea;
}
button {
border-radius: 12px !important;
font-weight: 600 !important;
transition: all 0.3s ease !important;
}
button:hover {
transform: translateY(-2px) !important;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15) !important;
}
.primary-btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
}
input, textarea, select {
border-radius: 10px !important;
border: 2px solid #e2e8f0 !important;
transition: all 0.3s ease !important;
}
input:focus, textarea:focus, select:focus {
border-color: #667eea !important;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1) !important;
}
.slider {
accent-color: #667eea !important;
}
"""
# Build UI
with gr.Blocks(css=custom_css, title="Creative Writing Assistant", theme=gr.themes.Soft()) as demo:
# Header
with gr.Row():
with gr.Column():
gr.HTML("""
<div class="main-header">
<h1>β¨ Creative Writing Assistant</h1>
<p>Transform your ideas into captivating stories with AI-powered creativity</p>
<div style="margin-top: 20px;">
<span style="background: rgba(102, 126, 234, 0.1); padding: 10px 20px; border-radius: 25px; color: #667eea; font-weight: 600; margin: 0 10px;">
π Free: 150 tokens
</span>
<span style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 10px 20px; border-radius: 25px; color: white; font-weight: 600; margin: 0 10px;">
β¨ Premium: 2048 tokens + Styles + Export
</span>
</div>
</div>
""")
# Main Content
with gr.Row(equal_height=True):
# Chat Section
with gr.Column(scale=2, elem_classes="chat-container"):
gr.Markdown("### π¬ Your Creative Space")
chatbot = gr.Chatbot(
type="messages",
height=550,
show_copy_button=True,
avatar_images=(None, "https://em-content.zobj.net/source/twitter/376/sparkles_2728.png")
)
with gr.Row():
msg = gr.Textbox(
label="",
placeholder="π¨ Write your creative prompt here... (e.g., 'Write a story about a magical garden')",
lines=3,
scale=9
)
with gr.Row():
submit = gr.Button("β¨ Generate Story", variant="primary", scale=2, size="lg")
clear = gr.Button("ποΈ Clear", scale=1, size="lg")
# Controls Section
with gr.Column(scale=1, elem_classes="controls-container"):
gr.Markdown("### ποΈ Creative Controls")
gr.HTML('<div class="feature-card"><b>π¨ Writing Style</b><span class="premium-badge">PREMIUM</span></div>')
style = gr.Dropdown(
choices=list(STYLE_PRESETS.keys()),
value="neutral",
label="",
info="Choose your narrative voice"
)
gr.Markdown("---")
gr.Markdown("**π Generation Length**")
max_tokens = gr.Slider(
FREE_MAX_TOKENS,
PREMIUM_MAX_TOKENS,
value=FREE_MAX_TOKENS,
step=50,
label="Max Tokens",
info="Free tier limited to 150 tokens",
elem_classes="slider"
)
gr.Markdown("**π‘οΈ Creativity Level**")
temperature = gr.Slider(
0.1,
2.0,
value=0.8,
step=0.1,
label="Temperature",
info="Higher = more creative",
elem_classes="slider"
)
gr.Markdown("**π² Diversity**")
top_p = gr.Slider(
0.1,
1.0,
value=0.95,
step=0.05,
label="Top-p",
info="Response variety",
elem_classes="slider"
)
gr.Markdown("---")
gr.HTML('<div class="feature-card"><b>πΎ Export</b><span class="premium-badge">PREMIUM</span></div>')
export_btn = gr.Button("π₯ Download Story", variant="secondary", size="lg")
download_file = gr.File(label="Your File", visible=False)
export_status = gr.Textbox(label="Status", interactive=False, visible=False)
# Footer
gr.HTML("""
<div style="text-align: center; margin-top: 30px; padding: 20px; background: rgba(255, 255, 255, 0.9); border-radius: 15px;">
<p style="color: #64748b; font-size: 0.95em;">
Powered by AI β’ Built with β€οΈ using Gradio & Paywalls.ai
</p>
</div>
""")
# Event handlers
submit.click(respond, [msg, chatbot, style, max_tokens, temperature, top_p], [chatbot]).then(lambda: "", None, [msg])
msg.submit(respond, [msg, chatbot, style, max_tokens, temperature, top_p], [chatbot]).then(lambda: "", None, [msg])
clear.click(lambda: None, None, [chatbot])
export_btn.click(export_conversation, [chatbot], [download_file, export_status]).then(
lambda: (gr.update(visible=True), gr.update(visible=True)), None, [download_file, export_status]
)
if __name__ == "__main__":
demo.launch() |