akhaliq HF Staff commited on
Commit
634b663
Β·
1 Parent(s): c7f26f9

update transformers js deploy

Browse files
Files changed (1) hide show
  1. app.py +88 -14
app.py CHANGED
@@ -5549,6 +5549,63 @@ def check_hf_space_url(url: str) -> Tuple[bool, Optional[str], Optional[str]]:
5549
  return True, username, project_name
5550
  return False, None, None
5551
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5552
  def fetch_hf_space_content(username: str, project_name: str) -> str:
5553
  """Fetch content from a Hugging Face Space"""
5554
  try:
@@ -5559,6 +5616,11 @@ def fetch_hf_space_content(username: str, project_name: str) -> str:
5559
  api = HfApi()
5560
  space_info = api.space_info(f"{username}/{project_name}")
5561
 
 
 
 
 
 
5562
  # Try to fetch the main file based on SDK
5563
  sdk = space_info.sdk
5564
  main_file = None
@@ -6606,7 +6668,8 @@ with gr.Blocks(
6606
  gr.update(value="", visible=False),
6607
  gr.update(value="πŸš€ Deploy App", visible=False),
6608
  gr.update(), # keep import header as-is
6609
- gr.update() # keep import button as-is
 
6610
  ]
6611
 
6612
  kind, meta = _parse_repo_or_model_url(url)
