akhaliq HF Staff commited on
Commit
768e149
Β·
1 Parent(s): 163358c
Files changed (2) hide show
  1. README.md +1 -0
  2. app.py +186 -10
README.md CHANGED
@@ -10,6 +10,7 @@ pinned: false
10
  disable_embedding: true
11
  hf_oauth: true
12
  hf_oauth_scopes:
 
13
  - write-repos
14
  - manage-repos
15
  ---
 
10
  disable_embedding: true
11
  hf_oauth: true
12
  hf_oauth_scopes:
13
+ - read-repos
14
  - write-repos
15
  - manage-repos
16
  ---
app.py CHANGED
@@ -211,6 +211,15 @@ def create_space_from_html(title: str, html_content: str, prompts: List[str] = N
211
  if not username:
212
  username = user_info.get('name', 'user')
213
  print(f"Debug: Final username: {username}")
 
 
 
 
 
 
 
 
 
214
  except Exception as e:
215
  print(f"Debug: Could not get user info: {e}")
216
  return {
@@ -232,16 +241,27 @@ def create_space_from_html(title: str, html_content: str, prompts: List[str] = N
232
 
233
  # Create the space
234
  try:
 
 
 
 
 
 
 
 
235
  repo_url = user_hf_api.create_repo(
236
  repo_id=repo_name,
237
  repo_type="space",
238
  space_sdk="static",
239
  private=False,
240
- exist_ok=False
 
241
  )
242
  print(f"Debug: Successfully created space: {repo_url}")
243
  except Exception as e:
244
  print(f"Debug: Failed to create space: {e}")
 
 
245
  raise e
246
 
247
  # Prepare the HTML content with proper structure
@@ -311,13 +331,28 @@ def create_space_from_html(title: str, html_content: str, prompts: List[str] = N
311
 
312
  full_html = html_template.format(title=title, html_content=html_content)
313
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  # Upload the HTML file
 
315
  user_hf_api.upload_file(
316
  path_or_fileobj=full_html.encode('utf-8'),
317
  path_in_repo="index.html",
318
  repo_id=repo_name,
319
- repo_type="space"
 
320
  )
 
321
 
322
  # Create README.md with project info
323
  prompts_text = "".join([f"- {prompt}\n" for prompt in (prompts or [])])
@@ -343,12 +378,15 @@ Visit: https://huggingface.co/spaces/{repo_name}
343
 
344
  readme_content = readme_template.format(title=title, prompts_text=prompts_text, repo_name=repo_name)
345
 
 
346
  user_hf_api.upload_file(
347
  path_or_fileobj=readme_content.encode('utf-8'),
348
  path_in_repo="README.md",
349
  repo_id=repo_name,
350
- repo_type="space"
 
351
  )
 
352
 
353
  return {
354
  "success": True,
@@ -358,11 +396,39 @@ Visit: https://huggingface.co/spaces/{repo_name}
358
  }
359
 
360
  except Exception as e:
361
- return {
362
- "success": False,
363
- "error": str(e),
364
- "message": f"Failed to create space: {str(e)}"
365
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
 
367
  def deploy_to_space(title: str, html_content: str, history: History, oauth_profile: gr.OAuthProfile = None, oauth_token: gr.OAuthToken = None) -> str:
368
  """
@@ -382,7 +448,10 @@ To deploy your application, you need to be logged in with your Hugging Face acco
382
 
383
  **How to log in:**
384
  1. Click the "Sign in with Hugging Face" button in the sidebar
385
- 2. Authorize AnyCoder to access your Hugging Face account
 
 
 
386
  3. Try deploying again
387
 
388
  **Why login is required:**
@@ -390,6 +459,8 @@ To deploy your application, you need to be logged in with your Hugging Face acco
390
  - You need write permissions to create spaces
391
  - This ensures you own and can manage your deployed applications
392
 
 
 
393
  ---
394
  *Please log in and try again.*"""
395
 
@@ -403,6 +474,80 @@ To deploy your application, you need to be logged in with your Hugging Face acco
403
  print(f"Debug: Token length: {len(user_token) if user_token else 0}")
404
  print(f"Debug: Token starts with: {user_token[:10] if user_token else 'None'}...")
405
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
  # Extract prompts from history
407
  prompts = []
408
  for user_msg, _ in history:
@@ -1177,6 +1322,9 @@ with gr.Blocks(
1177
  size="sm"
1178
  )
1179
 
 
 
 
1180
  # Main input section
1181
  input = gr.Textbox(
1182
  label="What would you like to build?",
@@ -1308,7 +1456,35 @@ with gr.Blocks(
1308
  sandbox = gr.HTML(label="Live preview")
1309
  with gr.Tab("Deploy"):
1310
  deploy_output = gr.Markdown(
1311
- value="## πŸš€ Deploy Your Application\n\n1. Generate some code first\n2. Enter a title for your space\n3. Click 'Deploy to Space' in the sidebar\n\nYour application will be deployed to Hugging Face Spaces and you'll get a shareable URL!",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1312
  label="Deployment Status"
1313
  )
1314
  with gr.Tab("History"):
 
211
  if not username:
212
  username = user_info.get('name', 'user')
213
  print(f"Debug: Final username: {username}")
214
+
215
+ # Additional validation
216
+ if not username or username == 'user':
217
+ return {
218
+ "success": False,
219
+ "error": "Could not retrieve username from token",
220
+ "message": "The authentication token is valid but username could not be retrieved. Please try logging in again."
221
+ }
222
+
223
  except Exception as e:
224
  print(f"Debug: Could not get user info: {e}")
225
  return {
 
241
 
242
  # Create the space
243
  try:
244
+ print(f"Debug: Creating space with parameters:")
245
+ print(f" repo_id: {repo_name}")
246
+ print(f" repo_type: space")
247
+ print(f" space_sdk: static")
248
+ print(f" private: False")
249
+ print(f" exist_ok: False")
250
+ print(f" token length: {len(api_token) if api_token else 0}")
251
+
252
  repo_url = user_hf_api.create_repo(
253
  repo_id=repo_name,
254
  repo_type="space",
255
  space_sdk="static",
256
  private=False,
257
+ exist_ok=False,
258
+ token=api_token
259
  )
260
  print(f"Debug: Successfully created space: {repo_url}")
261
  except Exception as e:
262
  print(f"Debug: Failed to create space: {e}")
263
+ print(f"Debug: Exception type: {type(e)}")
264
+ print(f"Debug: Exception args: {e.args}")
265
  raise e
266
 
267
  # Prepare the HTML content with proper structure
 
331
 
332
  full_html = html_template.format(title=title, html_content=html_content)
333
 
334
+ # Check HTML content size
335
+ html_size = len(full_html.encode('utf-8'))
336
+ print(f"Debug: HTML content size: {html_size} bytes")
337
+
338
+ if html_size > 1000000: # 1MB limit
339
+ print(f"Debug: Warning - HTML content is large ({html_size} bytes)")
340
+ # Truncate if too large
341
+ if len(html_content) > 500000: # 500KB limit for content
342
+ html_content = html_content[:500000] + "\n<!-- Content truncated due to size -->"
343
+ full_html = html_template.format(title=title, html_content=html_content)
344
+ print(f"Debug: HTML content truncated to {len(full_html.encode('utf-8'))} bytes")
345
+
346
  # Upload the HTML file
347
+ print(f"Debug: Uploading index.html to {repo_name}")
348
  user_hf_api.upload_file(
349
  path_or_fileobj=full_html.encode('utf-8'),
350
  path_in_repo="index.html",
351
  repo_id=repo_name,
352
+ repo_type="space",
353
+ token=api_token
354
  )
355
+ print(f"Debug: Successfully uploaded index.html")
356
 
357
  # Create README.md with project info
358
  prompts_text = "".join([f"- {prompt}\n" for prompt in (prompts or [])])
 
378
 
379
  readme_content = readme_template.format(title=title, prompts_text=prompts_text, repo_name=repo_name)
380
 
381
+ print(f"Debug: Uploading README.md to {repo_name}")
382
  user_hf_api.upload_file(
383
  path_or_fileobj=readme_content.encode('utf-8'),
384
  path_in_repo="README.md",
385
  repo_id=repo_name,
386
+ repo_type="space",
387
+ token=api_token
388
  )
389
+ print(f"Debug: Successfully uploaded README.md")
390
 
391
  return {
392
  "success": True,
 
396
  }
397
 
398
  except Exception as e:
399
+ error_msg = str(e)
400
+
401
+ # Handle specific API errors
402
+ if "401" in error_msg or "Unauthorized" in error_msg:
403
+ return {
404
+ "success": False,
405
+ "error": "Authentication failed - please log in again",
406
+ "message": "Your token may have expired. Please log out and log back in."
407
+ }
408
+ elif "403" in error_msg or "Forbidden" in error_msg:
409
+ return {
410
+ "success": False,
411
+ "error": "Permission denied - insufficient privileges",
412
+ "message": "You may not have permission to create spaces. Please check your Hugging Face account settings."
413
+ }
414
+ elif "409" in error_msg or "Conflict" in error_msg:
415
+ return {
416
+ "success": False,
417
+ "error": "Repository already exists",
418
+ "message": "A space with this name already exists. Please try a different title."
419
+ }
420
+ elif "422" in error_msg or "Validation" in error_msg:
421
+ return {
422
+ "success": False,
423
+ "error": "Invalid repository name",
424
+ "message": "The space title contains invalid characters. Please use only letters, numbers, hyphens, and underscores."
425
+ }
426
+ else:
427
+ return {
428
+ "success": False,
429
+ "error": error_msg,
430
+ "message": f"Failed to create space: {error_msg}"
431
+ }
432
 
433
  def deploy_to_space(title: str, html_content: str, history: History, oauth_profile: gr.OAuthProfile = None, oauth_token: gr.OAuthToken = None) -> str:
434
  """
 
448
 
449
  **How to log in:**
450
  1. Click the "Sign in with Hugging Face" button in the sidebar
451
+ 2. Authorize AnyCoder to access your Hugging Face account with the required permissions:
452
+ - read-repos
453
+ - write-repos
454
+ - manage-repos
455
  3. Try deploying again
456
 
457
  **Why login is required:**
 
459
  - You need write permissions to create spaces
460
  - This ensures you own and can manage your deployed applications
461
 
462
+ **Note:** Make sure to grant all the requested permissions when authorizing the application.
463
+
464
  ---
465
  *Please log in and try again.*"""
466
 
 
474
  print(f"Debug: Token length: {len(user_token) if user_token else 0}")
475
  print(f"Debug: Token starts with: {user_token[:10] if user_token else 'None'}...")
476
 
477
+ # Additional debugging for OAuth components
478
+ print(f"Debug: OAuth profile type: {type(oauth_profile)}")
479
+ print(f"Debug: OAuth token type: {type(oauth_token)}")
480
+ print(f"Debug: OAuth profile attributes: {dir(oauth_profile) if oauth_profile else 'None'}")
481
+ print(f"Debug: OAuth token attributes: {dir(oauth_token) if oauth_token else 'None'}")
482
+
483
+ # Validate token format
484
+ if not user_token or not user_token.startswith('hf_'):
485
+ return """❌ **Invalid Token Format**
486
+
487
+ The OAuth token appears to be invalid or in the wrong format. Please try logging out and logging back in.
488
+
489
+ **Steps to fix:**
490
+ 1. Click the logout button in the sidebar
491
+ 2. Click "Sign in with Hugging Face" again
492
+ 3. Authorize the application with the required permissions (read-repos, write-repos, manage-repos)
493
+ 4. Try deploying again
494
+
495
+ **Note:** Make sure you authorize all the required permissions when logging in.
496
+
497
+ ---
498
+ *Please try logging in again.*"""
499
+
500
+ # Test the token by making a simple API call
501
+ try:
502
+ test_api = HfApi(token=user_token)
503
+ user_info = test_api.whoami()
504
+ print(f"Debug: Token test successful - user: {user_info.get('name', 'unknown')}")
505
+
506
+ # Check if user has the necessary permissions by trying to list their repos
507
+ try:
508
+ repos = test_api.list_repos(author=username, token=user_token)
509
+ print(f"Debug: User has {len(list(repos))} repositories")
510
+ except Exception as repo_error:
511
+ print(f"Debug: Could not list repos: {repo_error}")
512
+ return """❌ **Insufficient Permissions**
513
+
514
+ Your Hugging Face account doesn't have the necessary permissions to create spaces. This could be because:
515
+
516
+ 1. You didn't grant all the required permissions during login
517
+ 2. Your account has restrictions on creating repositories
518
+ 3. The OAuth token doesn't include the necessary scopes
519
+
520
+ **Steps to fix:**
521
+ 1. Click the logout button in the sidebar
522
+ 2. Click "Sign in with Hugging Face" again
523
+ 3. Make sure to grant ALL the requested permissions:
524
+ - read-repos
525
+ - write-repos
526
+ - manage-repos
527
+ 4. Try deploying again
528
+
529
+ ---
530
+ *Please log in again with full permissions.*"""
531
+
532
+ except Exception as token_error:
533
+ print(f"Debug: Token test failed: {token_error}")
534
+ return """❌ **Token Validation Failed**
535
+
536
+ The OAuth token could not be validated. This could be because:
537
+
538
+ 1. The token has expired
539
+ 2. The token doesn't have the right permissions
540
+ 3. There's an issue with the authentication
541
+
542
+ **Steps to fix:**
543
+ 1. Click the logout button in the sidebar
544
+ 2. Click "Sign in with Hugging Face" again
545
+ 3. Authorize with all required permissions
546
+ 4. Try deploying again
547
+
548
+ ---
549
+ *Please log in again.*"""
550
+
551
  # Extract prompts from history
552
  prompts = []
553
  for user_msg, _ in history:
 
1322
  size="sm"
1323
  )
1324
 
1325
+ # OAuth components are automatically injected as function parameters
1326
+ # when using gr.LoginButton() - no need to create them separately
1327
+
1328
  # Main input section
1329
  input = gr.Textbox(
1330
  label="What would you like to build?",
 
1456
  sandbox = gr.HTML(label="Live preview")
1457
  with gr.Tab("Deploy"):
1458
  deploy_output = gr.Markdown(
1459
+ value="""## πŸš€ Deploy Your Application
1460
+
1461
+ ### Prerequisites
1462
+ 1. **Login Required**: You must be logged in with your Hugging Face account
1463
+ 2. **Permissions**: Grant the following permissions when logging in:
1464
+ - read-repos
1465
+ - write-repos
1466
+ - manage-repos
1467
+
1468
+ ### Steps to Deploy
1469
+ 1. **Login**: Click "Sign in with Hugging Face" in the sidebar
1470
+ 2. **Generate Code**: Generate some HTML code using the AI
1471
+ 3. **Enter Title**: In the sidebar, enter a title for your space (e.g., "My Todo App")
1472
+ 4. **Deploy**: Click the "πŸš€ Deploy to Space" button
1473
+
1474
+ ### What Happens
1475
+ - Your application will be deployed to Hugging Face Spaces under your account
1476
+ - You'll get a shareable URL (e.g., `https://huggingface.co/spaces/yourusername/my-app-1234567890`)
1477
+ - The deployment includes professional styling and documentation
1478
+
1479
+ ### Troubleshooting
1480
+ If deployment fails:
1481
+ - Make sure you're logged in with the correct account
1482
+ - Ensure you granted all required permissions during login
1483
+ - Try logging out and logging back in
1484
+ - Check that your Hugging Face account can create repositories
1485
+
1486
+ ---
1487
+ *Your application will be deployed to Hugging Face Spaces and you'll get a shareable URL!*""",
1488
  label="Deployment Status"
1489
  )
1490
  with gr.Tab("History"):