akhaliq HF Staff commited on
Commit
000b511
·
1 Parent(s): 8971824

svelte update

Browse files
Files changed (1) hide show
  1. app.py +113 -178
app.py CHANGED
@@ -335,77 +335,67 @@ The style.css should contain all the styling for the application.
335
 
336
  Always output only the three code blocks as shown above, and do not include any explanations or extra text."""
337
 
338
- SVELTE_SYSTEM_PROMPT = """You are an expert Svelte developer creating a modern Svelte application. You will generate ONLY the custom files that need user-specific content for the user's requested application.
339
 
340
- IMPORTANT: You MUST output files in the following format. Generate ONLY the files needed for the user's specific request:
 
 
 
 
341
 
342
- ```svelte
343
- <!-- src/App.svelte content here -->
344
- ```
 
345
 
346
- ```css
347
- /* src/app.css content here */
348
- ```
349
 
350
- If you need additional components for the user's specific app, add them like:
351
- ```svelte
352
- <!-- src/lib/ComponentName.svelte content here -->
353
- ```
354
 
355
  Requirements:
356
  1. Create a modern, responsive Svelte application based on the user's specific request
357
- 2. Use TypeScript for better type safety
358
  3. Create a clean, professional UI with good user experience
359
  4. Make the application fully responsive for mobile devices
360
  5. Use modern CSS practices and Svelte best practices
361
  6. Include proper error handling and loading states
362
  7. Follow accessibility best practices
363
  8. Use Svelte's reactive features effectively
