akhaliq HF Staff commited on
Commit
b916e5a
·
1 Parent(s): 42960dd

remove unused code

Browse files
Files changed (1) hide show
  1. app.py +7 -260
app.py CHANGED
@@ -2249,7 +2249,6 @@ for _m in AVAILABLE_MODELS:
2249
  break
2250
  if DEFAULT_MODEL is None and AVAILABLE_MODELS:
2251
  DEFAULT_MODEL = AVAILABLE_MODELS[0]
2252
- DEMO_LIST = []
2253
 
2254
  # HF Inference Client
2255
  HF_TOKEN = os.getenv('HF_TOKEN')
@@ -2440,22 +2439,6 @@ def history_to_messages(history: History, system: str) -> Messages:
2440
  messages.append({'role': 'assistant', 'content': h[1]})
2441
  return messages
2442
 
2443
- def messages_to_history(messages: Messages) -> Tuple[str, History]:
2444
- assert messages[0]['role'] == 'system'
2445
- history = []
2446
- for q, r in zip(messages[1::2], messages[2::2]):
2447
- # Extract text content from multimodal messages for history
2448
- user_content = q['content']
2449
- if isinstance(user_content, list):
2450
- text_content = ""
2451
- for item in user_content:
2452
- if isinstance(item, dict) and item.get("type") == "text":
2453
- text_content += item.get("text", "")
2454
- user_content = text_content if text_content else str(user_content)
2455
-
2456
- history.append([user_content, r['content']])
2457
- return history
2458
-
2459
  def history_to_chatbot_messages(history: History) -> List[Dict[str, str]]:
2460
  """Convert history tuples to chatbot message format"""
2461
  messages = []
@@ -2997,35 +2980,6 @@ def history_render(history: History):
2997
  def clear_history():
2998
  return [], [], None, "" # Empty lists for both tuple format and chatbot messages, None for file, empty string for website URL
2999
 
3000
- def update_image_input_visibility(model):
3001
- """Update image input visibility based on selected model"""
3002
- is_ernie_vl = model.get("id") == "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT"
3003
- is_glm_vl = model.get("id") == "THUDM/GLM-4.1V-9B-Thinking"
3004
- is_glm_45v = model.get("id") == "zai-org/GLM-4.5V"
3005
- return gr.update(visible=is_ernie_vl or is_glm_vl or is_glm_45v)
3006
-
3007
- def process_image_for_model(image):
3008
- """Convert image to base64 for model input"""
3009
- if image is None:
3010
- return None
3011
-
3012
- # Convert numpy array to PIL Image if needed
3013
- import io
3014
- import base64
3015
- import numpy as np
3016
- from PIL import Image
3017
-
3018
- # Handle numpy array from Gradio
3019
- if isinstance(image, np.ndarray):
3020
- image = Image.fromarray(image)
3021
-
3022
- buffer = io.BytesIO()
3023
- image.save(buffer, format='PNG')
3024
- img_str = base64.b64encode(buffer.getvalue()).decode('utf-8')
3025
- return f"data:image/png;base64,{img_str}"
3026
-
3027
-
3028
-
3029
  def create_multimodal_message(text, image=None):
