openfree commited on
Commit
0d65984
·
verified ·
1 Parent(s): 36ec0c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -567
app.py CHANGED
@@ -1,580 +1,35 @@
1
- import gradio as gr
2
- import replicate
3
  import os
4
- from PIL import Image
5
- import requests
6
- from io import BytesIO
7
- import time
8
- import base64
9
- import json
10
 
11
- # Set up API keys from environment variables
12
- os.environ['REPLICATE_API_TOKEN'] = os.getenv('REPLICATE_API_TOKEN')
13
- FIREWORKS_API_KEY = os.getenv('FIREWORKS_API_KEY', '')
14
- BRAVE_API_KEY = os.getenv('BRAVE_API_KEY', '') # Add Brave API key
15
-
16
- def search_design_trends(product_type):
17
- """
18
- Brave Search API를 사용하여 최신 디자인 트렌드와 기술 검색
19
- """
20
- if not BRAVE_API_KEY:
21
- return "검색 결과 없음 (API 키 미설정)"
22
-
23
- try:
24
- # 제품 디자인을 위한 검색 쿼리 구성
25
- query = f"{product_type} design trends 2024 2025 materials technology innovation"
26
-
27
- url = "https://api.search.brave.com/res/v1/web/search"
28
- headers = {
29
- "Accept": "application/json",
30
- "X-Subscription-Token": BRAVE_API_KEY
31
- }
32
- params = {
33
- "q": query,
34
- "count": 5
35
- }
36
-
37
- response = requests.get(url, headers=headers, params=params, timeout=10)
38
-
39
- if response.status_code == 200:
40
- data = response.json()
41
- results = []
42
-
43
- if 'web' in data and 'results' in data['web']:
44
- for item in data['web']['results'][:3]:
45
- results.append(f"- {item.get('title', '')}: {item.get('description', '')[:150]}")
46
-
47
- if results:
48
- return "\n".join(results)
49
- else:
50
- return "제한된 검색 결과"
51
- else:
52
- return "현재 검색 불가"
53
-
54
- except Exception as e:
55
- print(f"Brave 검색 오류: {str(e)}")
56
- return "검색 결과 이용 불가"
57
-
58
- def enhance_prompt_with_team(user_input):
59
- """
60
- 실제 웹 검색을 통한 팀 협업 방식의 향상된 프롬프트 생성
61
- """
62
- if not FIREWORKS_API_KEY:
63
- # 기본 향상으로 폴백
64
- return create_basic_design_prompt(user_input), "API 키가 설정되지 않음"
65
-
66
- try:
67
- # 먼저 엔지니어를 위한 실제 검색 결과 획득
68
- search_results = search_design_trends(user_input)
69
-
70
- url = "https://api.fireworks.ai/inference/v1/chat/completions"
71
-
72
- # 검색 통합된 향상된 시스템 프롬프트
73
- system_prompt = """당신은 세 가지 전문 역할로 구성된 제품 디자인 팀입니다. 모든 응답은 한국어로 작성하세요:
74
-
75
- ## 팀 역할:
76
-
77
- ### 1. 감독 (크리에이티브 비전 리더)
78
- - 사용자 요구사항과 시장 포지셔닝 분석
79
- - 디자인 철학과 제약 조건 설정
80
- - 기능에 대한 최종 결정
81
-
82
- ### 2. 엔지니어 (연구 데이터를 활용한 기술 전문가)
83
- - 제공된 검색 결과를 활용한 의사결정
84
- - 제조 가능성 평가
85
- - 재료와 기술 추천
86
- - 트렌드 기반 혁신 기능 제안
87
-
88
- ### 3. 디자이너 (비주얼 전문가)
89
- - 상세한 시각적 사양 작성
90
- - 정확한 재료, 마감, 색상 지정
91
- - 렌더링 스타일과 분위기 정의
92
- - 텍스트 레이블과 주석 포함 필수
93
-
94
- ## 출력 형식:
95
-
96
- **감독의 비전:**
97
- [간략한 비전 설명 - 2-3문장]
98
-
99
- **엔지니어의 기술 평가:**
100
- [검색 데이터 기반 3-4개 기술 권장사항]
101
-
102
- **디자이너의 최종 프롬프트:**
103
- [텍스트 레이블과 주석을 포함한 상세한 시각적 설명. 반드시 포함:
104
- - 제품명/모델을 타이틀 텍스트로
105
- - 화살표 주석과 함께 주요 기능 설명
106
- - 오버레이 텍스트로 기술 사양
107
- - 재료/구성요소 레이블
108
- 예시: "상단에 'MODEL X-500' 텍스트 오버레이, '티타늄 프레임', 'OLED 디스플레이', '5000mAh 배터리'를 가리키는 화살표와 기능 설명"]
109
-
110
- **최종 디자인 보고서:**
111
- [한국어로 작성된 제품의 핵심 특징, 혁신 포인트, 타겟 시장, 예상 제조 비용 등을 포함한 종합 보고서 - 3-4문장]
112
-
113
- 간결하지만 구체적으로 작성. 물리적 제품에만 집중하며 텍스트 주석 포함."""
114
-
115
- # 검색 결과와 함께 협업 프롬프트 생성
116
- user_prompt = f"""제품 컨셉: {user_input}
117
-
118
- 엔지니어의 연구 데이터:
119
- {search_results}
120
-
121
- 위 입력과 연구를 바탕으로 팀 협업 실행:
122
- 1. 감독이 비전 수립 (간략히)
123
- 2. 엔지니어가 위 연구 데이터를 활용해 기능 추천
124
- 3. 디자이너가 텍스트 레이블과 주석이 포함된 상세한 시각적 프롬프트 작성
125
- 4. 최종 디자인 보고서 작성 (한국어)
126
-
127
- 제조 가능하고 혁신적인 제품 디자인 창출에 집중하며, 명확한 텍스트 오버레이로 주요 기능, 사양, 구성요소 레이블 표시."""
128
-
129
- payload = {
130
- "model": "accounts/fireworks/models/qwen3-235b-a22b-instruct-2507", # Original model maintained
131
- "max_tokens": 600,
132
- "top_p": 0.9,
133
- "temperature": 0.7,
134
- "messages": [
135
- {
136
- "role": "system",
137
- "content": system_prompt
138
- },
139
- {
140
- "role": "user",
141
- "content": user_prompt
142
- }
143
- ]
144
- }
145
-
146
- headers = {
147
- "Accept": "application/json",
148
- "Content-Type": "application/json",
149
- "Authorization": f"Bearer {FIREWORKS_API_KEY}"
150
- }
151
-
152
- response = requests.post(url, headers=headers, data=json.dumps(payload), timeout=30)
153
-
154
- if response.status_code == 200:
155
- result = response.json()
156
- enhanced = result.get('choices', [{}])[0].get('message', {}).get('content', '')
157
- if enhanced:
158
- # 디자이너의 최종 프롬프트 추출
159
- if "디자이너의 최종 프롬프트:" in enhanced or "DESIGNER'S FINAL PROMPT:" in enhanced:
160
- parts = enhanced.split("디자이너의 최종 프롬프트:" if "디자이너의 최종 프롬프트:" in enhanced else "DESIGNER'S FINAL PROMPT:")
161
- if len(parts) > 1:
162
- # 최종 프롬프트와 전체 토론 모두 반환
163
- final_prompt = parts[1].split("**")[0].strip()
164
- return final_prompt, enhanced
165
- return enhanced, enhanced
166
-
167
- # API 실패 시 폴백
168
- return create_basic_design_prompt(user_input), "팀 협업 불가 - 기본 프롬프트 사용"
169
-
170
- except requests.exceptions.Timeout:
171
- print("Fireworks API 타임아웃 - 폴백 사용")
172
- return create_basic_design_prompt(user_input), "API 타임아웃 - 폴백 프롬프트 생성 사용"
173
- except Exception as e:
174
- print(f"팀 협업 오류: {str(e)}")
175
- return create_basic_design_prompt(user_input), f"오류: {str(e)[:100]}"
176
-
177
- def create_basic_design_prompt(user_input):
178
- """
179
- 텍스트 주석이 포함된 기본 디자인 프롬프트 생성을 위한 폴백 함수
180
- """
181
- product_name = user_input.upper().replace(" ", "-")
182
- return f"""상세한 텍스트 주석이 포함된 {user_input}의 전문 제품 디자인 컨셉:
183
- - 상단에 굵은 모던 폰트로 제품 타이틀 텍스트 오버레이: "{product_name} PRO 2025"
184
- - 주요 구성요소를 가리키는 화살표와 함께 기능 설명 레이블:
185
- * "프리미엄 소재" → 본체
186
- * "인체공학적 디자인" → 폼 팩터
187
- * "스마트 통합" → 제어 패널
188
- * "지속가능한 제조" → 친환경 요소
189
- - 모서리에 기술 사양 텍스트 오버레이:
190
- * 치수, 무게, 전력 사양
191
- - 주석이 포함된 깔끔한 산업 디자인
192
- - 스튜디오 조명과 함께 포토리얼리스틱 렌더링
193
- - 인포그래픽 요소가 포함된 전문 제품 사진 스타일
194
- - 깔끔한 산세리프 폰트(Helvetica/Arial 스타일)의 텍스트 레이블
195
- - 가독성을 위한 높은 대비 텍스트
196
- - 모든 레이블이 명확히 보이는 3/4 관점에서 표시"""
197
-
198
- def upload_image_to_hosting(image):
199
- """
200
- 호스팅 서비스에 이미지 업로드
201
- """
202
  try:
203
- # imgbb 먼저 시도
204
- buffered = BytesIO()
205
- image.save(buffered, format="PNG")
206
- buffered.seek(0)
207
- img_base64 = base64.b64encode(buffered.getvalue()).decode()
208
 
209
- response = requests.post(
210
- "https://api.imgbb.com/1/upload",
211
- data={
212
- 'key': '6d207e02198a847aa98d0a2a901485a5',
213
- 'image': img_base64,
214
- },
215
- timeout=10
216
- )
217
 
218
- if response.status_code == 200:
219
- data = response.json()
220
- if data.get('success'):
221
- return data['data']['url']
222
- except:
223
- pass
224
-
225
- # base64로 폴백
226
- buffered = BytesIO()
227
- image.save(buffered, format="PNG")
228
- buffered.seek(0)
229
- img_base64 = base64.b64encode(buffered.getvalue()).decode()
230
- return f"data:image/png;base64,{img_base64}"
231
-
232
- def process_product_design(prompt, enhance_prompt_flag, image1, image2=None):
233
- """
234
- 팀 협업을 통한 제품 디자인 처리
235
- """
236
- if not os.getenv('REPLICATE_API_TOKEN'):
237
- return None, prompt, "⚠️ REPLICATE_API_TOKEN을 설정하세요", ""
238
-
239
- try:
240
- team_discussion = ""
241
- final_prompt = prompt
242
 