364
- 9. Include proper component structure and organization
365
- 10. Generate ONLY components that are actually needed for the user's requested application
366
-
367
- Files you should generate:
368
- - src/App.svelte: Main application component (ALWAYS required)
369
- - src/app.css: Global styles (ALWAYS required)
370
- - src/lib/[ComponentName].svelte: Additional components (ONLY if needed for the user's specific app)
371
-
372
- The other files (index.html, package.json, vite.config.ts, tsconfig files, svelte.config.js, src/main.ts, src/vite-env.d.ts) are provided by the Svelte template and don't need to be generated.
373
-
374
- Always output only the two code blocks as shown above, and do not include any explanations or extra text."""
375
 
376
- SVELTE_SYSTEM_PROMPT_WITH_SEARCH = """You are an expert Svelte developer creating a modern Svelte application. You have access to real-time web search. When needed, use web search to find the latest information, best practices, or specific Svelte technologies.
377
 
378
- You will generate ONLY the custom files that need user-specific content.
 
 
 
 
379
 
380
- IMPORTANT: You MUST output ONLY the custom files in the following format:
 
 
 
381
 
382
- ```svelte
383
- <!-- src/App.svelte content here -->
384
- ```
385
 
386
- ```css
387
- /* src/app.css content here -->
388
- ```
389
 
390
  Requirements:
391
  1. Create a modern, responsive Svelte application
392
- 2. Use TypeScript for better type safety
393
- 3. Create a clean, professional UI with good user experience
394
- 4. Make the application fully responsive for mobile devices
395
- 5. Use modern CSS practices and Svelte best practices
396
- 6. Include proper error handling and loading states
397
- 7. Follow accessibility best practices
398
- 8. Use Svelte's reactive features effectively
399
- 9. Include proper component structure and organization
400
- 10. Use web search to find the latest Svelte patterns, libraries, and best practices
401
-
402
- The files you generate are:
403
- - src/App.svelte: Main application component (your custom app logic)
404
- - src/app.css: Global styles (your custom styling)
405
-
406
- The other files (index.html, package.json, vite.config.ts, tsconfig files, svelte.config.js, src/main.ts, src/vite-env.d.ts) are provided by the Svelte template and don't need to be generated.
407
-
408
- Always output only the two code blocks as shown above, and do not include any explanations or extra text."""
409
 
410
  TRANSFORMERS_JS_SYSTEM_PROMPT_WITH_SEARCH = """You are an expert web developer creating a transformers.js application. You have access to real-time web search. When needed, use web search to find the latest information, best practices, or specific technologies for transformers.js.
411
 
@@ -1628,48 +1618,37 @@ def extract_html_document(text: str) -> str:
1628
  return text[idx:] if idx != -1 else text
1629
 
1630
  def parse_svelte_output(text):
1631
- """Parse Svelte output to extract individual files"""
1632
- files = {
1633
- 'src/App.svelte': '',
1634
- 'src/app.css': ''
1635
- }
1636
-
 
 
 
 
 
 
 
 
 
 
 
 
1637
  import re
1638
-
1639
- # First try to extract using code block patterns
1640
- svelte_pattern = r'```svelte\s*\n([\s\S]+?)\n```'
1641
- css_pattern = r'```css\s*\n([\s\S]+?)\n```'
1642
-
1643
- # Extract svelte block for App.svelte
1644
- svelte_match = re.search(svelte_pattern, text, re.IGNORECASE)
1645
- css_match = re.search(css_pattern, text, re.IGNORECASE)
1646
-
1647
  if svelte_match:
1648
- files['src/App.svelte'] = svelte_match.group(1).strip()
 
1649
  if css_match:
1650
- files['src/app.css'] = css_match.group(1).strip()
1651
-
1652
- # Fallback: support === filename === format if any file is missing
1653
- if not (files['src/App.svelte'] and files['src/app.css']):
1654
- # Use regex to extract sections
1655
- app_svelte_fallback = re.search(r'===\s*src/App\.svelte\s*===\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE)
1656
- app_css_fallback = re.search(r'===\s*src/app\.css\s*===\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE)
1657
-
1658
- if app_svelte_fallback:
1659
- files['src/App.svelte'] = app_svelte_fallback.group(1).strip()
1660
- if app_css_fallback:
1661
- files['src/app.css'] = app_css_fallback.group(1).strip()
1662
-
1663
- return files
1664
 
1665
  def format_svelte_output(files):
1666
- """Format Svelte files into a single display string"""
1667
- output = []
1668
- output.append("=== src/App.svelte ===")
1669
- output.append(files['src/App.svelte'])
1670
- output.append("\n=== src/app.css ===")
1671
- output.append(files['src/app.css'])
1672
- return '\n'.join(output)
1673
 
1674
  def history_render(history: History):
1675
  return gr.update(visible=True), history
@@ -4576,7 +4555,7 @@ This will help me create a better design for you."""
4576
  }
4577
  elif language == "svelte":
4578
  files = parse_svelte_output(clean_code)
4579
- if files['src/App.svelte'] and files['src/app.css']:
4580
  # Note: Media generation (text-to-image, image-to-image, etc.) is not supported for Svelte apps
4581
  # Only static HTML apps support automatic image/video/audio generation
4582
 
@@ -5016,7 +4995,7 @@ This will help me create a better design for you."""
5016
  elif language == "svelte":
5017
  # Handle Svelte output
5018
  files = parse_svelte_output(content)
5019
- if files['src/App.svelte'] and files['src/app.css']:
5020
  # Model returned complete Svelte output
5021
  formatted_output = format_svelte_output(files)
5022
  _history.append([query, formatted_output])
@@ -7594,106 +7573,62 @@ with gr.Blocks(
7594
  action_verb = "updating" if is_update else "duplicating"
7595
  return gr.update(value=f"Error {action_verb} Transformers.js space: {error_msg}", visible=True)
7596
  # Svelte logic
7597
- elif sdk_name == "Svelte" and not is_update:
7598
  try:
7599
- # Use duplicate_space to create a Svelte template space
7600
- from huggingface_hub import duplicate_space
7601
-
7602
- # Duplicate the Svelte template space
7603
- duplicated_repo = duplicate_space(
7604
- from_id="static-templates/svelte",
7605
- to_id=repo_id, # Use the full repo_id (username/space_name)
7606
- token=token.token,
7607
- exist_ok=True
7608
- )
7609
- print("Duplicated Svelte repo result:", duplicated_repo, type(duplicated_repo))
7610
-
7611
- # Extract the actual repo ID from the duplicated space
7612
- # The duplicated_repo is a RepoUrl object, convert to string and extract the repo ID
7613
- try:
7614
- duplicated_repo_str = str(duplicated_repo)
7615
- # Extract username and repo name from the URL
7616
- if "/spaces/" in duplicated_repo_str:
7617
- parts = duplicated_repo_str.split("/spaces/")[-1].split("/")
7618
- if len(parts) >= 2:
7619
- actual_repo_id = f"{parts[0]}/{parts[1]}"
7620
- else:
7621
- actual_repo_id = repo_id # Fallback to original
7622
- else:
7623
- actual_repo_id = repo_id # Fallback to original
7624
- except Exception as e:
7625
- print(f"Error extracting repo ID from duplicated_repo: {e}")
7626
- actual_repo_id = repo_id # Fallback to original
7627
  print("Actual repo ID for Svelte uploads:", actual_repo_id)
7628
-
7629
- # Parse the Svelte output to get the custom files
7630
- files = parse_svelte_output(code)
7631
-
7632
- if not files['src/App.svelte']:
7633
- return gr.update(value="Error: Could not parse Svelte output. Please regenerate the code.", visible=True)
7634
-
7635
- # Upload only the custom Svelte files to the duplicated space
7636
- import tempfile
7637
-
7638
- # Upload src/App.svelte (required)
7639
- with tempfile.NamedTemporaryFile("w", suffix=".svelte", delete=False) as f:
7640
- f.write(files['src/App.svelte'])
7641
- temp_path = f.name
7642
-
7643
- try:
7644
- api.upload_file(
7645
- path_or_fileobj=temp_path,
7646
- path_in_repo="src/App.svelte",
7647
  repo_id=actual_repo_id,
7648
  repo_type="space"
7649
- )
7650
- except Exception as e:
7651
- error_msg = str(e)
7652
- if "403 Forbidden" in error_msg and "write token" in error_msg:
7653
- return gr.update(value=f"Error: Permission denied. Please ensure you have write access to {actual_repo_id} and your token has the correct permissions.", visible=True)
7654
- else:
7655
- return gr.update(value=f"Error uploading src/App.svelte: {e}", visible=True)
7656
- finally:
7657
- import os
7658
- os.unlink(temp_path)
7659
-
7660
- # Upload src/app.css (optional)
7661
- if files['src/app.css']:
7662
- with tempfile.NamedTemporaryFile("w", suffix=".css", delete=False) as f:
7663
- f.write(files['src/app.css'])
7664
- temp_path = f.name
7665
-
7666
- try:
7667
- api.upload_file(
7668
- path_or_fileobj=temp_path,
7669
- path_in_repo="src/app.css",
7670
- repo_id=actual_repo_id,
7671
- repo_type="space"
7672
- )
7673
- except Exception as e:
7674
- error_msg = str(e)
7675
- if "403 Forbidden" in error_msg and "write token" in error_msg:
7676
- return gr.update(value=f"Error: Permission denied. Please ensure you have write access to {actual_repo_id} and your token has the correct permissions.", visible=True)
7677
- else:
7678
- return gr.update(value=f"Error uploading src/app.css: {e}", visible=True)
7679
- finally:
7680
- import os
7681
- os.unlink(temp_path)
7682
-
7683
  # Add anycoder tag to existing README
7684
  add_anycoder_tag_to_readme(api, actual_repo_id)
7685
-
7686
- # Success - all files uploaded
7687
  space_url = f"https://huggingface.co/spaces/{actual_repo_id}"
7688
  action_text = "Updated" if is_update else "Deployed"
7689
  return gr.update(value=f"✅ {action_text}! [Open your Svelte Space here]({space_url})", visible=True)
7690
-
7691
  except Exception as e:
7692
- # Handle potential RepoUrl object errors
7693
  error_msg = str(e)
7694
- if "'url'" in error_msg or "RepoUrl" in error_msg:
7695
- return gr.update(value=f"Error duplicating Svelte space: RepoUrl handling error. Please try again. Details: {error_msg}", visible=True)
7696
- return gr.update(value=f"Error duplicating Svelte space: {error_msg}", visible=True)
7697
  # Other SDKs (existing logic)
7698
  if sdk == "static":
7699
  import time
 
335
 
336
  Always output only the three code blocks as shown above, and do not include any explanations or extra text."""
337
 
338
+ SVELTE_SYSTEM_PROMPT = """You are an expert Svelte developer creating a modern Svelte application.
339
 
340
+ File selection policy (dynamic, model-decided):
341
+ - Generate ONLY the files actually needed for the user's request.
342
+ - MUST include src/App.svelte (entry component). Usually include src/app.css for global styles.
343
+ - Add additional files when needed, e.g. src/lib/*.svelte, src/components/*.svelte, src/stores/*.ts, static/* assets, etc.
344
+ - Base template files (package.json, vite.config.ts, tsconfig, svelte.config.js, src/main.ts, src/vite-env.d.ts) are provided by the template and should NOT be generated unless explicitly requested by the user.
345
 
346
+ Output format (CRITICAL):
347
+ - Return ONLY a series of file sections, each starting with a filename line:
348
+ === src/App.svelte ===
349
+ ...file content...
350
 
351
+ === src/app.css ===
352
+ ...file content...
 
353
 
354
+ (repeat for all files you decide to create)
355
+ - Do NOT wrap files in Markdown code fences.
 
 
356
 
357
  Requirements:
358
  1. Create a modern, responsive Svelte application based on the user's specific request
359
+ 2. Prefer TypeScript where applicable for better type safety
360
  3. Create a clean, professional UI with good user experience
361
  4. Make the application fully responsive for mobile devices
362
  5. Use modern CSS practices and Svelte best practices
363
  6. Include proper error handling and loading states
364
  7. Follow accessibility best practices
365
  8. Use Svelte's reactive features effectively
366
+ 9. Include proper component structure and organization (only what's needed)
367
+ """
 
 
 
 
 
 
 
 
 
368
 
369
+ SVELTE_SYSTEM_PROMPT_WITH_SEARCH = """You are an expert Svelte developer. You have access to real-time web search.
370
 
371
+ File selection policy (dynamic, model-decided):
372
+ - Generate ONLY the files actually needed for the user's request.
373
+ - MUST include src/App.svelte (entry component). Usually include src/app.css for global styles.
374
+ - Add additional files when needed, e.g. src/lib/*.svelte, src/components/*.svelte, src/stores/*.ts, static/* assets, etc.
375
+ - Base template files (package.json, vite.config.ts, tsconfig, svelte.config.js, src/main.ts, src/vite-env.d.ts) are provided by the template and should NOT be generated unless explicitly requested by the user.
376
 
377
+ Output format (CRITICAL):
378
+ - Return ONLY a series of file sections, each starting with a filename line:
379
+ === src/App.svelte ===
380
+ ...file content...
381
 
382
+ === src/app.css ===
383
+ ...file content...
 
384
 
385
+ (repeat for all files you decide to create)
386
+ - Do NOT wrap files in Markdown code fences.
 
387
 
388
  Requirements:
389
  1. Create a modern, responsive Svelte application
390
+ 2. Prefer TypeScript where applicable
391
+ 3. Clean, professional UI and UX
392
+ 4. Mobile-first responsiveness
393
+ 5. Svelte best practices and modern CSS
394
+ 6. Error handling and loading states
395
+ 7. Accessibility best practices
396
+ 8. Use search to apply current best practices
397
+ 9. Keep component structure organized and minimal
398
+ """
 
 
 
 
 
 
 
 
399
 
400
  TRANSFORMERS_JS_SYSTEM_PROMPT_WITH_SEARCH = """You are an expert web developer creating a transformers.js application. You have access to real-time web search. When needed, use web search to find the latest information, best practices, or specific technologies for transformers.js.
401
 
 
1618
  return text[idx:] if idx != -1 else text
1619
 
1620
  def parse_svelte_output(text):
1621
+ """Parse Svelte output to extract individual files.
1622
+
1623
+ Supports dynamic multi-file using === filename === sections (preferred),
1624
+ and falls back to ```svelte / ```css code blocks for minimal projects.
1625
+ """
1626
+ if not text:
1627
+ return {}
1628
+
1629
+ # Preferred: multi-file sections (works for any filenames)
1630
+ try:
1631
+ files = parse_multipage_html_output(text) or {}
1632
+ except Exception:
1633
+ files = {}
1634
+
1635
+ if isinstance(files, dict) and files:
1636
+ return files
1637
+
1638
+ # Fallback: code fences for minimal two-file output
1639
  import re
1640
+ results = {}
1641
+ svelte_match = re.search(r"```svelte\s*\n([\s\S]+?)\n```", text, re.IGNORECASE)
 
 
 
 
 
 
 
1642
  if svelte_match:
1643
+ results['src/App.svelte'] = svelte_match.group(1).strip()
1644
+ css_match = re.search(r"```css\s*\n([\s\S]+?)\n```", text, re.IGNORECASE)
1645
  if css_match:
1646
+ results['src/app.css'] = css_match.group(1).strip()
1647
+ return results
 
 
 
 
 
 
 
 
 
 
 
 
1648
 
1649
  def format_svelte_output(files):
1650
+ """Format Svelte files into === filename === sections (generic)."""
1651
+ return format_multipage_output(files)
 
 
 
 
 
1652
 
1653
  def history_render(history: History):
1654
  return gr.update(visible=True), history
 
4555
  }
4556
  elif language == "svelte":
4557
  files = parse_svelte_output(clean_code)
4558
+ if isinstance(files, dict) and files.get('src/App.svelte'):
4559
  # Note: Media generation (text-to-image, image-to-image, etc.) is not supported for Svelte apps
4560
  # Only static HTML apps support automatic image/video/audio generation
4561
 
 
4995
  elif language == "svelte":
4996
  # Handle Svelte output
4997
  files = parse_svelte_output(content)
4998
+ if isinstance(files, dict) and files.get('src/App.svelte'):
4999
  # Model returned complete Svelte output
5000
  formatted_output = format_svelte_output(files)
5001
  _history.append([query, formatted_output])
 
7573
  action_verb = "updating" if is_update else "duplicating"
7574
  return gr.update(value=f"Error {action_verb} Transformers.js space: {error_msg}", visible=True)
7575
  # Svelte logic
7576
+ elif sdk_name == "Svelte":
7577
  try:
7578
+ actual_repo_id = repo_id
7579
+ # For new spaces, duplicate the template first
7580
+ if not is_update:
7581
+ from huggingface_hub import duplicate_space
7582
+ duplicated_repo = duplicate_space(
7583
+ from_id="static-templates/svelte",
7584
+ to_id=repo_id,
7585
+ token=token.token,
7586
+ exist_ok=True
7587
+ )
7588
+ print("Duplicated Svelte repo result:", duplicated_repo, type(duplicated_repo))
7589
+ # Extract the actual repo ID from the duplicated space (RepoUrl)
7590
+ try:
7591
+ duplicated_repo_str = str(duplicated_repo)
7592
+ if "/spaces/" in duplicated_repo_str:
7593
+ parts = duplicated_repo_str.split("/spaces/")[-1].split("/")
7594
+ if len(parts) >= 2:
7595
+ actual_repo_id = f"{parts[0]}/{parts[1]}"
7596
+ except Exception as e:
7597
+ print(f"Error extracting repo ID from duplicated_repo: {e}")
7598
+ actual_repo_id = repo_id
 
 
 
 
 
 
 
7599
  print("Actual repo ID for Svelte uploads:", actual_repo_id)
7600
+
7601
+ # Parse all generated Svelte files (dynamic multi-file)
7602
+ files = parse_svelte_output(code) or {}
7603
+ if not isinstance(files, dict) or 'src/App.svelte' not in files or not files['src/App.svelte'].strip():
7604
+ return gr.update(value="Error: Could not parse Svelte output (missing src/App.svelte). Please regenerate the code.", visible=True)
7605
+
7606
+ # Write all files to a temp directory and upload folder in one commit
7607
+ import tempfile, os
7608
+ with tempfile.TemporaryDirectory() as tmpdir:
7609
+ for rel_path, content in files.items():
7610
+ safe_rel = (rel_path or '').strip().lstrip('/')
7611
+ abs_path = os.path.join(tmpdir, safe_rel)
7612
+ os.makedirs(os.path.dirname(abs_path), exist_ok=True)
7613
+ with open(abs_path, 'w') as fh:
7614
+ fh.write(content or '')
7615
+ api.upload_folder(
7616
+ folder_path=tmpdir,
 
 
7617
  repo_id=actual_repo_id,
7618
  repo_type="space"
7619
+ )
7620
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7621
  # Add anycoder tag to existing README
7622
  add_anycoder_tag_to_readme(api, actual_repo_id)
7623
+
7624
+ # Success
7625
  space_url = f"https://huggingface.co/spaces/{actual_repo_id}"
7626
  action_text = "Updated" if is_update else "Deployed"
7627
  return gr.update(value=f"✅ {action_text}! [Open your Svelte Space here]({space_url})", visible=True)
7628
+
7629
  except Exception as e:
 
7630
  error_msg = str(e)
7631
+ return gr.update(value=f"Error deploying Svelte app: {error_msg}", visible=True)
 
 
7632
  # Other SDKs (existing logic)
7633
  if sdk == "static":
7634
  import time