mgbam commited on
Commit
2f2aa44
Β·
verified Β·
1 Parent(s): 074e628

Create deployment.py

Browse files
Files changed (1) hide show
  1. deployment.py +826 -0
deployment.py ADDED
@@ -0,0 +1,826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Deployment utilities for Hugging Face Spaces and project management.
3
+ """
4
+
5
+ import os
6
+ import re
7
+ import ast
8
+ import tempfile
9
+ import time
10
+ import webbrowser
11
+ import urllib.parse
12
+ from typing import Optional, List, Dict, Tuple, Union
13
+ import gradio as gr
14
+ from huggingface_hub import HfApi, duplicate_space, list_repo_files
15
+ import requests
16
+
17
+ from utils import get_inference_client
18
+ from code_processing import parse_transformers_js_output, parse_svelte_output, parse_multipage_html_output, validate_and_autofix_files
19
+ from web_utils import check_hf_space_url, parse_repo_or_model_url
20
+
21
+ class DependencyManager:
22
+ """Handles Python dependency extraction and requirements.txt generation"""
23
+
24
+ @staticmethod
25
+ def extract_import_statements(code: str) -> List[str]:
26
+ """Extract import statements from generated code"""
27
+ import_statements = []
28
+
29
+ # Built-in Python modules to exclude
30
+ builtin_modules = {
31
+ 'os', 'sys', 'json', 'time', 'datetime', 'random', 'math', 're', 'collections',
32
+ 'itertools', 'functools', 'pathlib', 'urllib', 'http', 'email', 'html', 'xml',
33
+ 'csv', 'tempfile', 'shutil', 'subprocess', 'threading', 'multiprocessing',
34
+ 'asyncio', 'logging', 'typing', 'base64', 'hashlib', 'secrets', 'uuid',
35
+ 'copy', 'pickle', 'io', 'contextlib', 'warnings', 'sqlite3', 'gzip', 'zipfile',
36
+ 'tarfile', 'socket', 'ssl', 'platform', 'getpass', 'pwd', 'grp', 'stat',
37
+ 'glob', 'fnmatch', 'linecache', 'traceback', 'inspect', 'keyword', 'token',
38
+ 'tokenize', 'ast', 'code', 'codeop', 'dis', 'py_compile', 'compileall',
39
+ 'importlib', 'pkgutil', 'modulefinder', 'runpy', 'site', 'sysconfig'
40
+ }
41
+
42
+ try:
43
+ # Try to parse as Python AST
44
+ tree = ast.parse(code)
45
+
46
+ for node in ast.walk(tree):
47
+ if isinstance(node, ast.Import):
48
+ for alias in node.names:
49
+ module_name = alias.name.split('.')[0]
50
+ if module_name not in builtin_modules and not module_name.startswith('_'):
51
+ import_statements.append(f"import {alias.name}")
52
+
53
+ elif isinstance(node, ast.ImportFrom):
54
+ if node.module:
55
+ module_name = node.module.split('.')[0]
56
+ if module_name not in builtin_modules and not module_name.startswith('_'):
57
+ names = [alias.name for alias in node.names]
58
+ import_statements.append(f"from {node.module} import {', '.join(names)}")
59
+
60
+ except SyntaxError:
61
+ # Fallback: use regex to find import statements
62
+ for line in code.split('\n'):
63
+ line = line.strip()
64
+ if line.startswith('import ') or line.startswith('from '):
65
+ # Check if it's not a builtin module
66
+ if line.startswith('import '):
67
+ module_name = line.split()[1].split('.')[0]
68
+ elif line.startswith('from '):
69
+ module_name = line.split()[1].split('.')[0]
70
+
71
+ if module_name not in builtin_modules and not module_name.startswith('_'):
72
+ import_statements.append(line)
73
+
74
+ return list(set(import_statements)) # Remove duplicates
75
+
76
+ @staticmethod
77
+ def generate_requirements_txt_with_llm(import_statements: List[str]) -> str:
78
+ """Generate requirements.txt content using LLM based on import statements"""
79
+ if not import_statements:
80
+ return "# No additional dependencies required\n"
81
+
82
+ try:
83
+ client = get_inference_client("Qwen/Qwen3-Coder-480B-A35B-Instruct", "auto")
84
+
85
+ imports_text = '\n'.join(import_statements)
86
+
87
+ prompt = f"""Based on the following Python import statements, generate a comprehensive requirements.txt file with all necessary and commonly used related packages:
88
+
89
+ {imports_text}
90
+
91
+ Instructions:
92
+ - Include the direct packages needed for the imports
93
+ - Include commonly used companion packages and dependencies for better functionality
94
+ - Use correct PyPI package names (e.g., cv2 -> opencv-python, PIL -> Pillow, sklearn -> scikit-learn)
95
+ - Examples of comprehensive dependencies:
96
+ * transformers often needs: accelerate, torch, tokenizers, datasets
97
+ * gradio often needs: requests, Pillow for image handling
98
+ * pandas often needs: numpy, openpyxl for Excel files
99
+ * matplotlib often needs: numpy, pillow for image saving
100
+ * sklearn often needs: numpy, scipy, joblib
101
+ * streamlit often needs: pandas, numpy, requests
102
+ * opencv-python often needs: numpy, pillow
103
+ * fastapi often needs: uvicorn, pydantic
104
+ * torch often needs: torchvision, torchaudio (if doing computer vision/audio)
105
+ - Include packages for common file formats if relevant (openpyxl, python-docx, PyPDF2)
106
+ - Do not include Python built-in modules
107
+ - Do not specify versions unless there are known compatibility issues
108
+ - One package per line
109
+ - If no external packages are needed, return "# No additional dependencies required"
110
+
111
+ Generate a comprehensive requirements.txt that ensures the application will work smoothly:"""
112
+
113
+ messages = [
114
+ {"role": "system", "content": "You are a Python packaging expert specializing in creating comprehensive, production-ready requirements.txt files. Your goal is to ensure applications work smoothly by including not just direct dependencies but also commonly needed companion packages, popular extensions, and supporting libraries that developers typically need together."},
115
+ {"role": "user", "content": prompt}
116
+ ]
117
+
118
+ response = client.chat.completions.create(
119
+ model="Qwen/Qwen3-Coder-480B-A35B-Instruct",
120
+ messages=messages,
121
+ max_tokens=1024,
122
+ temperature=0.1
123
+ )
124
+
125
+ requirements_content = response.choices[0].message.content.strip()
126
+
127
+ # Clean up the response
128
+ if '```' in requirements_content:
129
+ lines = requirements_content.split('\n')
130
+ in_code_block = False
131
+ clean_lines = []
132
+ for line in lines:
133
+ if line.strip().startswith('```'):
134
+ in_code_block = not in_code_block
135
+ continue
136
+ if in_code_block:
137
+ clean_lines.append(line)
138
+ requirements_content = '\n'.join(clean_lines).strip()
139
+
140
+ # Ensure it ends with a newline
141
+ if requirements_content and not requirements_content.endswith('\n'):
142
+ requirements_content += '\n'
143
+
144
+ return requirements_content if requirements_content else "# No additional dependencies required\n"
145
+
146
+ except Exception as e:
147
+ print(f"[Dependencies] LLM generation failed, using fallback: {e}")
148
+ # Fallback: simple extraction with basic mapping
149
+ return DependencyManager._generate_requirements_fallback(import_statements)
150
+
151
+ @staticmethod
152
+ def _generate_requirements_fallback(import_statements: List[str]) -> str:
153
+ """Fallback requirements generation with basic mapping"""
154
+ dependencies = set()
155
+ special_cases = {
156
+ 'cv2': 'opencv-python',
157
+ 'PIL': 'Pillow',
158
+ 'sklearn': 'scikit-learn',
159
+ 'skimage': 'scikit-image',
160
+ 'bs4': 'beautifulsoup4'
161
+ }
162
+
163
+ for stmt in import_statements:
164
+ if stmt.startswith('import '):
165
+ module_name = stmt.split()[1].split('.')[0]
166
+ package_name = special_cases.get(module_name, module_name)
167
+ dependencies.add(package_name)
168
+ elif stmt.startswith('from '):
169
+ module_name = stmt.split()[1].split('.')[0]
170
+ package_name = special_cases.get(module_name, module_name)
171
+ dependencies.add(package_name)
172
+
173
+ if dependencies:
174
+ return '\n'.join(sorted(dependencies)) + '\n'
175
+ else:
176
+ return "# No additional dependencies required\n"
177
+
178
+ class SpaceManager:
179
+ """Handles Hugging Face Space operations"""
180
+
181
+ @staticmethod
182
+ def add_anycoder_tag_to_readme(api: HfApi, repo_id: str) -> None:
183
+ """Download existing README, add anycoder tag, and upload back"""
184
+ try:
185
+ # Download the existing README
186
+ readme_path = api.hf_hub_download(
187
+ repo_id=repo_id,
188
+ filename="README.md",
189
+ repo_type="space"
190
+ )
191
+
192
+ # Read the existing README content
193
+ with open(readme_path, 'r', encoding='utf-8') as f:
194
+ content = f.read()
195
+
196
+ # Parse frontmatter and content
197
+ if content.startswith('---'):
198
+ # Split frontmatter and body
199
+ parts = content.split('---', 2)
200
+ if len(parts) >= 3:
201
+ frontmatter = parts[1].strip()
202
+ body = parts[2] if len(parts) > 2 else ""
203
+
204
+ # Check if tags already exist
205
+ if 'tags:' in frontmatter:
206
+ # Add anycoder to existing tags if not present
207
+ if '- anycoder' not in frontmatter:
208
+ frontmatter = re.sub(r'(tags:\s*\n(?:\s*-\s*[^\n]+\n)*)', r'\1- anycoder\n', frontmatter)
209
+ else:
210
+ # Add tags section with anycoder
211
+ frontmatter += '\ntags:\n- anycoder'
212
+
213
+ # Reconstruct the README
214
+ new_content = f"---\n{frontmatter}\n---{body}"
215
+ else:
216
+ # Malformed frontmatter, just add tags at the end of frontmatter
217
+ new_content = content.replace('---', '---\ntags:\n- anycoder\n---', 1)
218
+ else:
219
+ # No frontmatter, add it at the beginning
220
+ new_content = f"---\ntags:\n- anycoder\n---\n\n{content}"
221
+
222
+ # Upload the modified README
223
+ with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding='utf-8') as f:
224
+ f.write(new_content)
225
+ temp_path = f.name
226
+
227
+ api.upload_file(
228
+ path_or_fileobj=temp_path,
229
+ path_in_repo="README.md",
230
+ repo_id=repo_id,
231
+ repo_type="space"
232
+ )
233
+
234
+ os.unlink(temp_path)
235
+ print(f"[SpaceManager] Added anycoder tag to {repo_id}")
236
+
237
+ except Exception as e:
238
+ print(f"[SpaceManager] Could not modify README.md: {e}")
239
+
240
+ class ProjectImporter:
241
+ """Handles importing projects from various sources"""
242
+
243
+ @staticmethod
244
+ def fetch_hf_space_content(username: str, project_name: str) -> str:
245
+ """Fetch content from a Hugging Face Space"""
246
+ try:
247
+ api = HfApi()
248
+ space_info = api.space_info(f"{username}/{project_name}")
249
+
250
+ # Try to fetch the main file based on SDK
251
+ sdk = space_info.sdk
252
+ main_file = None
253
+
254
+ # Define file patterns based on SDK
255
+ if sdk == "static":
256
+ file_patterns = ["index.html"]
257
+ elif sdk == "gradio":
258
+ file_patterns = ["app.py", "main.py", "gradio_app.py"]
259
+ elif sdk == "streamlit":
260
+ file_patterns = [
261
+ "streamlit_app.py", "src/streamlit_app.py", "app.py", "src/app.py",
262
+ "main.py", "src/main.py", "Home.py", "src/Home.py",
263
+ "🏠_Home.py", "src/🏠_Home.py", "1_🏠_Home.py", "src/1_🏠_Home.py"
264
+ ]
265
+ else:
266
+ file_patterns = [
267
+ "app.py", "src/app.py", "index.html", "streamlit_app.py",
268
+ "src/streamlit_app.py", "main.py", "src/main.py", "Home.py", "src/Home.py"
269
+ ]
270
+
271
+ # Try to find and download the main file
272
+ for file in file_patterns:
273
+ try:
274
+ content = api.hf_hub_download(
275
+ repo_id=f"{username}/{project_name}",
276
+ filename=file,
277
+ repo_type="space"
278
+ )
279
+ main_file = file
280
+ break
281
+ except:
282
+ continue
283
+
284
+ # If no main file found, list repository files and find Python files
285
+ if not main_file and sdk in ["streamlit", "gradio"]:
286
+ try:
287
+ files = list_repo_files(repo_id=f"{username}/{project_name}", repo_type="space")
288
+
289
+ # Look for Python files that might be the main file
290
+ python_files = [f for f in files if f.endswith('.py') and not f.startswith('.') and
291
+ (('/' not in f) or f.startswith('src/'))]
292
+
293
+ for py_file in python_files:
294
+ try:
295
+ content = api.hf_hub_download(
296
+ repo_id=f"{username}/{project_name}",
297
+ filename=py_file,
298
+ repo_type="space"
299
+ )
300
+ main_file = py_file
301
+ break
302
+ except:
303
+ continue
304
+ except:
305
+ pass
306
+
307
+ if main_file:
308
+ content = api.hf_hub_download(
309
+ repo_id=f"{username}/{project_name}",
310
+ filename=main_file,
311
+ repo_type="space"
312
+ )
313
+
314
+ # Read the file content
315
+ with open(content, 'r', encoding='utf-8') as f:
316
+ file_content = f.read()
317
+
318
+ return f"""IMPORTED PROJECT FROM HUGGING FACE SPACE
319
+ ==============================================
320
+
321
+ Space: {username}/{project_name}
322
+ SDK: {sdk}
323
+ Main File: {main_file}
324
+
325
+ {file_content}"""
326
+ else:
327
+ # Try to get more information about available files
328
+ try:
329
+ files = list_repo_files(repo_id=f"{username}/{project_name}", repo_type="space")
330
+ available_files = [f for f in files if not f.startswith('.') and not f.endswith('.md')]
331
+ return f"Error: Could not find main file in space {username}/{project_name}.\n\nSDK: {sdk}\nAvailable files: {', '.join(available_files[:10])}{'...' if len(available_files) > 10 else ''}\n\nTried looking for: {', '.join(file_patterns)}"
332
+ except:
333
+ return f"Error: Could not find main file in space {username}/{project_name}. Expected files for {sdk} SDK: {', '.join(file_patterns) if 'file_patterns' in locals() else 'standard files'}"
334
+
335
+ except Exception as e:
336
+ return f"Error fetching space content: {str(e)}"
337
+
338
+ @staticmethod
339
+ def load_project_from_url(url: str) -> Tuple[str, str]:
340
+ """Load project from Hugging Face Space URL"""
341
+ # Validate URL
342
+ is_valid, username, project_name = check_hf_space_url(url)
343
+
344
+ if not is_valid:
345
+ return "Error: Please enter a valid Hugging Face Spaces URL.\n\nExpected format: https://huggingface.co/spaces/username/project", ""
346
+
347
+ # Fetch content
348
+ content = ProjectImporter.fetch_hf_space_content(username, project_name)
349
+
350
+ if content.startswith("Error:"):
351
+ return content, ""
352
+
353
+ # Extract the actual code content by removing metadata
354
+ lines = content.split('\n')
355
+ code_start = 0
356
+ for i, line in enumerate(lines):
357
+ # Skip metadata lines and find the start of actual code
358
+ if (line.strip() and
359
+ not line.startswith('=') and
360
+ not line.startswith('IMPORTED PROJECT') and
361
+ not line.startswith('Space:') and
362
+ not line.startswith('SDK:') and
363
+ not line.startswith('Main File:')):
364
+ code_start = i
365
+ break
366
+
367
+ code_content = '\n'.join(lines[code_start:])
368
+
369
+ return f"βœ… Successfully imported project from {username}/{project_name}", code_content
370
+
371
+ class Deployer:
372
+ """Handles deployment to various platforms"""
373
+
374
+ def __init__(self):
375
+ self.dependency_manager = DependencyManager()
376
+ self.space_manager = SpaceManager()
377
+
378
+ def deploy_to_user_space(self, code: str, space_name: str, sdk_name: str,
379
+ profile: Optional[gr.OAuthProfile] = None,
380
+ token: Optional[gr.OAuthToken] = None) -> str:
381
+ """Deploy code to user's Hugging Face Space"""
382
+ if not code or not code.strip():
383
+ return "No code to deploy."
384
+
385
+ if profile is None or token is None:
386
+ return "Please log in with your Hugging Face account to deploy to your own Space."
387
+
388
+ # Check token validity
389
+ if not token.token or token.token == "hf_":
390
+ return "Error: Invalid token. Please log in again with your Hugging Face account to get a valid write token."
391
+
392
+ # Determine if this is an update or new space
393
+ is_update = "/" in space_name.strip()
394
+ if is_update:
395
+ repo_id = space_name.strip()
396
+ space_username = repo_id.split('/')[0]
397
+ if space_username != profile.username:
398
+ return f"Error: You can only update your own spaces. This space belongs to {space_username}."
399
+ else:
400
+ repo_id = f"{profile.username}/{space_name.strip()}"
401
+
402
+ # Verify access for updates
403
+ if is_update:
404
+ try:
405
+ api = HfApi(token=token.token)
406
+ space_info = api.space_info(repo_id)
407
+ if not space_info:
408
+ return f"Error: Could not access space {repo_id}. Please check your permissions."
409
+ except Exception as e:
410
+ return f"Error: No write access to space {repo_id}. Error: {str(e)}"
411
+
412
+ # Route to appropriate deployment method
413
+ try:
414
+ if sdk_name == "Streamlit (Python)":
415
+ return self._deploy_streamlit(code, repo_id, is_update, token)
416
+ elif sdk_name == "Transformers.js":
417
+ return self._deploy_transformers_js(code, repo_id, is_update, token)
418
+ elif sdk_name == "Svelte":
419
+ return self._deploy_svelte(code, repo_id, is_update, token)
420
+ elif sdk_name == "Static (HTML)":
421
+ return self._deploy_static_html(code, repo_id, is_update, token)
422
+ else: # Gradio (Python)
423
+ return self._deploy_gradio(code, repo_id, is_update, token)
424
+ except Exception as e:
425
+ return f"Error during deployment: {str(e)}"
426
+
427
+ def _deploy_streamlit(self, code: str, repo_id: str, is_update: bool, token) -> str:
428
+ """Deploy Streamlit app"""
429
+ api = HfApi(token=token.token)
430
+
431
+ try:
432
+ if not is_update:
433
+ # Duplicate template space
434
+ duplicated_repo = duplicate_space(
435
+ from_id="streamlit/streamlit-template-space",
436
+ to_id=repo_id.split('/')[-1],
437
+ token=token.token,
438
+ exist_ok=True
439
+ )
440
+
441
+ # Generate and upload requirements.txt
442
+ import_statements = self.dependency_manager.extract_import_statements(code)
443
+ requirements_content = self.dependency_manager.generate_requirements_txt_with_llm(import_statements)
444
+
445
+ # Upload requirements.txt
446
+ with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:
447
+ f.write(requirements_content)
448
+ requirements_temp_path = f.name
449
+
450
+ try:
451
+ api.upload_file(
452
+ path_or_fileobj=requirements_temp_path,
453
+ path_in_repo="requirements.txt",
454
+ repo_id=repo_id,
455
+ repo_type="space"
456
+ )
457
+ finally:
458
+ os.unlink(requirements_temp_path)
459
+
460
+ # Add anycoder tag
461
+ self.space_manager.add_anycoder_tag_to_readme(api, repo_id)
462
+
463
+ # Upload the main Streamlit app
464
+ with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
465
+ f.write(code)
466
+ temp_path = f.name
467
+
468
+ try:
469
+ api.upload_file(
470
+ path_or_fileobj=temp_path,
471
+ path_in_repo="src/streamlit_app.py",
472
+ repo_id=repo_id,
473
+ repo_type="space"
474
+ )
475
+
476
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
477
+ action_text = "Updated" if is_update else "Deployed"
478
+ return f"βœ… {action_text}! [Open your Space here]({space_url})"
479
+
480
+ finally:
481
+ os.unlink(temp_path)
482
+
483
+ except Exception as e:
484
+ error_msg = str(e)
485
+ if "403 Forbidden" in error_msg:
486
+ return f"Error: Permission denied. Please ensure you have write access to {repo_id}."
487
+ else:
488
+ action_verb = "updating" if is_update else "creating"
489
+ return f"Error {action_verb} Streamlit space: {error_msg}"
490
+
491
+ def _deploy_transformers_js(self, code: str, repo_id: str, is_update: bool, token) -> str:
492
+ """Deploy Transformers.js app"""
493
+ api = HfApi(token=token.token)
494
+
495
+ try:
496
+ if not is_update:
497
+ # Duplicate template space
498
+ duplicated_repo = duplicate_space(
499
+ from_id="static-templates/transformers.js",
500
+ to_id=repo_id,
501
+ token=token.token,
502
+ exist_ok=True
503
+ )
504
+
505
+ # Parse transformers.js output
506
+ files = parse_transformers_js_output(code)
507
+ if not all(files.values()):
508
+ return "Error: Could not parse transformers.js output. Please regenerate the code."
509
+
510
+ # Upload the three files
511
+ files_to_upload = [
512
+ ("index.html", files['index.html']),
513
+ ("index.js", files['index.js']),
514
+ ("style.css", files['style.css'])
515
+ ]
516
+
517
+ for file_name, file_content in files_to_upload:
518
+ with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False) as f:
519
+ f.write(file_content)
520
+ temp_path = f.name
521
+
522
+ try:
523
+ api.upload_file(
524
+ path_or_fileobj=temp_path,
525
+ path_in_repo=file_name,
526
+ repo_id=repo_id,
527
+ repo_type="space"
528
+ )
529
+ finally:
530
+ os.unlink(temp_path)
531
+
532
+ # Add anycoder tag
533
+ self.space_manager.add_anycoder_tag_to_readme(api, repo_id)
534
+
535
+ # Restart space if updating
536
+ if is_update:
537
+ try:
538
+ api.restart_space(repo_id=repo_id)
539
+ except Exception as restart_error:
540
+ print(f"[Deploy] Could not restart space after update: {restart_error}")
541
+
542
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
543
+ action_text = "Updated" if is_update else "Deployed"
544
+ return f"βœ… {action_text}! [Open your Transformers.js Space here]({space_url})"
545
+
546
+ except Exception as e:
547
+ error_msg = str(e)
548
+ if "403 Forbidden" in error_msg:
549
+ return f"Error: Permission denied. Please ensure you have write access to {repo_id}."
550
+ else:
551
+ action_verb = "updating" if is_update else "creating"
552
+ return f"Error {action_verb} Transformers.js space: {error_msg}"
553
+
554
+ def _deploy_svelte(self, code: str, repo_id: str, is_update: bool, token) -> str:
555
+ """Deploy Svelte app"""
556
+ if is_update:
557
+ return "Error: Svelte space updates not yet supported. Please create a new space."
558
+
559
+ api = HfApi(token=token.token)
560
+
561
+ try:
562
+ # Duplicate template space
563
+ duplicated_repo = duplicate_space(
564
+ from_id="static-templates/svelte",
565
+ to_id=repo_id,
566
+ token=token.token,
567
+ exist_ok=True
568
+ )
569
+
570
+ # Parse Svelte output
571
+ files = parse_svelte_output(code)
572
+ if not files['src/App.svelte']:
573
+ return "Error: Could not parse Svelte output. Please regenerate the code."
574
+
575
+ # Upload src/App.svelte
576
+ with tempfile.NamedTemporaryFile("w", suffix=".svelte", delete=False) as f:
577
+ f.write(files['src/App.svelte'])
578
+ temp_path = f.name
579
+
580
+ try:
581
+ api.upload_file(
582
+ path_or_fileobj=temp_path,
583
+ path_in_repo="src/App.svelte",
584
+ repo_id=repo_id,
585
+ repo_type="space"
586
+ )
587
+ finally:
588
+ os.unlink(temp_path)
589
+
590
+ # Upload src/app.css if present
591
+ if files['src/app.css']:
592
+ with tempfile.NamedTemporaryFile("w", suffix=".css", delete=False) as f:
593
+ f.write(files['src/app.css'])
594
+ temp_path = f.name
595
+
596
+ try:
597
+ api.upload_file(
598
+ path_or_fileobj=temp_path,
599
+ path_in_repo="src/app.css",
600
+ repo_id=repo_id,
601
+ repo_type="space"
602
+ )
603
+ finally:
604
+ os.unlink(temp_path)
605
+
606
+ # Add anycoder tag
607
+ self.space_manager.add_anycoder_tag_to_readme(api, repo_id)
608
+
609
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
610
+ return f"βœ… Deployed! [Open your Svelte Space here]({space_url})"
611
+
612
+ except Exception as e:
613
+ return f"Error creating Svelte space: {str(e)}"
614
+
615
+ def _deploy_static_html(self, code: str, repo_id: str, is_update: bool, token) -> str:
616
+ """Deploy static HTML app"""
617
+ api = HfApi(token=token.token)
618
+
619
+ try:
620
+ if not is_update:
621
+ # Create the static space
622
+ api.create_repo(
623
+ repo_id=repo_id,
624
+ repo_type="space",
625
+ space_sdk="static",
626
+ exist_ok=True
627
+ )
628
+
629
+ # Add anycoder tag
630
+ self.space_manager.add_anycoder_tag_to_readme(api, repo_id)
631
+
632
+ # Detect multi-file structure
633
+ files = parse_multipage_html_output(code)
634
+ files = validate_and_autofix_files(files)
635
+
636
+ if isinstance(files, dict) and files.get('index.html'):
637
+ # Multi-file deployment
638
+ with tempfile.TemporaryDirectory() as tmpdir:
639
+ # Write each file preserving subdirectories
640
+ for rel_path, content in files.items():
641
+ safe_rel_path = rel_path.strip().lstrip('/')
642
+ abs_path = os.path.join(tmpdir, safe_rel_path)
643
+ os.makedirs(os.path.dirname(abs_path), exist_ok=True)
644
+ with open(abs_path, 'w') as fh:
645
+ fh.write(content)
646
+
647
+ # Upload the entire folder
648
+ api.upload_folder(
649
+ folder_path=tmpdir,
650
+ repo_id=repo_id,
651
+ repo_type="space"
652
+ )
653
+ else:
654
+ # Single HTML file deployment
655
+ with tempfile.NamedTemporaryFile("w", suffix=".html", delete=False) as f:
656
+ f.write(code)
657
+ temp_path = f.name
658
+
659
+ try:
660
+ api.upload_file(
661
+ path_or_fileobj=temp_path,
662
+ path_in_repo="index.html",
663
+ repo_id=repo_id,
664
+ repo_type="space"
665
+ )
666
+ finally:
667
+ os.unlink(temp_path)
668
+
669
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
670
+ action_text = "Updated" if is_update else "Deployed"
671
+ return f"βœ… {action_text}! [Open your Space here]({space_url})"
672
+
673
+ except Exception as e:
674
+ error_msg = str(e)
675
+ if "403 Forbidden" in error_msg:
676
+ return f"Error: Permission denied. Please ensure you have write access to {repo_id}."
677
+ else:
678
+ return f"Error deploying static HTML: {error_msg}"
679
+
680
+ def _deploy_gradio(self, code: str, repo_id: str, is_update: bool, token) -> str:
681
+ """Deploy Gradio app"""
682
+ api = HfApi(token=token.token)
683
+
684
+ try:
685
+ if not is_update:
686
+ # Create the Gradio space
687
+ api.create_repo(
688
+ repo_id=repo_id,
689
+ repo_type="space",
690
+ space_sdk="gradio",
691
+ exist_ok=True
692
+ )
693
+
694
+ # Generate and upload requirements.txt
695
+ import_statements = self.dependency_manager.extract_import_statements(code)
696
+ requirements_content = self.dependency_manager.generate_requirements_txt_with_llm(import_statements)
697
+
698
+ with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:
699
+ f.write(requirements_content)
700
+ requirements_temp_path = f.name
701
+
702
+ try:
703
+ api.upload_file(
704
+ path_or_fileobj=requirements_temp_path,
705
+ path_in_repo="requirements.txt",
706
+ repo_id=repo_id,
707
+ repo_type="space"
708
+ )
709
+ finally:
710
+ os.unlink(requirements_temp_path)
711
+
712
+ # Add anycoder tag
713
+ self.space_manager.add_anycoder_tag_to_readme(api, repo_id)
714
+
715
+ # Upload the main app.py file
716
+ with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
717
+ f.write(code)
718
+ temp_path = f.name
719
+
720
+ try:
721
+ api.upload_file(
722
+ path_or_fileobj=temp_path,
723
+ path_in_repo="app.py",
724
+ repo_id=repo_id,
725
+ repo_type="space"
726
+ )
727
+
728
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
729
+ action_text = "Updated" if is_update else "Deployed"
730
+ return f"βœ… {action_text}! [Open your Space here]({space_url})"
731
+
732
+ finally:
733
+ os.unlink(temp_path)
734
+
735
+ except Exception as e:
736
+ error_msg = str(e)
737
+ if "403 Forbidden" in error_msg:
738
+ return f"Error: Permission denied. Please ensure you have write access to {repo_id}."
739
+ else:
740
+ return f"Error deploying Gradio app: {error_msg}"
741
+
742
+ def deploy_to_spaces(self, code: str) -> None:
743
+ """Deploy using the old method (opens in new tab)"""
744
+ if not code or not code.strip():
745
+ return
746
+
747
+ # Wrap HTML in Gradio app
748
+ app_py = self._wrap_html_in_gradio_app(code.strip())
749
+ base_url = "https://huggingface.co/new-space"
750
+ params = urllib.parse.urlencode({
751
+ "name": "new-space",
752
+ "sdk": "gradio"
753
+ })
754
+ files_params = urllib.parse.urlencode({
755
+ "files[0][path]": "app.py",
756
+ "files[0][content]": app_py
757
+ })
758
+ full_url = f"{base_url}?{params}&{files_params}"
759
+ webbrowser.open_new_tab(full_url)
760
+
761
+ def deploy_to_spaces_static(self, code: str) -> None:
762
+ """Deploy using static SDK (opens in new tab)"""
763
+ if not code or not code.strip():
764
+ return
765
+
766
+ base_url = "https://huggingface.co/new-space"
767
+ params = urllib.parse.urlencode({
768
+ "name": "new-space",
769
+ "sdk": "static"
770
+ })
771
+ files_params = urllib.parse.urlencode({
772
+ "files[0][path]": "index.html",
773
+ "files[0][content]": code.strip()
774
+ })
775
+ full_url = f"{base_url}?{params}&{files_params}"
776
+ webbrowser.open_new_tab(full_url)
777
+
778
+ def _wrap_html_in_gradio_app(self, html_code: str) -> str:
779
+ """Wrap HTML code in a Gradio app"""
780
+ # Escape triple quotes for safe embedding
781
+ safe_html = html_code.replace('"""', r'\"\"\"')
782
+
783
+ # Extract import statements and generate requirements.txt comment
784
+ import_statements = self.dependency_manager.extract_import_statements(html_code)
785
+ requirements_comment = ""
786
+ if import_statements:
787
+ requirements_content = self.dependency_manager.generate_requirements_txt_with_llm(import_statements)
788
+ requirements_comment = (
789
+ "# Generated requirements.txt content (create this file manually if needed):\n"
790
+ + '\n'.join(f"# {line}" for line in requirements_content.strip().split('\n')) + '\n\n'
791
+ )
792
+
793
+ return (
794
+ f'{requirements_comment}'
795
+ 'import gradio as gr\n\n'
796
+ 'def show_html():\n'
797
+ f' return """{safe_html}"""\n\n'
798
+ 'demo = gr.Interface(fn=show_html, inputs=None, outputs=gr.HTML())\n\n'
799
+ 'if __name__ == "__main__":\n'
800
+ ' demo.launch()\n'
801
+ )
802
+
803
+ # Global deployer instance
804
+ deployer = Deployer()
805
+ project_importer = ProjectImporter()
806
+
807
+ # Export main functions
808
+ def deploy_to_user_space(code: str, space_name: str, sdk_name: str,
809
+ profile: Optional[gr.OAuthProfile] = None,
810
+ token: Optional[gr.OAuthToken] = None) -> str:
811
+ return deployer.deploy_to_user_space(code, space_name, sdk_name, profile, token)
812
+
813
+ def deploy_to_spaces(code: str) -> None:
814
+ return deployer.deploy_to_spaces(code)
815
+
816
+ def deploy_to_spaces_static(code: str) -> None:
817
+ return deployer.deploy_to_spaces_static(code)
818
+
819
+ def load_project_from_url(url: str) -> Tuple[str, str]:
820
+ return project_importer.load_project_from_url(url)
821
+
822
+ def extract_import_statements(code: str) -> List[str]:
823
+ return deployer.dependency_manager.extract_import_statements(code)
824
+
825
+ def generate_requirements_txt_with_llm(import_statements: List[str]) -> str:
826
+ return deployer.dependency_manager.generate_requirements_txt_with_llm(import_statements)