Yao211 commited on
Commit
8b4d06b
·
verified ·
1 Parent(s): 089b259

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -378
app.py DELETED
@@ -1,378 +0,0 @@
1
- import gradio as gr
2
- import requests
3
- import os
4
- from tempfile import NamedTemporaryFile
5
- from dotenv import load_dotenv
6
- import time
7
- import json
8
- from pathlib import Path
9
-
10
- # Load environment variables
11
- load_dotenv()
12
-
13
- # Configuration
14
- API_URL = os.getenv("MIRAGIC_API_URL")
15
- MAX_FREE_TRIALS = 2
16
-
17
- # Example images
18
- EXAMPLE_IMAGES = [
19
- ["assets/1.jpg"],
20
- ["assets/2.jpg"],
21
- ["assets/3.jpg"],
22
- ["assets/4.jpg"],
23
- ]
24
-
25
- # Company information
26
- COMPANY_INFO = """
27
- ## About US
28
- ### Miragic is a cutting-edge platform to serve AI-powered tools like Virtual Try-on, Speed Painting, Background Remover and Sales Pilot.
29
- ### [Visit our website](https://miragic.ai) to explore more innovative generative AI tools!
30
- """
31
-
32
- def call_speedpainting_api(image):
33
- """Call the Miragic API with proper error handling"""
34
- try:
35
- # Check if API_URL is configured
36
- if not API_URL:
37
- raise gr.Error("API URL is not configured. Please set MIRAGIC_API_URL in your environment variables.")
38
-
39
- with NamedTemporaryFile(suffix=".png") as tmp:
40
- image.save(tmp.name)
41
- with open(tmp.name, 'rb') as f:
42
- files = {'file': f}
43
-
44
- # Add headers for better compatibility
45
- headers = {
46
- 'User-Agent': 'Miragic-SpeedPainting/1.0',
47
- 'Accept': 'application/json'
48
- }
49
-
50
- # Reduced timeout for Hugging Face Spaces
51
- response = requests.post(
52
- API_URL,
53
- files=files,
54
- headers=headers,
55
- timeout=60, # Reduced from 120 to 60
56
- verify=True
57
- )
58
-
59
- if response.status_code == 200:
60
- result = response.json()
61
- if result.get("status") == "success":
62
- video_url = result["link"]
63
- if "dl=0" in video_url:
64
- return video_url.replace("dl=0", "raw=1")
65
- elif "?dl=" in video_url:
66
- return video_url.split("?dl=")[0] + "?raw=1"
67
- return video_url
68
- raise gr.Error(f"API error: {result.get('message', 'Unknown error')}")
69
- elif response.status_code == 429:
70
- raise gr.Error("API rate limit exceeded. Please try again later.")
71
- elif response.status_code == 503:
72
- raise gr.Error("API service temporarily unavailable. Please try again later.")
73
- else:
74
- raise gr.Error(f"API request failed with status {response.status_code}")
75
-
76
- except requests.exceptions.ConnectTimeout:
77
- raise gr.Error("Connection timed out. This might be due to network restrictions on Hugging Face Spaces. Please try again or contact support.")
78
- except requests.exceptions.ReadTimeout:
79
- raise gr.Error("Request timed out. The API is taking longer than expected. Please try again.")
80
- except requests.exceptions.ConnectionError:
81
- raise gr.Error("Unable to connect to the API. Please check if the service is running or try again later.")
82
- except requests.exceptions.RequestException as e:
83
- raise gr.Error(f"Network error: {str(e)}")
84
- except Exception as e:
85
- raise gr.Error(f"Processing error: {str(e)}")
86
-
87
- def generate_speedpainting(image, usage_count):
88
- """Generate speedpainting video"""
89
- try:
90
- count = int(usage_count) if usage_count else 0
91
-
92
- if count >= MAX_FREE_TRIALS:
93
- raise gr.Error(
94
- f"You've reached your daily limit of {MAX_FREE_TRIALS} free generations. "
95
- f"Please <a href='https://miragic.ai/' target='_blank'>sign up at Miragic.ai</a> "
96
- "for unlimited access or wait 24 hours to try again!"
97
- )
98
-
99
- if not image:
100
- raise gr.Error("Please upload an image first!")
101
-
102
- # Show loading message
103
- gr.Info("Processing your image... This may take a moment.")
104
-
105
- video_url = call_speedpainting_api(image)
106
-
107
- # Success message
108
- gr.Info("Speedpainting generated successfully!")
109
-
110
- return video_url, count + 1
111
- except gr.Error:
112
- # Re-raise Gradio errors as-is
113
- raise
114
- except Exception as e:
115
- # Handle any other unexpected errors
116
- raise gr.Error(f"An unexpected error occurred: {str(e)}")
117
-
118
- def check_usage_limit(usage_count):
119
- """Check if user should see signup prompt"""
120
- count = int(usage_count) if usage_count else 0
121
- return gr.HTML(visible=count >= MAX_FREE_TRIALS - 1)
122
-
123
- # Custom CSS for styling
124
- css = """
125
- footer {visibility: hidden}
126
- .banner {
127
- background-color: #f8f9fa;
128
- padding: 10px;
129
- border-radius: 5px;
130
- margin-bottom: 20px;
131
- text-align: center;
132
- }
133
- .input-row {
134
- display: flex;
135
- flex-direction: row;
136
- gap: 20px;
137
- }
138
- .input-column {
139
- flex: 1;
140
- }
141
- .button-gradient, .signup-button {
142
- background: linear-gradient(45deg, #ff416c, #ff4b2b, #ff9b00, #ff416c);
143
- background-size: 400% 400%;
144
- border: none;
145
- padding: 14px 28px;
146
- font-size: 16px;
147
- font-weight: bold;
148
- color: white;
149
- border-radius: 10px;
150
- cursor: pointer;
151
- transition: 0.3s ease-in-out;
152
- animation: gradientAnimation 2s infinite linear;
153
- box-shadow: 0 4px 10px rgba(255, 65, 108, 0.6);
154
- text-decoration: none;
155
- display: inline-block;
156
- margin-top: 10px;
157
- }
158
- .signup-button {
159
- margin: 0 auto;
160
- }
161
- @keyframes gradientAnimation {
162
- 0% { background-position: 0% 50%; }
163
- 100% { background-position: 100% 50%; }
164
- }
165
- .button-gradient:hover, .signup-button:hover {
166
- transform: scale(1.05);
167
- box-shadow: 0 6px 15px rgba(255, 75, 43, 0.8);
168
- }
169
- .signup-container {
170
- text-align: center;
171
- padding: 20px;
172
- background: #f8f9fa;
173
- border-radius: 8px;
174
- margin-top: 20px;
175
- }
176
- .signup-container h3 {
177
- margin-bottom: 10px;
178
- color: #333;
179
- }
180
- .signup-container p {
181
- margin-bottom: 15px;
182
- color: #555;
183
- }
184
- .usage-info {
185
- background-color: #e8f4f8;
186
- padding: 10px;
187
- border-radius: 5px;
188
- margin-bottom: 10px;
189
- text-align: center;
190
- font-weight: bold;
191
- }
192
- """
193
-
194
- # Custom JavaScript for cookie management
195
- js = """
196
- <script>
197
- // Cookie management functions
198
- function setCookie(name, value, days) {
199
- const expires = new Date();
200
- expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
201
- document.cookie = name + '=' + value + ';expires=' + expires.toUTCString() + ';path=/';
202
- }
203
-
204
- function getCookie(name) {
205
- const nameEQ = name + '=';
206
- const ca = document.cookie.split(';');
207
- for(let i = 0; i < ca.length; i++) {
208
- let c = ca[i];
209
- while (c.charAt(0) === ' ') c = c.substring(1, c.length);
210
- if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
211
- }
212
- return null;
213
- }
214
-
215
- function generateUserId() {
216
- return 'user_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
217
- }
218
-
219
- function getUserId() {
220
- let userId = getCookie('miragic_user_id');
221
- if (!userId) {
222
- userId = generateUserId();
223
- setCookie('miragic_user_id', userId, 7); // 7 days
224
- }
225
- return userId;
226
- }
227
-
228
- function getUsageCount() {
229
- const userId = getUserId();
230
- const usageKey = 'miragic_usage_' + userId;
231
- const today = new Date().toDateString();
232
- const storedData = getCookie(usageKey);
233
-
234
- if (storedData) {
235
- try {
236
- const data = JSON.parse(decodeURIComponent(storedData));
237
- if (data.date === today) {
238
- return data.count;
239
- }
240
- } catch (e) {
241
- console.error('Error parsing usage data:', e);
242
- }
243
- }
244
- return 0;
245
- }
246
-
247
- function incrementUsageCount() {
248
- const userId = getUserId();
249
- const usageKey = 'miragic_usage_' + userId;
250
- const today = new Date().toDateString();
251
- const currentCount = getUsageCount();
252
- const newCount = currentCount + 1;
253
-
254
- const data = {
255
- date: today,
256
- count: newCount
257
- };
258
-
259
- setCookie(usageKey, encodeURIComponent(JSON.stringify(data)), 1); // 1 day
260
- return newCount;
261
- }
262
-
263
- function updateUsageDisplay() {
264
- const count = getUsageCount();
265
- const remaining = Math.max(0, 2 - count);
266
- const usageInfo = document.querySelector('.usage-info');
267
- if (usageInfo) {
268
- usageInfo.textContent = `Free generations remaining: ${remaining}/2`;
269
- if (remaining === 0) {
270
- usageInfo.style.backgroundColor = '#ffebee';
271
- usageInfo.style.color = '#c62828';
272
- }
273
- }
274
- }
275
-
276
- // Initialize on page load
277
- document.addEventListener('DOMContentLoaded', function() {
278
- updateUsageDisplay();
279
-
280
- // Update usage count input
281
- const usageInput = document.querySelector('input[data-testid="textbox"]');
282
- if (usageInput) {
283
- usageInput.value = getUsageCount();
284
- }
285
- });
286
-
287
- // Function to handle form submission
288
- function handleSubmit() {
289
- const currentCount = getUsageCount();
290
- if (currentCount >= 2) {
291
- alert('You have reached your daily limit of 2 free generations. Please sign up at miragic.ai for unlimited access or wait 24 hours to try again!');
292
- return false;
293
- }
294
-
295
- const newCount = incrementUsageCount();
296
- updateUsageDisplay();
297
-
298
- // Update hidden input
299
- const usageInput = document.querySelector('input[data-testid="textbox"]');
300
- if (usageInput) {
301
- usageInput.value = newCount;
302
- }
303
-
304
- return true;
305
- }
306
- </script>
307
- """
308
-
309
- with gr.Blocks(title="Miragic Speed-Painting", theme=gr.themes.Ocean(), css=css, head=js) as demo:
310
- gr.Markdown("""
311
- <div style="display: flex; align-items: center;">
312
- <img src="https://avatars.githubusercontent.com/u/211682198?s=200&v=4" style="width: 80px; margin-right: 20px;"/>
313
- <div>
314
- <h1 style="margin-bottom: 0;">Miragic Speed-Painting 🎨</h1>
315
- <p>Upload an image to see AI create speedpainting animations!</p>
316
- </div>
317
- </div>
318
- """)
319
-
320
- gr.Markdown(COMPANY_INFO)
321
-
322
- # # Usage info display
323
- # gr.HTML('<div class="usage-info">Free generations remaining: 2/2</div>')
324
-
325
- with gr.Row():
326
- with gr.Column():
327
- image_input = gr.Image(
328
- label="Upload Image",
329
- type="pil",
330
- sources=["upload", "clipboard"],
331
- height=300
332
- )
333
-
334
- gr.Examples(
335
- examples=EXAMPLE_IMAGES,
336
- inputs=image_input,
337
- label="Try these examples!",
338
- examples_per_page=4
339
- )
340
-
341
- submit_btn = gr.Button("Generate Speedpainting 🚀", elem_classes="button-gradient")
342
-
343
- with gr.Column():
344
- video_output = gr.Video(
345
- label="Speedpainting Result",
346
- autoplay=True,
347
- format="mp4",
348
- height=300
349
- )
350
-
351
- signup_prompt = gr.HTML(
352
- visible=False,
353
- value="""<div class="signup-container">
354
- <h3>🚀 Unlock Unlimited Generations!</h3>
355
- <p>Sign up at https://miragic.ai for full access!</p>
356
- <a href='https://miragic.ai/' target='_blank' class="signup-button">
357
- Get Started Free 🚀
358
- </a>
359
- </div>"""
360
- )
361
-
362
- # Hidden input to track usage count
363
- usage_count = gr.Textbox(visible=False, value="0")
364
-
365
- # Submit button click handler
366
- submit_btn.click(
367
- fn=generate_speedpainting,
368
- inputs=[image_input, usage_count],
369
- outputs=[video_output, usage_count],
370
- js="(image, count) => { if (!handleSubmit()) return [null, count]; return [image, count]; }"
371
- ).then(
372
- fn=check_usage_limit,
373
- inputs=[usage_count],
374
- outputs=signup_prompt
375
- )
376
-
377
- if __name__ == "__main__":
378
- demo.launch()