243
- # 활성화된 경우 팀 협업 적용
244
- if enhance_prompt_flag:
245
- result = enhance_prompt_with_team(prompt)
246
- if isinstance(result, tuple):
247
- final_prompt, team_discussion = result
248
- else:
249
- final_prompt = result
250
- team_discussion = "팀 협업 완료"
251
-
252
- # 표시를 위한 팀 토론 형식화
253
- if "감독의 비전:" in team_discussion or "DIRECTOR'S VISION:" in team_discussion:
254
- team_discussion = f"### 🎬 팀 협업 프로세스\n\n{team_discussion}"
255
-
256
- # 모델 입력 준비
257
- model_input = {
258
- "prompt": final_prompt
259
- }
260
-
261
- # 제공된 경우 참조 이미지 추가
262
- if image1 or image2:
263
- image_urls = []
264
-
265
- if image1:
266
- url1 = upload_image_to_hosting(image1)
267
- image_urls.append(url1)
268
-
269
- if image2:
270
- url2 = upload_image_to_hosting(image2)
271
- image_urls.append(url2)
272
-
273
- model_input["image_input"] = image_urls
274
- status_msg = "✅ 스타일 참조와 함께 제품 디자인 생성 완료!"
275
- else:
276
- status_msg = "✅ 제품 디자인이 성공적으로 생성되었습니다!"
277
 
278
- # Replicate로 이미지 생성
279
  try:
280
- # 프롬프트에 텍스트 주석 강조 추가
281
- annotated_prompt = f"{final_prompt}. Include clear text labels, feature callouts with arrows, product name/model as title, technical specifications overlay, component annotations in clean modern typography"
282
-
283
- output = replicate.run(
284
- "black-forest-labs/flux-schnell", # Alternative model that works better
285
- input={
286
- "prompt": annotated_prompt,
287
- "num_outputs": 1,
288
- "aspect_ratio": "1:1",
289
- "output_format": "webp",
290
- "output_quality": 90
291
- }
292
- )
293
  except:
294
- # 텍스트 주석과 함께 원본 모델로 폴백
295
- annotated_prompt = f"{final_prompt}. With text overlays showing product name, key features with arrow callouts, specifications, and component labels in professional typography"
296
 
297
- output = replicate.run(
298
- "stability-ai/sdxl:39ed52f2a78e934b3ba6e2a89f5b1c712de7dfea535525255b1aa35c5565e08b",
299
- input={
300
- "prompt": annotated_prompt,
301
- "negative_prompt": "low quality, blurry, distorted, unreadable text, messy labels",
302
- "width": 1024,
303
- "height": 1024,
304
- "num_outputs": 1
305
- }
306
- )
307
-
308
- if output is None:
309
- return None, final_prompt, "❌ 모델로부터 출력을 받지 못했습니다", team_discussion
310
-
311
- # 출력 처리
312
- output_url = None
313
- if isinstance(output, str):
314
- output_url = output
315
- elif isinstance(output, list) and len(output) > 0:
316
- output_url = output[0]
317
- elif hasattr(output, 'url'):
318
- output_url = output.url
319
-
320
- if output_url:
321
- response = requests.get(output_url, timeout=30)
322
- if response.status_code == 200:
323
- img = Image.open(BytesIO(response.content))
324
- return img, final_prompt, status_msg, team_discussion
325
-
326
- return None, final_prompt, "❌ 출력을 처리할 수 없습니다", team_discussion
327
-
328
  except Exception as e:
329
- error_msg = str(e)
330
- return None, prompt, f"❌ 오류: {error_msg[:200]}", ""
331
-
332
- # 전문 제품 디자인 CSS
333
- css = """
334
- .gradio-container {
335
- background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
336
- font-family: 'Pretendard', 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
337
- min-height: 100vh;
338
- }
339
- .header-container {
340
- background: linear-gradient(135deg, #2d2d2d 0%, #0f0f0f 100%);
341
- padding: 2rem;
342
- border-radius: 20px;
343
- margin-bottom: 2rem;
344
- box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
345
- border: 1px solid rgba(255, 215, 0, 0.2);
346
- }
347
- .logo-text {
348
- font-size: 2.8rem;
349
- font-weight: 800;
350
- color: #ffd700;
351
- text-align: center;
352
- margin: 0;
353
- letter-spacing: -1px;
354
- text-shadow: 2px 2px 4px rgba(0,0,0,0.8);
355
- }
356
- .subtitle {
357
- color: #b0b0b0;
358
- text-align: center;
359
- font-size: 1rem;
360
- margin-top: 0.5rem;
361
- font-weight: 400;
362
- letter-spacing: 0.5px;
363
- }
364
- .mode-indicator {
365
- background: rgba(255, 215, 0, 0.1);
366
- border: 1px solid rgba(255, 215, 0, 0.3);
367
- border-radius: 10px;
368
- padding: 0.6rem 1.2rem;
369
- margin: 1rem auto;
370
- text-align: center;
371
- font-weight: 500;
372
- color: #ffd700;
373
- max-width: 600px;
374
- font-size: 0.9rem;
375
- }
376
- .main-content {
377
- background: rgba(255, 255, 255, 0.98);
378
- border-radius: 20px;
379
- padding: 2rem;
380
- box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
381
- }
382
- .gr-button-primary {
383
- background: linear-gradient(135deg, #2d2d2d 0%, #0f0f0f 100%) !important;
384
- border: 1px solid #ffd700 !important;
385
- color: #ffd700 !important;
386
- font-weight: 600 !important;
387
- font-size: 1rem !important;
388
- padding: 1rem 2rem !important;
389
- border-radius: 10px !important;
390
- transition: all 0.3s ease !important;
391
- text-transform: uppercase;
392
- letter-spacing: 0.5px;
393
- width: 100%;
394
- margin-top: 1rem !important;
395
- }
396
- .gr-button-primary:hover {
397
- transform: translateY(-2px) !important;
398
- box-shadow: 0 8px 25px rgba(255, 215, 0, 0.25) !important;
399
- background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%) !important;
400
- color: #000 !important;
401
- }
402
- .info-box {
403
- background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
404
- border-radius: 10px;
405
- padding: 1rem;
406
- margin-bottom: 1.5rem;
407
- border-left: 4px solid #ffd700;
408
- color: #333;
409
- font-size: 0.9rem;
410
- }
411
- .team-discussion {
412
- background: #f8f9fa;
413
- border-radius: 10px;
414
- padding: 1.2rem;
415
- margin-top: 1rem;
416
- border: 1px solid #dee2e6;
417
- font-family: 'Pretendard', 'Noto Sans KR', monospace;
418
- font-size: 0.85rem;
419
- max-height: 400px;
420
- overflow-y: auto;
421
- white-space: pre-wrap;
422
- line-height: 1.6;
423
- }
424
- .enhanced-prompt-box {
425
- background: #f0f0f0;
426
- border-radius: 10px;
427
- padding: 1rem;
428
- margin-top: 0.5rem;
429
- border-left: 3px solid #ffd700;
430
- font-size: 0.9rem;
431
- }
432
- .gr-input, .gr-textarea {
433
- background: #ffffff !important;
434
- border: 1px solid #d0d0d0 !important;
435
- border-radius: 8px !important;
436
- font-size: 0.95rem !important;
437
- padding: 0.7rem !important;
438
- }
439
- .gr-input:focus, .gr-textarea:focus {
440
- border-color: #ffd700 !important;
441
- box-shadow: 0 0 0 3px rgba(255, 215, 0, 0.1) !important;
442
- }
443
- .image-container {
444
- border-radius: 10px !important;
445
- overflow: hidden;
446
- border: 1px solid #e0e0e0 !important;
447
- }
448
- footer {
449
- display: none !important;
450
- }
451
- """
452
-
453
- # Gradio 인터페이스 생성
454
- with gr.Blocks(css=css, theme=gr.themes.Base()) as demo:
455
- with gr.Column(elem_classes="header-container"):
456
- gr.HTML("""
457
- <h1 class="logo-text">🏭 제품 디자인 스튜디오</h1>
458
- <p class="subtitle">AI 기반 산업 디자인 시스템 - 웹 리서치와 주석 기능 포함</p>
459
- <div class="mode-indicator">
460
- 👥 감독 → 🔍 엔지니어 (Brave 검색) → 🎨 디자이너 (텍스트 주석 포함)
461
- </div>
462
- """)
463
-
464
- with gr.Column(elem_classes="main-content"):
465
- gr.HTML("""
466
- <div class="info-box">
467
- <strong>🎯 전문 제품 디자인 프로세스 (주석 포함):</strong><br>
468
- • <b>감독:</b> 비전과 요구사항 수립<br>
469
- • <b>엔지니어:</b> Brave API로 최신 트렌드와 기술 검색<br>
470
- • <b>디자이너:</b> <b>텍스트 레이블과 기능 설명</b>이 포함된 시각 사양 작성<br>
471
- • <b>결과물:</b> 주요 기능이 강조된 주석 포함 제품 디자인<br>
472
- • <b>집중 분야:</b> 인포그래픽 스타일 주석이 포함된 물리적 제품
473
- </div>
474
- """)
475
-
476
- with gr.Row(equal_height=True):
477
- with gr.Column(scale=1):
478
- prompt = gr.Textbox(
479
- label="📝 제품 컨셉",
480
- placeholder="제품 유형 입력: '스마트 운동화', '미래형 주방용품', '친환경 가방', '모듈형 가구'...",
481
- lines=2,
482
- value="차세대 무선 이어폰",
483
- elem_classes="prompt-input"
484
- )
485
-
486
- enhance_prompt_checkbox = gr.Checkbox(
487
- label="🚀 웹 리서치를 통한 팀 협업 활성화",
488
- value=True,
489
- info="감독 + 엔지니어(Brave 검색) + 디자이너 프로세스 활성화"
490
- )
491
-
492
- with gr.Row():
493
- image1 = gr.Image(
494
- label="스타일 참조 1 (선택사항)",
495
- type="pil",
496
- height=180
497
- )
498
- image2 = gr.Image(
499
- label="스타일 참조 2 (선택사항)",
500
- type="pil",
501
- height=180
502
- )
503
-
504
- generate_btn = gr.Button(
505
- "🎨 제품 디자인 생성",
506
- variant="primary",
507
- size="lg"
508
- )
509
-
510
- with gr.Column(scale=1):
511
- output_image = gr.Image(
512
- label="생성된 제품 디자인",
513
- type="pil",
514
- height=400,
515
- elem_classes="image-container"
516
- )
517
-
518
- enhanced_prompt_display = gr.Textbox(
519
- label="📋 최종 디자인 사양",
520
- interactive=False,
521
- lines=3,
522
- elem_classes="enhanced-prompt-box"
523
- )
524
-
525
- status = gr.Textbox(
526
- label="상태",
527
- interactive=False,
528
- elem_classes="status-text",
529
- value="디자인 준비 중..."
530
- )
531
-
532
- with gr.Row():
533
- team_discussion_display = gr.Markdown(
534
- value="",
535
- elem_classes="team-discussion"
536
- )
537
-
538
- # 이벤트 핸들러 연결
539
- generate_btn.click(
540
- fn=process_product_design,
541
- inputs=[prompt, enhance_prompt_checkbox, image1, image2],
542
- outputs=[output_image, enhanced_prompt_display, status, team_discussion_display]
543
- )
544
-
545
- # 창의적인 한글 제품 예시
546
- gr.Examples(
547
- examples=[
548
- ["공중 부양 스피커", True, None, None],
549
- ["변형 가능한 다목적 가구", True, None, None],
550
- ["자가 충전 스마트 신발", True, None, None],
551
- ["홀로그램 디스플레이 시계", True, None, None],
552
- ["접이식 전기 스쿠터 헬멧", True, None, None],
553
- ["AI 요리 도우미 로봇", True, None, None],
554
- ["투명 OLED 노트북", True, None, None],
555
- ["생체인식 스마트 도어락", True, None, None],
556
- ["모듈형 캠핑 장비 시스템", True, None, None],
557
- ["웨어러블 공기청정기", True, None, None],
558
- ["자동 온도조절 텀블러", True, None, None],
559
- ["미래형 반려동물 케어 스테이션", True, None, None],
560
- ],
561
- inputs=[prompt, enhance_prompt_checkbox, image1, image2],
562
- label="💡 창의적인 제품 디자인 예시"
563
- )
564
 
