Spaces:
Sleeping
Sleeping
File size: 5,452 Bytes
9fbf50e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
import gradio as gr
import os
from dotenv import load_dotenv
load_dotenv()
import tempfile
from backend.converter import convert_code
from backend.deployer import deploy_to_space
from backend.utils import create_zip_archive, extract_code_from_ipynb
import json
# Load CSS
with open("assets/style.css", "r") as f:
custom_css = f.read()
def process_and_deploy(
input_text,
input_file,
hf_token,
space_name,
deploy_mode
):
try:
# 1. Get Source Code
code_content = ""
if input_file is not None:
# Determine file type
if input_file.name.endswith('.ipynb'):
with open(input_file.name, 'r', encoding='utf-8') as f:
content = f.read()
code_content = extract_code_from_ipynb(content)
else:
with open(input_file.name, 'r', encoding='utf-8') as f:
code_content = f.read()
elif input_text.strip():
code_content = input_text
else:
return None, "Please provide either a file or paste code."
if not code_content.strip():
return None, "No code found to convert."
# 2. Convert Code using AI Agent
# Note: We expect GROQ_API_KEY to be set in the environment.
# If not, we could ask user, but requirements said "place to enter HF tokens", didn't specify Groq key user input.
# Assuming env var is present or handled globally.
try:
conversion_result = convert_code(code_content)
except Exception as e:
return None, f"AI Conversion Failed: {str(e)}"
files_dict = {
"app.py": conversion_result["app_py"],
"requirements.txt": conversion_result["requirements_txt"],
"README.md": conversion_result["readme_md"]
}
# 3. Create Zip
zip_bytes = create_zip_archive(files_dict)
# Create a temp file for the zip output
# Gradio File component needs a real path
temp_dir = tempfile.mkdtemp()
zip_path = os.path.join(temp_dir, "huggingface_space_files.zip")
with open(zip_path, "wb") as f:
f.write(zip_bytes)
status_msg = "Conversion Successful! Download the zip below."
# 4. Deploy if requested
deploy_url = ""
if deploy_mode == "Convert & Deploy to HF Space":
if not hf_token or not space_name:
status_msg += "\n\nDeployment Skipped: Missing HF Token or Space Name."
else:
try:
deploy_url = deploy_to_space(hf_token, space_name, files_dict)
status_msg += f"\n\nSuccessfully Deployed to: {deploy_url}"
except Exception as e:
status_msg += f"\n\nDeployment Failed: {str(e)}"
return zip_path, status_msg
except Exception as e:
return None, f"An unexpected error occurred: {str(e)}"
with gr.Blocks(css=custom_css, title="HF Agent Creator") as demo:
with gr.Row(elem_id="header-title"):
gr.Markdown("# 🐝 Hugging Face Space Creator Agent")
gr.Markdown("Transform your local Python scripts or Jupyter Notebooks into ready-to-deploy Hugging Face Spaces instantly.")
with gr.Row():
with gr.Column(scale=1):
with gr.Group(elem_classes="panel-container"):
gr.Markdown("### 1. Source Code")
input_tab = gr.Tabs()
with input_tab:
with gr.TabItem("Upload File"):
file_input = gr.File(
label="Upload .py or .ipynb file",
file_types=[".py", ".ipynb"]
)
with gr.TabItem("Paste Code"):
text_input = gr.Code(
label="Paste your Python code",
language="python"
)
with gr.Column(scale=1):
with gr.Group(elem_classes="panel-container"):
gr.Markdown("### 2. Deployment Details")
hf_token = gr.Textbox(
label="Hugging Face Access Token (Write)",
type="password",
placeholder="hf_..."
)
space_name = gr.Textbox(
label="New Space Name",
placeholder="my-awesome-agent"
)
action_radio = gr.Radio(
["Convert Only", "Convert & Deploy to HF Space"],
label="Action",
value="Convert Only"
)
submit_btn = gr.Button("Generate Agent", variant="primary", size="lg")
with gr.Row():
with gr.Group(elem_classes="panel-container"):
gr.Markdown("### 3. Results")
status_output = gr.Markdown(label="Status Console")
zip_output = gr.File(label="Download Generated Files")
submit_btn.click(
fn=process_and_deploy,
inputs=[text_input, file_input, hf_token, space_name, action_radio],
outputs=[zip_output, status_output]
)
if __name__ == "__main__":
demo.launch()
|