akhaliq HF Staff commited on
Commit
a6a4576
·
1 Parent(s): 3ca98cc
Files changed (1) hide show
  1. app.py +24 -140
app.py CHANGED
@@ -1217,7 +1217,7 @@ with gr.Blocks(
1217
  label="app name (e.g. my-cool-app)",
1218
  placeholder="Enter your app name",
1219
  lines=1,
1220
- visible=True
1221
  )
1222
  sdk_choices = [
1223
  ("Gradio (Python)", "gradio"),
@@ -1228,9 +1228,9 @@ with gr.Blocks(
1228
  choices=[x[0] for x in sdk_choices],
1229
  value="Static (HTML)",
1230
  label="App SDK",
1231
- visible=True
1232
  )
1233
- deploy_btn = gr.Button("🚀 Deploy App", variant="primary", visible=True)
1234
  deploy_status = gr.Markdown(visible=False, label="Deploy status")
1235
  # --- End move ---
1236
  search_toggle = gr.Checkbox(
@@ -1265,19 +1265,8 @@ with gr.Blocks(
1265
  if m['name'] == model_name:
1266
  return m, update_image_input_visibility(m)
1267
  return AVAILABLE_MODELS[0], update_image_input_visibility(AVAILABLE_MODELS[0])
1268
-
1269
- def on_sdk_change(sdk_name):
1270
- # Automatically set language based on SDK selection
1271
- if sdk_name == "Gradio (Python)":
1272
- return gr.update(value="python"), gr.update(language="python")
1273
- elif sdk_name == "Streamlit (Python)":
1274
- return gr.update(value="python"), gr.update(language="python")
1275
- else: # Static (HTML)
1276
- return gr.update(value="html"), gr.update(language="html")
1277
-
1278
  def save_prompt(input):
1279
  return {setting: {"system": input}}
1280
-
1281
  model_dropdown.change(
1282
  lambda model_name: on_model_change(model_name),
1283
  inputs=model_dropdown,
@@ -1305,13 +1294,6 @@ with gr.Blocks(
1305
  return gr.update(language=get_gradio_language(language))
1306
 
1307
  language_dropdown.change(update_code_language, inputs=language_dropdown, outputs=code_output)
1308
-
1309
- # Add SDK change handler after code_output is defined
1310
- sdk_dropdown.change(
1311
- on_sdk_change,
1312
- inputs=sdk_dropdown,
1313
- outputs=[language_dropdown, code_output]
1314
- )
1315
 
1316
  def preview_logic(code, language):
1317
  if language == "html":
@@ -1319,17 +1301,26 @@ with gr.Blocks(
1319
  else:
1320
  return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>"
1321
 
 
 
1322
 
 
 
1323
 
1324
  btn.click(
1325
  generation_code,
1326
  inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state],
1327
  outputs=[code_output, history, sandbox, history_output]
 
 
 
 
1328
  )
1329
  # Update preview when code or language changes
1330
  code_output.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)
1331
  language_dropdown.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)
1332
  clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])
 
1333
 
1334
  # Deploy to Spaces logic
1335
 
@@ -1367,135 +1358,28 @@ with gr.Blocks(
1367
  # Save code to a temporary file
1368
  if sdk == "static":
1369
  file_name = "index.html"
1370
- app_code = code
1371
- elif sdk == "docker": # Streamlit (Python)
1372
- import shutil
1373
- import os
1374
- import tempfile
1375
- # Create a temp dir for the structure
1376
- temp_dir = tempfile.mkdtemp()
1377
- # 1. Write requirements.txt
1378
- reqs = "altair\npandas\nstreamlit\n"
1379
- req_path = os.path.join(temp_dir, "requirements.txt")
1380
- with open(req_path, "w") as f:
1381
- f.write(reqs)
1382
- # 2. Write Dockerfile (EXACT content as screenshot, with proper line breaks)
1383
- dockerfile_content = '''FROM python:3.9-slim
1384
-
1385
- WORKDIR /app
1386
-
1387
- RUN apt-get update && apt-get install -y \\
1388
- build-essential \\
1389
- curl \\
1390
- software-properties-common \\
1391
- git \\
1392
- && rm -rf /var/lib/apt/lists/*
1393
-
1394
- COPY requirements.txt ./
1395
- COPY src/ ./src/
1396
-
1397
- RUN pip3 install -r requirements.txt
1398
-
1399
- EXPOSE 8501
1400
-
1401
- HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
1402
-
1403
- ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
1404
- '''
1405
- dockerfile_path = os.path.join(temp_dir, "Dockerfile")
1406
- with open(dockerfile_path, "w", encoding="utf-8", newline="\n") as f:
1407
- f.write(dockerfile_content)
1408
- # 3. Write src/streamlit_app.py
1409
- src_dir = os.path.join(temp_dir, "src")
1410
- os.makedirs(src_dir, exist_ok=True)
1411
- app_py_path = os.path.join(src_dir, "streamlit_app.py")
1412
- with open(app_py_path, "w") as f:
1413
- f.write(code)
1414
- # 4. Write README.md in the required format
1415
- readme_content = f'''---
1416
- title: {space_name.strip()}
1417
- emoji: 🚀
1418
- colorFrom: red
1419
- colorTo: red
1420
- sdk: docker
1421
- app_port: 8501
1422
- tags:
1423
- - streamlit
1424
- pinned: false
1425
- short_description: Streamlit template space
1426
- ---
1427
-
1428
- # Welcome to Streamlit!
1429
-
1430
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
1431
-
1432
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community forums](https://discuss.streamlit.io).
1433
- '''
1434
- readme_path = os.path.join(temp_dir, "README.md")
1435
- with open(readme_path, "w", encoding="utf-8") as f:
1436
- f.write(readme_content)
1437
- # Prepare files to upload
1438
- files_to_upload = [
1439
- (req_path, "requirements.txt"),
1440
- (dockerfile_path, "Dockerfile"),
1441
- (app_py_path, "src/streamlit_app.py"),
1442
- (readme_path, "README.md"),
1443
- ]
1444
- else: # Gradio (Python)
1445
  file_name = "app.py"
1446
- # Check if the code is already Python/Gradio code or HTML
1447
- if code.strip().startswith('import gradio') or code.strip().startswith('import gr') or 'gradio' in code.lower():
1448
- # Code is already Python/Gradio, use it directly
1449
- app_code = code
1450
- else:
1451
- # Code is HTML, wrap it in a Gradio app structure
1452
- app_code = wrap_html_in_gradio_app(code)
1453
- with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding='utf-8') as f:
1454
- f.write(app_code)
1455
- temp_path = f.name
1456
- files_to_upload = [(temp_path, file_name)]
1457
- # Upload the file(s)
1458
  try:
1459
- if sdk == "docker": # Streamlit - upload multiple files
1460
- for local_path, repo_path in files_to_upload:
1461
- api.upload_file(
1462
- path_or_fileobj=local_path,
1463
- path_in_repo=repo_path,
1464
- repo_id=repo_id,
1465
- repo_type="space"
1466
- )
1467
- else: # Gradio or Static - upload single file
1468
- api.upload_file(
1469
- path_or_fileobj=temp_path,
1470
- path_in_repo=file_name,
1471
- repo_id=repo_id,
1472
- repo_type="space"
1473
- )
1474
  space_url = f"https://huggingface.co/spaces/{repo_id}"
1475
  return gr.update(value=f"✅ Deployed! [Open your Space here]({space_url})", visible=True)
1476
  except Exception as e:
1477
  return gr.update(value=f"Error uploading file: {e}", visible=True)
1478
- finally:
1479
- # Clean up temporary files
1480
- import os
1481
- if sdk == "docker": # Streamlit - clean up multiple files
1482
- for local_path, _ in files_to_upload:
1483
- try:
1484
- if os.path.exists(local_path):
1485
- os.unlink(local_path)
1486
- except Exception as cleanup_error:
1487
- print(f"Warning: Could not clean up {local_path}: {cleanup_error}")
1488
- else: # Gradio or Static - clean up single file
1489
- try:
1490
- if os.path.exists(temp_path):
1491
- os.unlink(temp_path)
1492
- except Exception as cleanup_error:
1493
- print(f"Warning: Could not clean up {temp_path}: {cleanup_error}")
1494
 
1495
  # Connect the deploy button to the new function
1496
  deploy_btn.click(
1497
  deploy_to_user_space,
1498
- inputs=[code_output, space_name_input, sdk_dropdown, login_button, login_button],
1499
  outputs=deploy_status
1500
  )
1501
  # Keep the old deploy method as fallback (if not logged in, user can still use the old method)
 
1217
  label="app name (e.g. my-cool-app)",
1218
  placeholder="Enter your app name",
1219
  lines=1,
1220
+ visible=False
1221
  )
