openfree commited on
Commit
356a23a
ยท
verified ยท
1 Parent(s): 3dc0b12

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -123
app.py CHANGED
@@ -161,7 +161,6 @@ os.environ["TRANSFORMERS_CACHE"] = cache_path
161
  os.environ["HF_HUB_CACHE"] = cache_path
162
  os.environ["HF_HOME"] = cache_path
163
 
164
-
165
  # Hugging Face ํ† ํฐ ์„ค์ •
166
  HF_TOKEN = os.getenv("HF_TOKEN")
167
  if not HF_TOKEN:
@@ -190,8 +189,6 @@ try:
190
  except Exception as e:
191
  print(f"Error initializing FLUX model: {str(e)}")
192
  pipe = None
193
-
194
-
195
 
196
  # ์ด๋ฏธ์ง€ ์ƒ์„ฑ ํ•จ์ˆ˜ ์ถ”๊ฐ€
197
  @spaces.GPU
@@ -441,18 +438,17 @@ class Demo:
441
  if not query or query.strip() == '':
442
  query = get_random_placeholder()
443
 
444
- # ํŒŒ์ผ ๋ถ„์„ ๊ฒฐ๊ณผ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ ์ปจํ…์ŠคํŠธ๋กœ ์ถ”๊ฐ€
445
- context = ""
446
- if self.last_analysis: # self.file_state ๋Œ€์‹  ์ง์ ‘ self.last_analysis ์‚ฌ์šฉ
447
- context = "Based on the uploaded files:\n"
448
- for filename, analysis in self.last_analysis.items():
449
- context += f"\nFile '{filename}':\n{analysis}\n"
450
- query = f"{context}\n\nUser Query: {query}"
451
-
452
- # ์ด๋ฏธ์ง€ ์ƒ์„ฑ์ด ํ•„์š”ํ•œ์ง€ ํ™•์ธ
453
  needs_image = '์ด๋ฏธ์ง€' in query or '๊ทธ๋ฆผ' in query or 'image' in query.lower()
454
  image_prompt = None
455
-
456
  if needs_image:
457
  for keyword in ['์ด๋ฏธ์ง€:', '๊ทธ๋ฆผ:', 'image:']:
458
  if keyword in query.lower():
@@ -463,12 +459,11 @@ class Demo:
463
 
464
  messages = [{'role': Role.SYSTEM, 'content': _setting['system']}]
465
  messages.append({'role': Role.USER, 'content': query})
466
-
467
  system_message = messages[0]['content']
468
  claude_messages = [{"role": "user", "content": query}]
469
 
470
- # ์—…๋กœ๋“œ๋œ ์ด๋ฏธ์ง€๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ Claude API ๋ฉ”์‹œ์ง€์— ์ถ”๊ฐ€
471
- for filename, file in self.uploaded_files.items(): # self.file_state ๋Œ€์‹  ์ง์ ‘ self.uploaded_files ์‚ฌ์šฉ
472
  if any(filename.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']):
473
  try:
474
  image = Image.open(file)
@@ -518,10 +513,8 @@ class Demo:
518
  ]
519
  await asyncio.sleep(0)
520
  collected_content = content
521
-
522
  except Exception as claude_error:
523
  print(f"Falling back to OpenAI API due to Claude error: {str(claude_error)}")
524
-
525
  async for content in try_openai_api(openai_messages):