3030
  """Create a chat message. For broad provider compatibility, always return content as a string.
3031
 
@@ -3299,57 +3253,6 @@ def send_to_sandbox(code):
3299
  iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
3300
  return iframe
3301
 
3302
- def send_to_sandbox_with_refresh(code):
3303
- """Render HTML in a sandboxed iframe with cache-busting for media generation updates."""
3304
- import time
3305
- html_doc = (code or "").strip()
3306
- # For preview only: inline local file URLs as data URIs so the
3307
- # data: iframe can load them. The original code (shown to the user) still contains file URLs.
3308
- try:
3309
- import re
3310
- import base64 as _b64
3311
- import mimetypes as _mtypes
3312
- import urllib.parse as _uparse
3313
- def _file_url_to_data_uri(file_url: str) -> str | None:
3314
- try:
3315
- parsed = _uparse.urlparse(file_url)
3316
- path = _uparse.unquote(parsed.path)
3317
- if not path:
3318
- return None
3319
- with open(path, 'rb') as _f:
3320
- raw = _f.read()
3321
- mime = _mtypes.guess_type(path)[0] or 'application/octet-stream'
3322
-
3323
- b64 = _b64.b64encode(raw).decode()
3324
- return f"data:{mime};base64,{b64}"
3325
- except Exception as e:
3326
- print(f"[Sandbox] Failed to convert file URL to data URI: {str(e)}")
3327
- return None
3328
- def _repl_double(m):
3329
- url = m.group(1)
3330
- data_uri = _file_url_to_data_uri(url)
3331
- return f'src="{data_uri}"' if data_uri else m.group(0)
3332
- def _repl_single(m):
3333
- url = m.group(1)
3334
- data_uri = _file_url_to_data_uri(url)
3335
- return f"src='{data_uri}'" if data_uri else m.group(0)
3336
- html_doc = re.sub(r'src="(file:[^"]+)"', _repl_double, html_doc)
3337
- html_doc = re.sub(r"src='(file:[^']+)'", _repl_single, html_doc)
3338
-
3339
- except Exception:
3340
- # Best-effort; continue without inlining
3341
- pass
3342
-
3343
- # Add cache-busting timestamp to force iframe refresh when content changes
3344
- timestamp = str(int(time.time() * 1000))
3345
- cache_bust_comment = f"<!-- refresh-{timestamp} -->"
3346
- html_doc = cache_bust_comment + html_doc
3347
-
3348
- encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8')
3349
- data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
3350
- iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture" key="preview-{timestamp}"></iframe>'
3351
- return iframe
3352
-
3353
  def is_streamlit_code(code: str) -> bool:
3354
  """Heuristic check to determine if Python code is a Streamlit app."""
3355
  if not code:
@@ -3599,34 +3502,6 @@ def send_gradio_to_lite(code: str) -> str:
3599
  iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
3600
  return iframe
3601
 
3602
- def demo_card_click(e: gr.EventData):
3603
- try:
3604
- # Get the index from the event data
3605
- if hasattr(e, '_data') and e._data:
3606
- # Try different ways to get the index
3607
- if 'index' in e._data:
3608
- index = e._data['index']
3609
- elif 'component' in e._data and 'index' in e._data['component']:
3610
- index = e._data['component']['index']
3611
- elif 'target' in e._data and 'index' in e._data['target']:
3612
- index = e._data['target']['index']
3613
- else:
3614
- # If we can't get the index, try to extract it from the card data
3615
- index = 0
3616
- else:
3617
- index = 0
3618
-
3619
- # Ensure index is within bounds
3620
- if index >= len(DEMO_LIST):
3621
- index = 0
3622
-
3623
- return DEMO_LIST[index]['description']
3624
- except (KeyError, IndexError, AttributeError) as e:
3625
- # Return the first demo description as fallback
3626
- return DEMO_LIST[0]['description']
3627
-
3628
-
3629
-
3630
  stop_generation = False
3631
 
3632
 
@@ -4954,23 +4829,6 @@ def prettify_comfyui_json_for_html(json_content: str) -> str:
4954
  print(f"Error prettifying ComfyUI JSON: {e}")
4955
  return json_content
4956
 
4957
- def deploy_to_spaces_static(code):
4958
- if not code or not code.strip():
4959
- return # Do nothing if code is empty
4960
- # Use the HTML code directly for static Spaces
4961
- app_html = wrap_html_in_static_app(code.strip())
4962
- base_url = "https://huggingface.co/new-space"
4963
- params = urllib.parse.urlencode({
4964
- "name": "new-space",
4965
- "sdk": "static"
4966
- })
4967
- files_params = urllib.parse.urlencode({
4968
- "files[0][path]": "index.html",
4969
- "files[0][content]": app_html
4970
- })
4971
- full_url = f"{base_url}?{params}&{files_params}"
4972
- webbrowser.open_new_tab(full_url)
4973
-
4974
  def check_hf_space_url(url: str) -> Tuple[bool, str | None, str | None]:
4975
  """Check if URL is a valid Hugging Face Spaces URL and extract username/project"""
4976
  import re
@@ -5497,16 +5355,6 @@ def _generate_gradio_app_from_diffusers(repo_id: str) -> str:
5497
  " demo.launch()\n"
5498
  )
5499
 
5500
- def _generate_streamlit_wrapper(gradio_code: str) -> str:
5501
- """Convert a simple Gradio app into a Streamlit wrapper by embedding via components if needed.
5502
- If code is already Streamlit, return as is. Otherwise, provide a basic Streamlit UI calling the same pipeline.
5503
- """
5504
- # For now, simply return a minimal placeholder to keep scope tight; prefer Gradio by default.
5505
- return (
5506
- "import streamlit as st\n"
5507
- "st.markdown('This model is best used with a Gradio app in this tool. Switch framework to Gradio for a runnable demo.')\n"
5508
- )
5509
-
5510
  def import_repo_to_app(url: str, framework: str = "Gradio") -> Tuple[str, str, str]:
5511
  """Import a GitHub or HF model repo and return the raw code snippet from README/model card.