@@ -6616,11 +6679,22 @@ with gr.Blocks(
6616
  is_valid, username, project_name = check_hf_space_url(url)
6617
  space_info = f"{username}/{project_name}" if is_valid else ""
6618
  loaded_history = [[f"Imported Space from {url}", code]]
6619
- # Preview not auto-rendered for imported content
6620
- code_lang = "python" if (is_streamlit_code(code) or is_gradio_code(code)) else "html"
 
 
 
 
 
 
 
 
 
 
 
6621
  return [
6622
  gr.update(value=status, visible=True),
6623
- gr.update(value=code, language=code_lang),
6624
  gr.update(value=""),
6625
  gr.update(value="", visible=False), # hide import textbox after submit
6626
  loaded_history,
@@ -6628,18 +6702,22 @@ with gr.Blocks(
6628
  gr.update(value=space_info, visible=True),
6629
  gr.update(value="Update Existing Space", visible=True),
6630
  gr.update(visible=False), # hide import header
6631
- gr.update(visible=False) # hide import button
 
6632
  ]
6633
  else:
6634
  # GitHub or HF model β†’ return raw snippet for LLM starting point
6635
  status, code, _ = import_repo_to_app(url)
6636
  loaded_history = [[f"Imported Repo/Model from {url}", code]]
6637
  code_lang = "python"
 
6638
  lower = (code or "").lower()
6639
  if code.strip().startswith("<!doctype html>") or code.strip().startswith("<html"):
6640
  code_lang = "html"
 
6641
  elif "```json" in lower:
6642
  code_lang = "json"
 
6643
  return [
6644
  gr.update(value=status, visible=True),
6645
  gr.update(value=code, language=code_lang),
@@ -6650,7 +6728,8 @@ with gr.Blocks(
6650
  gr.update(value="", visible=False),
6651
  gr.update(value="πŸš€ Deploy App", visible=False),
6652
  gr.update(visible=False), # hide import header
6653
- gr.update(visible=False) # hide import button
 
6654
  ]
6655
 
6656
  # Import repo/model handler
@@ -6993,6 +7072,7 @@ with gr.Blocks(
6993
  deploy_btn,
6994
  import_header_md,
6995
  load_project_btn,
 
6996
  ],
6997
  )
6998
 
@@ -7608,14 +7688,8 @@ with gr.Blocks(
7608
  return gr.update(value=f"Error: Could not access space {repo_id} for update.", visible=True)
7609
  except Exception as e:
7610
  return gr.update(value=f"Error: Cannot update space {repo_id}. {str(e)}", visible=True)
7611
- # Build files from multi-file editors if available; fallback to parsing single editor value
7612
- files = {
7613
- 'index.html': tjs_html_code.value if 'tjs_html_code' in locals() else '',
7614
- 'index.js': tjs_js_code.value if 'tjs_js_code' in locals() else '',
7615
- 'style.css': tjs_css_code.value if 'tjs_css_code' in locals() else '',
7616
- }
7617
- if not (files['index.html'] and files['index.js'] and files['style.css']):
7618
- files = parse_transformers_js_output(code)
7619
 
7620
  if not files['index.html'] or not files['index.js'] or not files['style.css']:
7621
  return gr.update(value="Error: Could not parse transformers.js output. Please regenerate the code.", visible=True)
 
5549
  return True, username, project_name
5550
  return False, None, None
5551
 
5552
+ def detect_transformers_js_space(api, username: str, project_name: str) -> bool:
5553
+ """Check if a space is a transformers.js app by looking for the three key files"""
5554
+ try:
5555
+ from huggingface_hub import list_repo_files
5556
+ files = list_repo_files(repo_id=f"{username}/{project_name}", repo_type="space")
5557
+
5558
+ # Check for the three transformers.js files
5559
+ has_index_html = any('index.html' in f for f in files)
5560
+ has_index_js = any('index.js' in f for f in files)
5561
+ has_style_css = any('style.css' in f for f in files)
5562
+
5563
+ return has_index_html and has_index_js and has_style_css
5564
+ except:
5565
+ return False
5566
+
5567
+ def fetch_transformers_js_files(api, username: str, project_name: str) -> dict:
5568
+ """Fetch all three transformers.js files from a space"""
5569
+ files = {}
5570
+ file_names = ['index.html', 'index.js', 'style.css']
5571
+
5572
+ for file_name in file_names:
5573
+ try:
5574
+ content_path = api.hf_hub_download(
5575
+ repo_id=f"{username}/{project_name}",
5576
+ filename=file_name,
5577
+ repo_type="space"
5578
+ )
5579
+
5580
+ with open(content_path, 'r', encoding='utf-8') as f:
5581
+ files[file_name] = f.read()
5582
+ except:
5583
+ files[file_name] = ""
5584
+
5585
+ return files
5586
+
5587
+ def combine_transformers_js_files(files: dict, username: str, project_name: str) -> str:
5588
+ """Combine transformers.js files into the expected format for the LLM"""
5589
+ combined = f"""IMPORTED PROJECT FROM HUGGING FACE SPACE
5590
+ ==============================================
5591
+
5592
+ Space: {username}/{project_name}
5593
+ SDK: static (transformers.js)
5594
+ Type: Transformers.js Application
5595
+
5596
+ """
5597
+
5598
+ if files.get('index.html'):
5599
+ combined += f"=== index.html ===\n{files['index.html']}\n\n"
5600
+
5601
+ if files.get('index.js'):
5602
+ combined += f"=== index.js ===\n{files['index.js']}\n\n"
5603
+
5604
+ if files.get('style.css'):
5605
+ combined += f"=== style.css ===\n{files['style.css']}\n\n"
5606
+
5607
+ return combined
5608
+
5609
  def fetch_hf_space_content(username: str, project_name: str) -> str:
5610
  """Fetch content from a Hugging Face Space"""
5611
  try:
 
5616
  api = HfApi()
5617
  space_info = api.space_info(f"{username}/{project_name}")
5618
 
5619
+ # Check if this is a transformers.js space first
5620
+ if space_info.sdk == "static" and detect_transformers_js_space(api, username, project_name):
5621
+ files = fetch_transformers_js_files(api, username, project_name)
5622
+ return combine_transformers_js_files(files, username, project_name)
5623
+
5624
  # Try to fetch the main file based on SDK
5625
  sdk = space_info.sdk
5626
  main_file = None
 
6668
  gr.update(value="", visible=False),
6669
  gr.update(value="πŸš€ Deploy App", visible=False),
6670
  gr.update(), # keep import header as-is
6671
+ gr.update(), # keep import button as-is
6672
+ gr.update() # language dropdown - no change
6673
  ]
6674
 
6675
  kind, meta = _parse_repo_or_model_url(url)
 
6679
  is_valid, username, project_name = check_hf_space_url(url)
6680
  space_info = f"{username}/{project_name}" if is_valid else ""
6681
  loaded_history = [[f"Imported Space from {url}", code]]
6682
+
6683
+ # Determine the correct language/framework based on the imported content
6684
+ code_lang = "html" # default
6685
+ framework_type = "html" # for language dropdown
6686
+ if is_streamlit_code(code) or is_gradio_code(code):
6687
+ code_lang = "python"
6688
+ framework_type = "python"
6689
+ elif "=== index.html ===" in code and "=== index.js ===" in code and "=== style.css ===" in code:
6690
+ # This is a transformers.js app with the combined format
6691
+ code_lang = "html" # Use html for code display
6692
+ framework_type = "transformers.js" # But set dropdown to transformers.js
6693
+
6694
+ # Return the updates with proper language settings
6695
  return [
6696
  gr.update(value=status, visible=True),
6697
+ gr.update(value=code, language=code_lang), # Use html for transformers.js display
6698
  gr.update(value=""),
6699
  gr.update(value="", visible=False), # hide import textbox after submit
6700
  loaded_history,
 
6702
  gr.update(value=space_info, visible=True),
6703
  gr.update(value="Update Existing Space", visible=True),
6704
  gr.update(visible=False), # hide import header
6705
+ gr.update(visible=False), # hide import button
6706
+ gr.update(value=framework_type) # set language dropdown to framework type
6707
  ]
6708
  else:
6709
  # GitHub or HF model β†’ return raw snippet for LLM starting point
6710
  status, code, _ = import_repo_to_app(url)
6711
  loaded_history = [[f"Imported Repo/Model from {url}", code]]
6712
  code_lang = "python"
6713
+ framework_type = "python"
6714
  lower = (code or "").lower()
6715
  if code.strip().startswith("<!doctype html>") or code.strip().startswith("<html"):
6716
  code_lang = "html"
6717
+ framework_type = "html"
6718
  elif "```json" in lower:
6719
  code_lang = "json"
6720
+ framework_type = "json"
6721
  return [
6722
  gr.update(value=status, visible=True),
6723
  gr.update(value=code, language=code_lang),
 
6728
  gr.update(value="", visible=False),
6729
  gr.update(value="πŸš€ Deploy App", visible=False),
6730
  gr.update(visible=False), # hide import header
6731
+ gr.update(visible=False), # hide import button
6732
+ gr.update(value=framework_type) # set language dropdown to detected language
6733
  ]
6734
 
6735
  # Import repo/model handler
 
7072
  deploy_btn,
7073
  import_header_md,
7074
  load_project_btn,
7075
+ language_dropdown,
7076
  ],
7077
  )
7078
 
 
7688
  return gr.update(value=f"Error: Could not access space {repo_id} for update.", visible=True)
7689
  except Exception as e:
7690
  return gr.update(value=f"Error: Cannot update space {repo_id}. {str(e)}", visible=True)
7691
+ # Parse the code parameter which should contain the formatted transformers.js output
7692
+ files = parse_transformers_js_output(code)
 
 
 
 
 
 
7693
 
7694
  if not files['index.html'] or not files['index.js'] or not files['style.css']:
7695
  return gr.update(value="Error: Could not parse transformers.js output. Please regenerate the code.", visible=True)