1222
  sdk_choices = [
1223
  ("Gradio (Python)", "gradio"),
 
1228
  choices=[x[0] for x in sdk_choices],
1229
  value="Static (HTML)",
1230
  label="App SDK",
1231
+ visible=False
1232
  )
1233
+ deploy_btn = gr.Button("🚀 Deploy App", variant="primary", visible=False)
1234
  deploy_status = gr.Markdown(visible=False, label="Deploy status")
1235
  # --- End move ---
1236
  search_toggle = gr.Checkbox(
 
1265
  if m['name'] == model_name:
1266
  return m, update_image_input_visibility(m)
1267
  return AVAILABLE_MODELS[0], update_image_input_visibility(AVAILABLE_MODELS[0])
 
 
 
 
 
 
 
 
 
 
1268
  def save_prompt(input):
1269
  return {setting: {"system": input}}
 
1270
  model_dropdown.change(
1271
  lambda model_name: on_model_change(model_name),
1272
  inputs=model_dropdown,
 
1294
  return gr.update(language=get_gradio_language(language))
1295
 
1296
  language_dropdown.change(update_code_language, inputs=language_dropdown, outputs=code_output)
 
 
 
 
 
 
 
1297
 
1298
  def preview_logic(code, language):
1299
  if language == "html":
 
1301
  else:
1302
  return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>"
1303
 
1304
+ def show_deploy_components(*args):
1305
+ return [gr.Textbox(visible=True), gr.Dropdown(visible=True), gr.Button(visible=True)]
1306
 
1307
+ def hide_deploy_components(*args):
1308
+ return [gr.Textbox(visible=False), gr.Dropdown(visible=False), gr.Button(visible=False)]
1309
 
1310
  btn.click(
1311
  generation_code,
1312
  inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state],
1313
  outputs=[code_output, history, sandbox, history_output]
1314
+ ).then(
1315
+ show_deploy_components,
1316
+ None,
1317
+ [space_name_input, sdk_dropdown, deploy_btn]
1318
  )
1319
  # Update preview when code or language changes
1320
  code_output.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)