565
- # 실행 설정
566
  if __name__ == "__main__":
567
- # 필요한 API 키 확인
568
- if not os.getenv('REPLICATE_API_TOKEN'):
569
- print("⚠️ 경고: REPLICATE_API_TOKEN이 설정되지 않음")
570
- if not os.getenv('FIREWORKS_API_KEY'):
571
- print("⚠️ 경고: FIREWORKS_API_KEY가 설정되지 않음 - 폴백 프롬프트 사용")
572
- if not os.getenv('BRAVE_API_KEY'):
573
- print("⚠️ 경고: BRAVE_API_KEY가 설정되지 않음 - 웹 검색 불가")
574
-
575
- demo.launch(
576
- share=False, # Hugging Face Spaces용으로 False 설정
577
- server_name="0.0.0.0",
578
- server_port=7860,
579
- ssr_mode=False # 경고 방지를 위해 SSR 비활성화
580
- )
 
 
 
1
  import os
2
+ import sys
3
+ import streamlit as st
4
+ from tempfile import NamedTemporaryFile
 
 
 
5
 
6
+ def main():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  try:
8
+ # Get the code from secrets
9
+ code = os.environ.get("MAIN_CODE")
 
 
 
10
 
11
+ if not code:
12
+ st.error("⚠️ The application code wasn't found in secrets. Please add the MAIN_CODE secret.")
13
+ return
 
 
 
 
 
14
 
15
+ # Create a temporary Python file
16
+ with NamedTemporaryFile(suffix='.py', delete=False, mode='w') as tmp:
17
+ tmp.write(code)
18
+ tmp_path = tmp.name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ # Execute the code
21
+ exec(compile(code, tmp_path, 'exec'), globals())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Clean up the temporary file
24
  try:
25
+ os.unlink(tmp_path)
 
 
 
 
 
 
 
 
 
 
 
 
26
  except:
27
+ pass
 
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  except Exception as e:
30
+ st.error(f"⚠️ Error loading or executing the application: {str(e)}")
31
+ import traceback
32
+ st.code(traceback.format_exc())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
 
34
  if __name__ == "__main__":
35
+ main()