526
  yield [
527
  "",
@@ -533,88 +526,13 @@ class Demo:
533
  collected_content = content
534
 
535
  if collected_content:
536
- # ์ด๋ฏธ์ง€ ์ƒ์„ฑ์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ
537
- if needs_image and image_prompt:
538
- try:
539
- print(f"Generating image for prompt: {image_prompt}")
540
- if pipe is not None:
541
- image = generate_image(
542
- prompt=image_prompt,
543
- height=512,
544
- width=512,
545
- steps=8,
546
- scales=3.5,
547
- seed=random.randint(1, 10000)
548
- )
549
-
550
- buffered = BytesIO()
551
- image.save(buffered, format="PNG")
552
- img_str = base64.b64encode(buffered.getvalue()).decode()
553
-
554
- image_html = f'''
555
- <div class="generated-image" style="margin: 20px 0; text-align: center;">
556
- <h3 style="color: #333; margin-bottom: 10px;">Generated Image:</h3>
557
- <img src="data:image/png;base64,{img_str}"
558
- style="max-width: 100%;
559
- border-radius: 10px;
560
- box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
561
- <p style="color: #666; margin-top: 10px; font-style: italic;">
562
- Prompt: {html.escape(image_prompt)}
563
- </p>
564
- </div>
565
- '''
566
-
567
- if '```html' in collected_content:
568
- collected_content = collected_content.replace('```html\n', f'```html\n{image_html}')
569
- else:
570
- collected_content = f'```html\n{image_html}\n```\n{collected_content}'
571
-
572
- print("Image generation successful")
573
- else:
574
- raise Exception("FLUX model not initialized")
575
-
576
- except Exception as e:
577
- print(f"Image generation error: {str(e)}")
578
- error_message = f'''
579
- <div style="color: #ff4d4f; padding: 10px; margin: 10px 0;
580
- border-left: 4px solid #ff4d4f; background: #fff2f0;">
581
- <p>Failed to generate image: {str(e)}</p>
582
- </div>
583
- '''
584
- if '```html' in collected_content:
585
- collected_content = collected_content.replace('```html\n', f'```html\n{error_message}')
586
- else:
587
- collected_content = f'```html\n{error_message}\n```\n{collected_content}'
588
-
589
- # ์—…๋กœ๋“œ๋œ ์ด๋ฏธ์ง€ ํ‘œ์‹œ
590
- for filename, file in self.uploaded_files.items():
591
- if any(filename.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']):
592
- try:
593
- image = Image.open(file)
594
- buffered = BytesIO()
595
- image.save(buffered, format=image.format)
596
- img_str = base64.b64encode(buffered.getvalue()).decode()
597
-
598
- uploaded_image_html = f'''
599
- <div class="uploaded-image" style="margin: 20px 0; text-align: center;">
600
- <h3 style="color: #333; margin-bottom: 10px;">Uploaded Image: {html.escape(filename)}</h3>
601
- <img src="data:image/{image.format.lower()};base64,{img_str}"
602
- style="max-width: 100%;
603
- border-radius: 10px;
604
- box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
605
- </div>
606
- '''
607
-
608
- if '```html' in collected_content:
609
- collected_content = collected_content.replace('```html\n', f'```html\n{uploaded_image_html}')
610
- else:
611
- collected_content = f'```html\n{uploaded_image_html}\n```\n{collected_content}'
612
- except Exception as e:
613
- print(f"Error displaying uploaded image: {str(e)}")
614
-
615
  yield [
616
- collected_content,
617
- send_to_sandbox(remove_code_block(collected_content)),
618
  gr.update(active_key="render"),
619
  gr.update(open=False)
620
  ]
@@ -635,8 +553,8 @@ class Demo:
635
  return "No files uploaded"
636
 
637
  results = []
638
- self.last_analysis.clear() # file_state.last_analysis ๋Œ€์‹  ์ง์ ‘ ์ฐธ์กฐ
639
- self.uploaded_files.clear() # file_state.uploaded_files ๋Œ€์‹  ์ง์ ‘ ์ฐธ์กฐ
640
 
641
  for file in files:
642
  try:
@@ -714,10 +632,6 @@ class Demo:
714
  self.uploaded_files.clear()
715
  return []
716
 
717
-
718
-
719
-
720
-
721
  def update_file_state(self, analysis_result, files):
722
  """ํŒŒ์ผ ๋ถ„์„ ๊ฒฐ๊ณผ์™€ ํŒŒ์ผ ๊ฐ์ฒด ์—…๋ฐ์ดํŠธ"""
723
  self.file_state.last_analysis.update(analysis_result)
@@ -744,6 +658,7 @@ def send_to_sandbox(code):
744
  frameborder="0"
745
  ></iframe>
746
  """
 
747
  # ๋ฐฐํฌ ๊ด€๋ จ ํ•จ์ˆ˜ ์ถ”๊ฐ€
748
  def generate_space_name():
749
  """6์ž๋ฆฌ ๋žœ๋ค ์˜๋ฌธ ์ด๋ฆ„ ์ƒ์„ฑ"""
@@ -759,7 +674,6 @@ def deploy_to_vercel(code: str):
759
  # 6์ž๋ฆฌ ์˜๋ฌธ ํ”„๋กœ์ ํŠธ ์ด๋ฆ„ ์ƒ์„ฑ
760
  project_name = ''.join(random.choice(string.ascii_lowercase) for i in range(6))
761
 
762
-
763
  # Vercel API ์—”๋“œํฌ์ธํŠธ
764
  deploy_url = "https://api.vercel.com/v13/deployments"
765
 
@@ -773,7 +687,7 @@ def deploy_to_vercel(code: str):
773
  package_json = {
774
  "name": project_name,
775
  "version": "1.0.0",
776
- "private": True, # true -> True๋กœ ์ˆ˜์ •
777
  "dependencies": {
778
  "vite": "^5.0.0"
779
  },
@@ -792,7 +706,7 @@ def deploy_to_vercel(code: str):
792
  },
793
  {
794
  "file": "package.json",
795
- "data": json.dumps(package_json, indent=2) # indent ์ถ”๊ฐ€๋กœ ๊ฐ€๋…์„ฑ ํ–ฅ์ƒ
796
  }
797
  ]
798
 
@@ -812,7 +726,6 @@ def deploy_to_vercel(code: str):
812
  "projectSettings": project_settings
813
  }
814
 
815
-
816
  deploy_response = requests.post(deploy_url, headers=headers, json=deploy_data)
817
 
818
  if deploy_response.status_code != 200:
@@ -1178,8 +1091,6 @@ def create_main_interface():
1178
  # ์ขŒ์ธก ํŒจ๋„
1179
  with antd.Col(span=24, md=8):
1180
  with antd.Flex(vertical=True, gap="middle", wrap=True):
1181
- # macOS ์Šคํƒ€์ผ ์œˆ๋„์šฐ ํ—ค๋”
1182
- # macOS ์Šคํƒ€์ผ ์œˆ๋„์šฐ ํ—ค๋”
1183
  header = gr.HTML("""
1184
  <div class="window-frame">
1185
  <div class="window-header">
@@ -1204,7 +1115,6 @@ Use the "Generate" button for basic creation, "Enhance" button for prompt improv
1204
  </div>
1205
  """.format(get_image_base64('mouse.gif')))
1206
 
1207
-
1208
  # ํŒŒ์ผ ์—…๋กœ๋“œ ์„น์…˜
1209
  with gr.Group(elem_classes="file-upload-section"):
1210
  file_upload = gr.File(
@@ -1296,18 +1206,16 @@ Use the "Generate" button for basic creation, "Enhance" button for prompt improv
1296
  with antd.Tabs.Item(key="render"):
1297
  sandbox = gr.HTML(elem_classes="html_content")
1298
 
1299
-
1300
  demo_instance = Demo() # Demo ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
1301
 
1302
-
1303
- # ํŒŒ์ผ ์—…๋กœ๋“œ ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
1304
  analyze_btn.click(
1305
- fn=demo_instance.handle_file_upload, # Demo ์ธ์Šคํ„ด์Šค์˜ ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ
1306
  inputs=[file_upload],
1307
  outputs=[file_analysis]
1308
  )
1309
 
1310
- # Generate ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
1311
  btn.click(
1312
  fn=demo_instance.generation_code,
1313
  inputs=[input, setting],
@@ -1318,7 +1226,6 @@ Use the "Generate" button for basic creation, "Enhance" button for prompt improv
1318
  outputs=[input]
1319
  )
1320
 
1321
-
1322
  boost_btn.click(
1323
  fn=handle_boost,
1324
  inputs=[input],
@@ -1420,16 +1327,13 @@ Use the "Generate" button for basic creation, "Enhance" button for prompt improv
1420
 
1421
  return demo
1422
 
1423
-
1424
-
1425
-
1426
  # ๋ฉ”์ธ ์‹คํ–‰ ๋ถ€๋ถ„
1427
  if __name__ == "__main__":
1428
  try:
1429
  demo_instance = Demo() # Demo ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
1430
  demo = create_main_interface() # ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ
1431
  demo.queue(
1432
- default_concurrency_limit=20, # concurrency_count ๋Œ€์‹  default_concurrency_limit ์‚ฌ์šฉ
1433
  status_update_rate=10,
1434
  api_open=False
1435
  ).launch(
@@ -1440,4 +1344,4 @@ if __name__ == "__main__":
1440
  )
1441
  except Exception as e:
1442
  print(f"Initialization error: {e}")
1443
- raise
 
161
  os.environ["HF_HUB_CACHE"] = cache_path
162
  os.environ["HF_HOME"] = cache_path
163
 
 
164
  # Hugging Face ํ† ํฐ ์„ค์ •
165
  HF_TOKEN = os.getenv("HF_TOKEN")
166
  if not HF_TOKEN:
 
189
  except Exception as e:
190
  print(f"Error initializing FLUX model: {str(e)}")
191
  pipe = None
 
 
192
 
193
  # ์ด๋ฏธ์ง€ ์ƒ์„ฑ ํ•จ์ˆ˜ ์ถ”๊ฐ€
194
  @spaces.GPU
 
438
  if not query or query.strip() == '':
439
  query = get_random_placeholder()
440
 
441
+ # ํŒŒ์ผ ๋ถ„์„ ๊ฒฐ๊ณผ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ์—๋„ ์ถœ๋ ฅ ๊ฒฐ๊ณผ์— ํฌํ•จํ•˜์ง€ ์•Š์Œ
442
+ # context = ""
443
+ # if self.last_analysis:
444
+ # context = "Based on the uploaded files:\n" + "\n".join(
445
+ # [f"\nFile '{filename}':\n{analysis}" for filename, analysis in self.last_analysis.items()]
446
+ # )
447
+ # query = f"{context}\n\nUser Query: {query}"
448
+
449
+ # ์ด๋ฏธ์ง€ ๊ด€๋ จ ์ฒ˜๋ฆฌ๋Š” ๋‚ด๋ถ€ API ํ˜ธ์ถœ์—๋งŒ ์‚ฌ์šฉํ•˜๊ณ  ์ถœ๋ ฅ ๊ฒฐ๊ณผ์—๋Š” ๋ฐ˜์˜ํ•˜์ง€ ์•Š์Œ
450
  needs_image = '์ด๋ฏธ์ง€' in query or '๊ทธ๋ฆผ' in query or 'image' in query.lower()
451
  image_prompt = None
 
452
  if needs_image:
453
  for keyword in ['์ด๋ฏธ์ง€:', '๊ทธ๋ฆผ:', 'image:']:
454
  if keyword in query.lower():
 
459
 
460
  messages = [{'role': Role.SYSTEM, 'content': _setting['system']}]
461
  messages.append({'role': Role.USER, 'content': query})
 
462
  system_message = messages[0]['content']
463
  claude_messages = [{"role": "user", "content": query}]
464
 
465
+ # ์—…๋กœ๋“œ๋œ ํŒŒ์ผ์ด ์ด๋ฏธ์ง€์ธ ๊ฒฝ์šฐ์—๋„ ๋‚ด๋ถ€ API ํ˜ธ์ถœ์—๋งŒ ์‚ฌ์šฉํ•˜๊ณ  ์ถœ๋ ฅ์—๋Š” ๋ฐ˜์˜ํ•˜์ง€ ์•Š์Œ
466
+ for filename, file in self.uploaded_files.items():
467
  if any(filename.lower().endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']):
468
  try:
469
  image = Image.open(file)
 
513
  ]
514
  await asyncio.sleep(0)
515
  collected_content = content
 
516
  except Exception as claude_error:
517
  print(f"Falling back to OpenAI API due to Claude error: {str(claude_error)}")
 
518
  async for content in try_openai_api(openai_messages):
519
  yield [
520
  "",
 
526
  collected_content = content
527
 
528
  if collected_content:
529
+ # ์ตœ์ข… ์ถœ๋ ฅ ์‹œ, API ์‘๋‹ต ๋‚ด์šฉ์„ ์ „๋ถ€ ์ดˆ๊ธฐํ™”ํ•˜์—ฌ
530
+ # ์—…๋กœ๋“œํ•œ ์ด๋ฏธ์ง€, ํ”„๋กฌํ”„ํŠธ ์ž…๋ ฅ, ๊ทธ๋ฆฌ๊ณ  ์ถœ๋ ฅ ํ…์ŠคํŠธ๊ฐ€ ์ „ํ˜€ ๋ฐ˜์˜๋˜์ง€ ์•Š๋„๋ก ํ•จ.
531
+ collected_content = ""
532
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
533
  yield [
534
+ collected_content, # ๋นˆ ๋ฌธ์ž์—ด ๋ฐ˜ํ™˜
535
+ send_to_sandbox(""), # sandbox์—๋„ ๋นˆ HTML ์ฝ”๋“œ ์ „๋‹ฌ
536
  gr.update(active_key="render"),
537
  gr.update(open=False)
538
  ]
 
553
  return "No files uploaded"
554
 
555
  results = []
556
+ self.last_analysis.clear()
557
+ self.uploaded_files.clear()
558
 
559
  for file in files:
560
  try:
 
632
  self.uploaded_files.clear()
633
  return []
634
 
 
 
 
 
635
  def update_file_state(self, analysis_result, files):
636
  """ํŒŒ์ผ ๋ถ„์„ ๊ฒฐ๊ณผ์™€ ํŒŒ์ผ ๊ฐ์ฒด ์—…๋ฐ์ดํŠธ"""
637
  self.file_state.last_analysis.update(analysis_result)
 
658
  frameborder="0"
659
  ></iframe>
660
  """
661
+
662
  # ๋ฐฐํฌ ๊ด€๋ จ ํ•จ์ˆ˜ ์ถ”๊ฐ€
663
  def generate_space_name():
664
  """6์ž๋ฆฌ ๋žœ๋ค ์˜๋ฌธ ์ด๋ฆ„ ์ƒ์„ฑ"""
 
674
  # 6์ž๋ฆฌ ์˜๋ฌธ ํ”„๋กœ์ ํŠธ ์ด๋ฆ„ ์ƒ์„ฑ
675
  project_name = ''.join(random.choice(string.ascii_lowercase) for i in range(6))
676
 
 
677
  # Vercel API ์—”๋“œํฌ์ธํŠธ
678
  deploy_url = "https://api.vercel.com/v13/deployments"
679
 
 
687
  package_json = {
688
  "name": project_name,
689
  "version": "1.0.0",
690
+ "private": True,
691
  "dependencies": {
692
  "vite": "^5.0.0"
693
  },
 
706
  },
707
  {
708
  "file": "package.json",
709
+ "data": json.dumps(package_json, indent=2)
710
  }
711
  ]
712
 
 
726
  "projectSettings": project_settings
727
  }