1321
  language_dropdown.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)
1322
  clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])
1323
+ clear_btn.click(hide_deploy_components, None, [space_name_input, sdk_dropdown, deploy_btn])
1324
 
1325
  # Deploy to Spaces logic
1326
 
 
1358
  # Save code to a temporary file
1359
  if sdk == "static":
1360
  file_name = "index.html"
1361
+ else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1362
  file_name = "app.py"
1363
+ with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False) as f:
1364
+ f.write(code)
1365
+ temp_path = f.name
1366
+ # Upload the file
 
 
 
 
 
 
 
 
1367
  try:
1368
+ api.upload_file(
1369
+ path_or_fileobj=temp_path,
1370
+ path_in_repo=file_name,
1371
+ repo_id=repo_id,
1372
+ repo_type="space"
1373
+ )
 
 
 
 
 
 
 
 
 
1374
  space_url = f"https://huggingface.co/spaces/{repo_id}"
1375
  return gr.update(value=f"✅ Deployed! [Open your Space here]({space_url})", visible=True)
1376
  except Exception as e:
1377
  return gr.update(value=f"Error uploading file: {e}", visible=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1378
 
1379
  # Connect the deploy button to the new function
1380
  deploy_btn.click(
1381
  deploy_to_user_space,
1382
+ inputs=[code_output, space_name_input, sdk_dropdown],
1383
  outputs=deploy_status
1384
  )
1385
  # Keep the old deploy method as fallback (if not logged in, user can still use the old method)