5512
 
@@ -5857,33 +5705,6 @@ with gr.Blocks(
5857
 
5858
 
5859
 
5860
- # Collapsed Advanced Commands reference
5861
- with gr.Accordion(label="Advanced Commands", open=False, visible=False) as advanced_commands:
5862
- gr.Markdown(
5863
- value=(
5864
- "### Command Reference\n"
5865
- "- **Language**: 'use streamlit' | 'use gradio' | 'use html'\n"
5866
- "- **Model**: 'model <name>' (exact match to items in the Model dropdown)\n"
5867
- "- **Files**: attach documents or images directly for reference\n"
5868
- "- **Multiple directives**: separate with commas. The first segment is the main build prompt.\n\n"
5869
- "Examples:\n"
5870
- "- anycoder coffee shop website\n"
5871
- "- dashboard ui with minimalist design"
5872
- )
5873
- )
5874
-
5875
- # Theme Selector (hidden for end users, developers can modify code)
5876
- with gr.Column(visible=False):
5877
- theme_dropdown = gr.Dropdown(
5878
- choices=list(THEME_CONFIGS.keys()),
5879
- value=current_theme_name,
5880
- label="Select Theme",
5881
- info="Choose your preferred visual style"
5882
- )
5883
- theme_description = gr.Markdown("")
5884
- apply_theme_btn = gr.Button("Apply Theme", variant="primary", size="sm")
5885
- theme_status = gr.Markdown("")
5886
-
5887
  # Unified Import section
5888
  import_header_md = gr.Markdown("📥 Import Project (Space, GitHub, or Model)", visible=False)
5889
  load_project_url = gr.Textbox(
@@ -5911,28 +5732,12 @@ with gr.Blocks(
5911
  label="Code Language",
5912
  visible=True
5913
  )
5914
- image_input = gr.Image(
5915
- label="UI design image",
5916
- visible=False
5917
- )
5918
  # Removed image generation components
5919
  with gr.Row():
5920
  btn = gr.Button("Generate", variant="secondary", size="lg", scale=2, visible=True, interactive=False)
5921
  clear_btn = gr.Button("Clear", variant="secondary", size="sm", scale=1, visible=True)
5922
  # --- Deploy components (visible by default) ---
5923
  deploy_header_md = gr.Markdown("", visible=False)
5924
- sdk_choices = [
5925
- ("Gradio (Python)", "gradio"),
5926
- ("Streamlit (Python)", "streamlit"),
5927
- ("Static (HTML)", "static"),
5928
- ("Transformers.js", "transformers.js")
5929
- ]
5930
- sdk_dropdown = gr.Dropdown(
5931
- choices=[x[0] for x in sdk_choices],
5932
- value="Static (HTML)",
5933
- label="App SDK",
5934
- visible=False
5935
- )
5936
  deploy_btn = gr.Button("Publish", variant="primary", visible=True)
5937
  deploy_status = gr.Markdown(visible=False, label="Deploy status")
5938
  # --- End move ---
@@ -5946,30 +5751,18 @@ with gr.Blocks(
5946
  visible=True
5947
  )
5948
  provider_state = gr.State("auto")
5949
- quick_start_md = gr.Markdown("**Quick start**", visible=False)
5950
- with gr.Column(visible=False) as quick_examples_col:
5951
- for i, demo_item in enumerate(DEMO_LIST[:3]):
5952
- demo_card = gr.Button(
5953
- value=demo_item['title'],
5954
- variant="secondary",
5955
- size="sm"
5956
- )
5957
- demo_card.click(
5958
- fn=lambda idx=i: gr.update(value=DEMO_LIST[idx]['description']),
5959
- outputs=input
5960
- )
5961
  # Removed web search availability indicator
5962
  def on_model_change(model_name):
5963
  for m in AVAILABLE_MODELS:
5964
  if m['name'] == model_name:
5965
- return m, update_image_input_visibility(m)
5966
- return AVAILABLE_MODELS[0], update_image_input_visibility(AVAILABLE_MODELS[0])
5967
  def save_prompt(input):
5968
  return {setting: {"system": input}}
5969
  model_dropdown.change(
5970
  lambda model_name: on_model_change(model_name),
5971
  inputs=model_dropdown,
5972
- outputs=[current_model, image_input]
5973
  )
5974
  # --- Remove deploy/app name/sdk from bottom column ---
5975
  # (delete the gr.Column() block containing space_name_input, sdk_dropdown, deploy_btn, deploy_status)
@@ -6644,8 +6437,8 @@ with gr.Blocks(
6644
  outputs=[sidebar, generating_status],
6645
  show_progress="hidden",
6646
  ).then(
6647
- generation_code,
6648
- inputs=[input, image_input, setting, history, current_model, language_dropdown, provider_state],
6649
  outputs=[code_output, history, history_output]
6650
  ).then(
6651
  end_generation_ui,
@@ -6692,8 +6485,8 @@ with gr.Blocks(
6692
  outputs=[sidebar, generating_status],
6693
  show_progress="hidden",
6694
  ).then(
6695
- generation_code,
6696
- inputs=[input, image_input, setting, history, current_model, language_dropdown, provider_state],
6697
  outputs=[code_output, history, history_output]
6698
  ).then(
6699
  end_generation_ui,
@@ -6766,52 +6559,6 @@ with gr.Blocks(
6766
  outputs=[deploy_btn]
6767
  )
6768
 
6769
- # Theme switching handlers
6770
- def handle_theme_change(theme_name):
6771
- """Handle theme selection change and update description"""
6772
- if theme_name in THEME_CONFIGS:
6773
- description = THEME_CONFIGS[theme_name]["description"]
6774
- features = THEME_FEATURES.get(theme_name, [])
6775
- feature_text = f"**Features:** {', '.join(features)}" if features else ""
6776
- full_description = f"*{description}*\n\n{feature_text}"
6777
-
6778
- return gr.update(value=full_description)
6779
- return gr.update()
6780
-
6781
- def apply_theme_change(theme_name):
6782
- """Save theme preference and show restart instruction"""
6783
- if theme_name in THEME_CONFIGS:
6784
- save_theme_preference(theme_name)
6785
-
6786
- restart_message = f"""
6787
- 🎨 **Theme saved:** {theme_name}
6788
- ⚠️ **Restart required** to fully apply the new theme.
6789
- **Why restart is needed:** Gradio themes are set during application startup and cannot be changed dynamically at runtime. This ensures all components are properly styled with consistent theming.
6790
- **To apply your new theme:**
6791
- 1. Stop the application (Ctrl+C)
6792
- 2. Restart it with the same command
6793
- 3. Your theme will be automatically loaded
6794
-
6795
- *Your theme preference has been saved and will persist across restarts.*
6796
- """
6797
-
6798
- return gr.update(value=restart_message, visible=True, elem_classes=["restart-needed"])
6799
- return gr.update()
6800
-
6801
- # Theme dropdown change event
6802
- theme_dropdown.change(
6803
- handle_theme_change,
6804
- inputs=[theme_dropdown],
6805
- outputs=[theme_description]
6806
- )
6807
-
6808
- # Apply theme button click event
6809
- apply_theme_btn.click(
6810
- apply_theme_change,
6811
- inputs=[theme_dropdown],
6812
- outputs=[theme_status]
6813
- )
6814
-
6815
  # Deploy to Spaces logic
6816
 
6817
  def generate_random_app_name():
 
2249
  break
2250
  if DEFAULT_MODEL is None and AVAILABLE_MODELS:
2251
  DEFAULT_MODEL = AVAILABLE_MODELS[0]
 
2252
 
2253
  # HF Inference Client
2254
  HF_TOKEN = os.getenv('HF_TOKEN')
 
2439
  messages.append({'role': 'assistant', 'content': h[1]})
2440
  return messages
2441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2442
  def history_to_chatbot_messages(history: History) -> List[Dict[str, str]]:
2443
  """Convert history tuples to chatbot message format"""
2444
  messages = []
 
2980
  def clear_history():
2981
  return [], [], None, "" # Empty lists for both tuple format and chatbot messages, None for file, empty string for website URL
2982
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2983
  def create_multimodal_message(text, image=None):
2984
  """Create a chat message. For broad provider compatibility, always return content as a string.
2985
 
 
3253
  iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
3254
  return iframe
3255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3256
  def is_streamlit_code(code: str) -> bool:
3257
  """Heuristic check to determine if Python code is a Streamlit app."""
3258
  if not code:
 
3502
  iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
3503
  return iframe
3504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3505
  stop_generation = False
3506
 
3507
 
 
4829
  print(f"Error prettifying ComfyUI JSON: {e}")
4830
  return json_content
4831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4832
  def check_hf_space_url(url: str) -> Tuple[bool, str | None, str | None]:
4833
  """Check if URL is a valid Hugging Face Spaces URL and extract username/project"""
4834
  import re
 
5355
  " demo.launch()\n"
5356
  )
5357
 
 
 
 
 
 
 
 
 
 
 
5358
  def import_repo_to_app(url: str, framework: str = "Gradio") -> Tuple[str, str, str]:
5359
  """Import a GitHub or HF model repo and return the raw code snippet from README/model card.
5360
 
 
5705
 
5706
 
5707
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5708
  # Unified Import section
5709
  import_header_md = gr.Markdown("📥 Import Project (Space, GitHub, or Model)", visible=False)
5710
  load_project_url = gr.Textbox(
 
5732
  label="Code Language",
5733
  visible=True
5734
  )
 
 
 
 
5735
  # Removed image generation components
5736
  with gr.Row():
5737
  btn = gr.Button("Generate", variant="secondary", size="lg", scale=2, visible=True, interactive=False)
5738
  clear_btn = gr.Button("Clear", variant="secondary", size="sm", scale=1, visible=True)
5739
  # --- Deploy components (visible by default) ---
5740
  deploy_header_md = gr.Markdown("", visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
5741
  deploy_btn = gr.Button("Publish", variant="primary", visible=True)
5742
  deploy_status = gr.Markdown(visible=False, label="Deploy status")
5743
  # --- End move ---
 
5751
  visible=True
5752
  )
5753
  provider_state = gr.State("auto")
 
 
 
 
 
 
 
 
 
 
 
 
5754
  # Removed web search availability indicator
5755
  def on_model_change(model_name):
5756
  for m in AVAILABLE_MODELS:
5757
  if m['name'] == model_name:
5758
+ return m
5759
+ return AVAILABLE_MODELS[0]
5760
  def save_prompt(input):
5761
  return {setting: {"system": input}}
5762
  model_dropdown.change(
5763
  lambda model_name: on_model_change(model_name),
5764
  inputs=model_dropdown,
5765
+ outputs=[current_model]
5766
  )
5767
  # --- Remove deploy/app name/sdk from bottom column ---
5768
  # (delete the gr.Column() block containing space_name_input, sdk_dropdown, deploy_btn, deploy_status)
 
6437
  outputs=[sidebar, generating_status],
6438
  show_progress="hidden",
6439
  ).then(
6440
+ lambda inp, sett, hist, model, lang, prov: generation_code(inp, None, sett, hist, model, lang, prov),
6441
+ inputs=[input, setting, history, current_model, language_dropdown, provider_state],
6442
  outputs=[code_output, history, history_output]
6443
  ).then(
6444
  end_generation_ui,
 
6485
  outputs=[sidebar, generating_status],
6486
  show_progress="hidden",
6487
  ).then(
6488
+ lambda inp, sett, hist, model, lang, prov: generation_code(inp, None, sett, hist, model, lang, prov),
6489
+ inputs=[input, setting, history, current_model, language_dropdown, provider_state],
6490
  outputs=[code_output, history, history_output]
6491
  ).then(
6492
  end_generation_ui,
 
6559
  outputs=[deploy_btn]
6560
  )
6561
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6562
  # Deploy to Spaces logic
6563
 
6564
  def generate_random_app_name():