728
 
 
729
  deploy_response = requests.post(deploy_url, headers=headers, json=deploy_data)
730
 
731
  if deploy_response.status_code != 200:
 
1091
  # ์ขŒ์ธก ํŒจ๋„
1092
  with antd.Col(span=24, md=8):
1093
  with antd.Flex(vertical=True, gap="middle", wrap=True):
 
 
1094
  header = gr.HTML("""
1095
  <div class="window-frame">
1096
  <div class="window-header">
 
1115
  </div>
1116
  """.format(get_image_base64('mouse.gif')))
1117
 
 
1118
  # ํŒŒ์ผ ์—…๋กœ๋“œ ์„น์…˜
1119
  with gr.Group(elem_classes="file-upload-section"):
1120
  file_upload = gr.File(
 
1206
  with antd.Tabs.Item(key="render"):
1207
  sandbox = gr.HTML(elem_classes="html_content")
1208
 
 
1209
  demo_instance = Demo() # Demo ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
1210
 
1211
+ # ํŒŒ์ผ ์—…๋กœ๋“œ ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
 
1212
  analyze_btn.click(
1213
+ fn=demo_instance.handle_file_upload,
1214
  inputs=[file_upload],
1215
  outputs=[file_analysis]
1216
  )
1217
 
1218
+ # Generate ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
1219
  btn.click(
1220
  fn=demo_instance.generation_code,
1221
  inputs=[input, setting],
 
1226
  outputs=[input]
1227
  )
1228
 
 
1229
  boost_btn.click(
1230
  fn=handle_boost,
1231
  inputs=[input],
 
1327
 
1328
  return demo
1329
 
 
 
 
1330
  # ๋ฉ”์ธ ์‹คํ–‰ ๋ถ€๋ถ„
1331
  if __name__ == "__main__":
1332
  try:
1333
  demo_instance = Demo() # Demo ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
1334
  demo = create_main_interface() # ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ
1335
  demo.queue(
1336
+ default_concurrency_limit=20,
1337
  status_update_rate=10,
1338
  api_open=False
1339
  ).launch(
 
1344
  )
1345
  except Exception as e:
1346
  print(f"Initialization error: {e}")
1347
+ raise