codeboosterstech commited on
Commit
9fbf50e
·
verified ·
1 Parent(s): 2ea4c61

Upload 9 files

Browse files
Huggface/.env ADDED
@@ -0,0 +1 @@
 
 
1
+ GROQ_API_KEY=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
Huggface/HuggfaceAgent.ipynb ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# 🐝 Hugging Face Space Creator Agent\n",
8
+ "\n",
9
+ "Run this notebook to launch the Agent Creator. This tool allows you to convert code to Gradio apps and deploy them to Hugging Face Spaces."
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "# @title 1. Install Dependencies\n",
19
+ "!pip install -q gradio langchain-groq huggingface_hub python-dotenv nbconvert beautifulsoup4"
20
+ ]
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "execution_count": null,
25
+ "metadata": {},
26
+ "outputs": [],
27
+ "source": [
28
+ "# @title 2. Configuration\n",
29
+ "import os\n",
30
+ "from google.colab import userdata\n",
31
+ "\n",
32
+ "# Try to get from Colab Secrets, otherwise verify env\n",
33
+ "try:\n",
34
+ " os.environ[\"GROQ_API_KEY\"] = userdata.get('GROQ_API_KEY')\n",
35
+ "except (ImportError, AttributeError, Exception):\n",
36
+ " pass\n",
37
+ "\n",
38
+ "if not os.environ.get(\"GROQ_API_KEY\"):\n",
39
+ " print(\"⚠️ GROQ_API_KEY not found in secrets. Please set it manually below or rely on the UI input if we implemented that (code currently expects env var).\")\n",
40
+ " key = input(\"Enter your GROQ_API_KEY: \")\n",
41
+ " os.environ[\"GROQ_API_KEY\"] = key"
42
+ ]
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "execution_count": null,
47
+ "metadata": {},
48
+ "outputs": [],
49
+ "source": [
50
+ "# @title 3. Define Backend Logic\n",
51
+ "\n",
52
+ "import os\n",
53
+ "from langchain_groq import ChatGroq\n",
54
+ "from langchain_core.prompts import ChatPromptTemplate\n",
55
+ "from langchain_core.output_parsers import JsonOutputParser\n",
56
+ "from typing import Dict, Any, Optional\n",
57
+ "import json\n",
58
+ "from huggingface_hub import HfApi, create_repo\n",
59
+ "import zipfile\n",
60
+ "import io\n",
61
+ "\n",
62
+ "# --- Converter Logic ---\n",
63
+ "def convert_code(input_code: str, model_name: str = \"llama-3.3-70b-versatile\") -> Dict[str, str]:\n",
64
+ " \"\"\"\n",
65
+ " Converts input Python/IPYNB code into a Gradio app structure.\n",
66
+ " Returns a dictionary containing app.py, requirements.txt, and README.md content.\n",
67
+ " \"\"\"\n",
68
+ " \n",
69
+ " # Check for API Key\n",
70
+ " if not os.environ.get(\"GROQ_API_KEY\"):\n",
71
+ " raise ValueError(\"GROQ_API_KEY environment variable is not set.\")\n",
72
+ "\n",
73
+ " chat = ChatGroq(temperature=0, model_name=model_name)\n",
74
+ "\n",
75
+ " system_prompt = \"\"\"You are an expert Python developer specializing in Gradio and Hugging Face Spaces. \n",
76
+ " Your task is to convert the provided Python code (which might be a script or a notebook content) into a deployable Gradio web application.\n",
77
+ " \n",
78
+ " You must output a JSON object with exactly three keys:\n",
79
+ " 1. \"app_py\": The complete code for app.py. It must use Gradio to create a UI for the functionality in the source code. Ensure all imports are correct.\n",
80
+ " 2. \"requirements_txt\": A list of dependencies required to run the app. Include 'gradio'.\n",
81
+ " 3. \"readme_md\": A README.md file customized for a Hugging Face Space.\n",
82
+ " \n",
83
+ " Rules for app.py:\n",
84
+ " - Encapsulate logic in functions.\n",
85
+ " - Create a professional Gradio interface `demo = gr.Interface(...)` or `with gr.Blocks() as demo: ...`.\n",
86
+ " - Ensure `demo.launch()` is called at the end if it's main, but standard HF spaces just look for `demo` object or run the script.\n",
87
+ " - Handle potential errors gracefully.\n",
88
+ " \n",
89
+ " Do not include markdown triple backticks in the JSON values. The values should be raw string content.\n",
90
+ " \"\"\"\n",
91
+ "\n",
92
+ " human_template = \"Convert this code into a Gradio app:\\n\\n{code}\"\n",
93
+ " \n",
94
+ " prompt = ChatPromptTemplate.from_messages([\n",
95
+ " (\"system\", system_prompt),\n",
96
+ " (\"human\", human_template)\n",
97
+ " ])\n",
98
+ "\n",
99
+ " chain = prompt | chat | JsonOutputParser()\n",
100
+ "\n",
101
+ " try:\n",
102
+ " result = chain.invoke({\"code\": input_code})\n",
103
+ " return result\n",
104
+ " except Exception as e:\n",
105
+ " # Fallback or error handling\n",
106
+ " raise RuntimeError(f\"Failed to generate code: {str(e)}\")\n",
107
+ "\n",
108
+ "def parse_notebook(notebook_content: dict) -> str:\n",
109
+ " \"\"\"Extracts code cells from a notebook dictionary.\"\"\"\n",
110
+ " code = []\n",
111
+ " for cell in notebook_content.get('cells', []):\n",
112
+ " if cell.get('cell_type') == 'code':\n",
113
+ " code.append(\"\".join(cell.get('source', [])))\n",
114
+ " return \"\\n\\n\".join(code)\n",
115
+ "\n",
116
+ "# --- Deployer Logic ---\n",
117
+ "def deploy_to_space(\n",
118
+ " token: str, \n",
119
+ " space_name: str, \n",
120
+ " files: Dict[str, str], \n",
121
+ " username: Optional[str] = None\n",
122
+ ") -> str:\n",
123
+ " \"\"\"\n",
124
+ " Deploys the given files to a Hugging Face Space.\n",
125
+ " Returns the URL of the deployed space.\n",
126
+ " \"\"\"\n",
127
+ " if not token:\n",
128
+ " raise ValueError(\"Hugging Face Token is required.\")\n",
129
+ "\n",
130
+ " api = HfApi(token=token)\n",
131
+ " \n",
132
+ " # Authenticate and get user\n",
133
+ " try:\n",
134
+ " user_info = api.whoami()\n",
135
+ " if not username:\n",
136
+ " username = user_info['name']\n",
137
+ " except Exception as e:\n",
138
+ " raise ValueError(f\"Invalid Token: {str(e)}\")\n",
139
+ "\n",
140
+ " repo_id = f\"{username}/{space_name}\"\n",
141
+ "\n",
142
+ " # Create Repo if not exists\n",
143
+ " try:\n",
144
+ " api.create_repo(\n",
145
+ " repo_id=repo_id,\n",
146
+ " repo_type=\"space\",\n",
147
+ " space_sdk=\"gradio\",\n",
148
+ " exist_ok=True,\n",
149
+ " private=False # Default to public, can be changed\n",
150
+ " )\n",
151
+ " except Exception as e:\n",
152
+ " print(f\"Repo creation/check status: {e}\")\n",
153
+ "\n",
154
+ " try:\n",
155
+ " for filename, content in files.items():\n",
156
+ " content_bytes = content.encode('utf-8')\n",
157
+ " api.upload_file(\n",
158
+ " path_or_fileobj=content_bytes,\n",
159
+ " path_in_repo=filename,\n",
160
+ " repo_id=repo_id,\n",
161
+ " repo_type=\"space\",\n",
162
+ " commit_message=f\"Update {filename} via Agent\"\n",
163
+ " )\n",
164
+ " \n",
165
+ " return f\"https://huggingface.co/spaces/{repo_id}\"\n",
166
+ " \n",
167
+ " except Exception as e:\n",
168
+ " raise RuntimeError(f\"Deployment Failed: {str(e)}\")\n",
169
+ "\n",
170
+ "# --- Utils ---\n",
171
+ "def create_zip_archive(files: dict) -> bytes:\n",
172
+ " \"\"\"Creates a zip archive in memory from a dictionary of filename: content.\"\"\"\n",
173
+ " zip_buffer = io.BytesIO()\n",
174
+ " with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:\n",
175
+ " for filename, content in files.items():\n",
176
+ " zip_file.writestr(filename, content)\n",
177
+ " zip_buffer.seek(0)\n",
178
+ " return zip_buffer.getvalue()\n",
179
+ "\n",
180
+ "def extract_code_from_ipynb(ipynb_content: str) -> str:\n",
181
+ " \"\"\"Extracts code cells from ipynb json string.\"\"\"\n",
182
+ " try:\n",
183
+ " data = json.loads(ipynb_content)\n",
184
+ " code_cells = []\n",
185
+ " for cell in data.get('cells', []):\n",
186
+ " if cell.get('cell_type') == 'code':\n",
187
+ " source = cell.get('source', [])\n",
188
+ " if isinstance(source, list):\n",
189
+ " code_cells.append(''.join(source))\n",
190
+ " elif isinstance(source, str):\n",
191
+ " code_cells.append(source)\n",
192
+ " return '\\n\\n'.join(code_cells)\n",
193
+ " except json.JSONDecodeError:\n",
194
+ " return ipynb_content"
195
+ ]
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "execution_count": null,
200
+ "metadata": {},
201
+ "outputs": [],
202
+ "source": [
203
+ "# @title 4. Launch Application\n",
204
+ "import gradio as gr\n",
205
+ "import tempfile\n",
206
+ "\n",
207
+ "# Custom CSS\n",
208
+ "custom_css = \"\"\"\n",
209
+ ":root {\n",
210
+ " --primary-color: #FFD700; /* Gold/Yellow */\n",
211
+ " --secondary-color: #1a1a1a; /* Dark Gray/Black */\n",
212
+ " --text-color: #333333;\n",
213
+ " --bg-color: #f4f4f4;\n",
214
+ "}\n",
215
+ "body { background-color: var(--bg-color); font-family: 'Roboto', sans-serif; }\n",
216
+ "gradio-app { background-color: var(--bg-color) !important; }\n",
217
+ ".gradio-container { max-width: 1200px !important; }\n",
218
+ "button.primary { \n",
219
+ " background-color: var(--primary-color) !important; \n",
220
+ " color: var(--secondary-color) !important; \n",
221
+ " font-weight: bold !important; \n",
222
+ " border: none !important; \n",
223
+ "}\n",
224
+ "\"\"\"\n",
225
+ "\n",
226
+ "def process_and_deploy(input_text, input_file, hf_token, space_name, deploy_mode):\n",
227
+ " try:\n",
228
+ " # 1. Get Source Code\n",
229
+ " code_content = \"\"\n",
230
+ " if input_file is not None:\n",
231
+ " if input_file.name.endswith('.ipynb'):\n",
232
+ " with open(input_file.name, 'r', encoding='utf-8') as f:\n",
233
+ " content = f.read()\n",
234
+ " code_content = extract_code_from_ipynb(content)\n",
235
+ " else:\n",
236
+ " with open(input_file.name, 'r', encoding='utf-8') as f:\n",
237
+ " code_content = f.read()\n",
238
+ " elif input_text.strip():\n",
239
+ " code_content = input_text\n",
240
+ " else:\n",
241
+ " return None, \"Please provide either a file or paste code.\"\n",
242
+ "\n",
243
+ " if not code_content.strip():\n",
244
+ " return None, \"No code found to convert.\"\n",
245
+ "\n",
246
+ " # 2. Convert\n",
247
+ " try:\n",
248
+ " conversion_result = convert_code(code_content)\n",
249
+ " except Exception as e:\n",
250
+ " return None, f\"AI Conversion Failed: {str(e)}\"\n",
251
+ "\n",
252
+ " files_dict = {\n",
253
+ " \"app.py\": conversion_result[\"app_py\"],\n",
254
+ " \"requirements.txt\": conversion_result[\"requirements_txt\"],\n",
255
+ " \"README.md\": conversion_result[\"readme_md\"]\n",
256
+ " }\n",
257
+ "\n",
258
+ " # 3. Zip\n",
259
+ " zip_bytes = create_zip_archive(files_dict)\n",
260
+ " temp_dir = tempfile.mkdtemp()\n",
261
+ " zip_path = os.path.join(temp_dir, \"huggingface_space_files.zip\")\n",
262
+ " with open(zip_path, \"wb\") as f:\n",
263
+ " f.write(zip_bytes)\n",
264
+ " \n",
265
+ " status_msg = \"Conversion Successful! Download the zip below.\"\n",
266
+ " \n",
267
+ " # 4. Deploy\n",
268
+ " if deploy_mode == \"Convert & Deploy to HF Space\":\n",
269
+ " if not hf_token or not space_name:\n",
270
+ " status_msg += \"\\n\\nDeployment Skipped: Missing HF Token or Space Name.\"\n",
271
+ " else:\n",
272
+ " try:\n",
273
+ " deploy_url = deploy_to_space(hf_token, space_name, files_dict)\n",
274
+ " status_msg += f\"\\n\\nSuccessfully Deployed to: {deploy_url}\"\n",
275
+ " except Exception as e:\n",
276
+ " status_msg += f\"\\n\\nDeployment Failed: {str(e)}\"\n",
277
+ "\n",
278
+ " return zip_path, status_msg\n",
279
+ "\n",
280
+ " except Exception as e:\n",
281
+ " return None, f\"An unexpected error occurred: {str(e)}\"\n",
282
+ "\n",
283
+ "with gr.Blocks(css=custom_css, title=\"HF Agent Creator\") as demo:\n",
284
+ " with gr.Row():\n",
285
+ " gr.Markdown(\"# 🐝 Hugging Face Space Creator Agent\")\n",
286
+ " \n",
287
+ " gr.Markdown(\"Transform your local Python scripts or Jupyter Notebooks into ready-to-deploy Hugging Face Spaces instantly.\")\n",
288
+ " \n",
289
+ " with gr.Row():\n",
290
+ " with gr.Column(scale=1):\n",
291
+ " gr.Markdown(\"### 1. Source Code\")\n",
292
+ " with gr.Tabs():\n",
293
+ " with gr.TabItem(\"Upload File\"):\n",
294
+ " file_input = gr.File(label=\"Upload .py or .ipynb file\", file_types=[\".py\", \".ipynb\"])\n",
295
+ " with gr.TabItem(\"Paste Code\"):\n",
296
+ " text_input = gr.Code(label=\"Paste your Python code\", language=\"python\")\n",
297
+ " \n",
298
+ " with gr.Column(scale=1):\n",
299
+ " gr.Markdown(\"### 2. Deployment Details\")\n",
300
+ " hf_token = gr.Textbox(label=\"Hugging Face Access Token (Write)\", type=\"password\", placeholder=\"hf_...\")\n",
301
+ " space_name = gr.Textbox(label=\"New Space Name\", placeholder=\"my-awesome-agent\")\n",
302
+ " action_radio = gr.Radio([\"Convert Only\", \"Convert & Deploy to HF Space\"], label=\"Action\", value=\"Convert Only\")\n",
303
+ " submit_btn = gr.Button(\"Generate Agent\", variant=\"primary\", size=\"lg\")\n",
304
+ "\n",
305
+ " with gr.Row():\n",
306
+ " with gr.Group():\n",
307
+ " gr.Markdown(\"### 3. Results\")\n",
308
+ " status_output = gr.Markdown(label=\"Status Console\")\n",
309
+ " zip_output = gr.File(label=\"Download Generated Files\")\n",
310
+ "\n",
311
+ " submit_btn.click(\n",
312
+ " fn=process_and_deploy,\n",
313
+ " inputs=[text_input, file_input, hf_token, space_name, action_radio],\n",
314
+ " outputs=[zip_output, status_output]\n",
315
+ " )\n",
316
+ "\n",
317
+ "demo.launch(debug=True, share=True)\n"
318
+ ]
319
+ }
320
+ ],
321
+ "metadata": {
322
+ "kernelspec": {
323
+ "display_name": "Python 3",
324
+ "language": "python",
325
+ "name": "python3"
326
+ },
327
+ "language_info": {
328
+ "codemirror_mode": {
329
+ "name": "ipython",
330
+ "version": 3
331
+ },
332
+ "file_extension": ".py",
333
+ "mimetype": "text/x-python",
334
+ "name": "python",
335
+ "nbconvert_exporter": "python",
336
+ "pygments_lexer": "ipython3",
337
+ "version": "3.10.12"
338
+ }
339
+ },
340
+ "nbformat": 4,
341
+ "nbformat_minor": 5
342
+ }
Huggface/app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from dotenv import load_dotenv
4
+
5
+ load_dotenv()
6
+ import tempfile
7
+ from backend.converter import convert_code
8
+ from backend.deployer import deploy_to_space
9
+ from backend.utils import create_zip_archive, extract_code_from_ipynb
10
+ import json
11
+
12
+ # Load CSS
13
+ with open("assets/style.css", "r") as f:
14
+ custom_css = f.read()
15
+
16
+ def process_and_deploy(
17
+ input_text,
18
+ input_file,
19
+ hf_token,
20
+ space_name,
21
+ deploy_mode
22
+ ):
23
+ try:
24
+ # 1. Get Source Code
25
+ code_content = ""
26
+ if input_file is not None:
27
+ # Determine file type
28
+ if input_file.name.endswith('.ipynb'):
29
+ with open(input_file.name, 'r', encoding='utf-8') as f:
30
+ content = f.read()
31
+ code_content = extract_code_from_ipynb(content)
32
+ else:
33
+ with open(input_file.name, 'r', encoding='utf-8') as f:
34
+ code_content = f.read()
35
+ elif input_text.strip():
36
+ code_content = input_text
37
+ else:
38
+ return None, "Please provide either a file or paste code."
39
+
40
+ if not code_content.strip():
41
+ return None, "No code found to convert."
42
+
43
+ # 2. Convert Code using AI Agent
44
+ # Note: We expect GROQ_API_KEY to be set in the environment.
45
+ # If not, we could ask user, but requirements said "place to enter HF tokens", didn't specify Groq key user input.
46
+ # Assuming env var is present or handled globally.
47
+ try:
48
+ conversion_result = convert_code(code_content)
49
+ except Exception as e:
50
+ return None, f"AI Conversion Failed: {str(e)}"
51
+
52
+ files_dict = {
53
+ "app.py": conversion_result["app_py"],
54
+ "requirements.txt": conversion_result["requirements_txt"],
55
+ "README.md": conversion_result["readme_md"]
56
+ }
57
+
58
+ # 3. Create Zip
59
+ zip_bytes = create_zip_archive(files_dict)
60
+
61
+ # Create a temp file for the zip output
62
+ # Gradio File component needs a real path
63
+ temp_dir = tempfile.mkdtemp()
64
+ zip_path = os.path.join(temp_dir, "huggingface_space_files.zip")
65
+ with open(zip_path, "wb") as f:
66
+ f.write(zip_bytes)
67
+
68
+ status_msg = "Conversion Successful! Download the zip below."
69
+
70
+ # 4. Deploy if requested
71
+ deploy_url = ""
72
+ if deploy_mode == "Convert & Deploy to HF Space":
73
+ if not hf_token or not space_name:
74
+ status_msg += "\n\nDeployment Skipped: Missing HF Token or Space Name."
75
+ else:
76
+ try:
77
+ deploy_url = deploy_to_space(hf_token, space_name, files_dict)
78
+ status_msg += f"\n\nSuccessfully Deployed to: {deploy_url}"
79
+ except Exception as e:
80
+ status_msg += f"\n\nDeployment Failed: {str(e)}"
81
+
82
+ return zip_path, status_msg
83
+
84
+ except Exception as e:
85
+ return None, f"An unexpected error occurred: {str(e)}"
86
+
87
+
88
+ with gr.Blocks(css=custom_css, title="HF Agent Creator") as demo:
89
+
90
+ with gr.Row(elem_id="header-title"):
91
+ gr.Markdown("# 🐝 Hugging Face Space Creator Agent")
92
+
93
+ gr.Markdown("Transform your local Python scripts or Jupyter Notebooks into ready-to-deploy Hugging Face Spaces instantly.")
94
+
95
+ with gr.Row():
96
+ with gr.Column(scale=1):
97
+ with gr.Group(elem_classes="panel-container"):
98
+ gr.Markdown("### 1. Source Code")
99
+ input_tab = gr.Tabs()
100
+ with input_tab:
101
+ with gr.TabItem("Upload File"):
102
+ file_input = gr.File(
103
+ label="Upload .py or .ipynb file",
104
+ file_types=[".py", ".ipynb"]
105
+ )
106
+ with gr.TabItem("Paste Code"):
107
+ text_input = gr.Code(
108
+ label="Paste your Python code",
109
+ language="python"
110
+ )
111
+
112
+ with gr.Column(scale=1):
113
+ with gr.Group(elem_classes="panel-container"):
114
+ gr.Markdown("### 2. Deployment Details")
115
+ hf_token = gr.Textbox(
116
+ label="Hugging Face Access Token (Write)",
117
+ type="password",
118
+ placeholder="hf_..."
119
+ )
120
+ space_name = gr.Textbox(
121
+ label="New Space Name",
122
+ placeholder="my-awesome-agent"
123
+ )
124
+ action_radio = gr.Radio(
125
+ ["Convert Only", "Convert & Deploy to HF Space"],
126
+ label="Action",
127
+ value="Convert Only"
128
+ )
129
+ submit_btn = gr.Button("Generate Agent", variant="primary", size="lg")
130
+
131
+ with gr.Row():
132
+ with gr.Group(elem_classes="panel-container"):
133
+ gr.Markdown("### 3. Results")
134
+ status_output = gr.Markdown(label="Status Console")
135
+ zip_output = gr.File(label="Download Generated Files")
136
+
137
+ submit_btn.click(
138
+ fn=process_and_deploy,
139
+ inputs=[text_input, file_input, hf_token, space_name, action_radio],
140
+ outputs=[zip_output, status_output]
141
+ )
142
+
143
+ if __name__ == "__main__":
144
+ demo.launch()
Huggface/assets/style.css ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --primary-color: #FFD700; /* Gold/Yellow */
3
+ --secondary-color: #1a1a1a; /* Dark Gray/Black */
4
+ --text-color: #333333;
5
+ --bg-color: #f4f4f4;
6
+ }
7
+
8
+ body {
9
+ background-color: var(--bg-color);
10
+ font-family: 'Roboto', sans-serif;
11
+ }
12
+
13
+ gradio-app {
14
+ background-color: var(--bg-color) !important;
15
+ }
16
+
17
+ .gradio-container {
18
+ max-width: 1200px !important;
19
+ }
20
+
21
+ /* Customizing Buttons */
22
+ button.primary {
23
+ background-color: var(--primary-color) !important;
24
+ color: var(--secondary-color) !important;
25
+ font-weight: bold !important;
26
+ border: none !important;
27
+ transition: transform 0.1s;
28
+ }
29
+
30
+ button.primary:hover {
31
+ transform: scale(1.02);
32
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
33
+ }
34
+
35
+ /* Header Styling */
36
+ #header-title {
37
+ text-align: center;
38
+ color: var(--secondary-color);
39
+ margin-bottom: 20px;
40
+ }
41
+
42
+ #header-title h1 {
43
+ font-size: 2.5rem;
44
+ border-bottom: 4px solid var(--primary-color);
45
+ display: inline-block;
46
+ padding-bottom: 5px;
47
+ }
48
+
49
+ /* Panel Styling */
50
+ .panel-container {
51
+ background: white;
52
+ border-radius: 12px;
53
+ padding: 20px;
54
+ box-shadow: 0 4px 12px rgba(0,0,0,0.08);
55
+ border-top: 5px solid var(--primary-color);
56
+ }
Huggface/backend/__init__.py ADDED
File without changes
Huggface/backend/converter.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain_groq import ChatGroq
3
+ from langchain_core.prompts import ChatPromptTemplate
4
+ from langchain_core.output_parsers import JsonOutputParser
5
+ from typing import Dict, Any
6
+ import json
7
+
8
+ def convert_code(input_code: str, model_name: str = "llama-3.3-70b-versatile") -> Dict[str, str]:
9
+ """
10
+ Converts input Python/IPYNB code into a Gradio app structure.
11
+ Returns a dictionary containing app.py, requirements.txt, and README.md content.
12
+ """
13
+
14
+ # Check for API Key
15
+ if not os.environ.get("GROQ_API_KEY"):
16
+ raise ValueError("GROQ_API_KEY environment variable is not set.")
17
+
18
+ chat = ChatGroq(temperature=0, model_name=model_name)
19
+
20
+ system_prompt = """You are an expert Python developer specializing in Gradio and Hugging Face Spaces.
21
+ Your task is to convert the provided Python code (which might be a script or a notebook content) into a deployable Gradio web application.
22
+
23
+ You must output a JSON object with exactly three keys:
24
+ 1. "app_py": The complete code for app.py. It must use Gradio to create a UI for the functionality in the source code. Ensure all imports are correct.
25
+ 2. "requirements_txt": A list of dependencies required to run the app. Include 'gradio'.
26
+ 3. "readme_md": A README.md file customized for a Hugging Face Space.
27
+
28
+ Rules for app.py:
29
+ - Encapsulate logic in functions.
30
+ - Create a professional Gradio interface `demo = gr.Interface(...)` or `with gr.Blocks() as demo: ...`.
31
+ - Ensure `demo.launch()` is called at the end if it's main, but standard HF spaces just look for `demo` object or run the script.
32
+ - Handle potential errors gracefully.
33
+
34
+ Do not include markdown triple backticks in the JSON values. The values should be raw string content.
35
+ """
36
+
37
+ human_template = "Convert this code into a Gradio app:\n\n{code}"
38
+
39
+ prompt = ChatPromptTemplate.from_messages([
40
+ ("system", system_prompt),
41
+ ("human", human_template)
42
+ ])
43
+
44
+ chain = prompt | chat | JsonOutputParser()
45
+
46
+ try:
47
+ result = chain.invoke({"code": input_code})
48
+ return result
49
+ except Exception as e:
50
+ # Fallback or error handling
51
+ raise RuntimeError(f"Failed to generate code: {str(e)}")
52
+
53
+ def parse_notebook(notebook_content: dict) -> str:
54
+ """Extracts code cells from a notebook dictionary."""
55
+ code = []
56
+ for cell in notebook_content.get('cells', []):
57
+ if cell.get('cell_type') == 'code':
58
+ code.append("".join(cell.get('source', [])))
59
+ return "\n\n".join(code)
Huggface/backend/deployer.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import HfApi, create_repo
2
+ from typing import Dict, Optional
3
+ import tempfile
4
+ import os
5
+
6
+ def deploy_to_space(
7
+ token: str,
8
+ space_name: str,
9
+ files: Dict[str, str],
10
+ username: Optional[str] = None
11
+ ) -> str:
12
+ """
13
+ Deploys the given files to a Hugging Face Space.
14
+ Returns the URL of the deployed space.
15
+ """
16
+ if not token:
17
+ raise ValueError("Hugging Face Token is required.")
18
+
19
+ api = HfApi(token=token)
20
+
21
+ # Authenticate and get user
22
+ try:
23
+ user_info = api.whoami()
24
+ if not username:
25
+ username = user_info['name']
26
+ except Exception as e:
27
+ raise ValueError(f"Invalid Token: {str(e)}")
28
+
29
+ repo_id = f"{username}/{space_name}"
30
+
31
+ # Create Repo if not exists
32
+ try:
33
+ api.create_repo(
34
+ repo_id=repo_id,
35
+ repo_type="space",
36
+ space_sdk="gradio",
37
+ exist_ok=True,
38
+ private=False # Default to public, can be changed
39
+ )
40
+ except Exception as e:
41
+ print(f"Repo creation/check status: {e}")
42
+
43
+ # Prepare files for upload
44
+ operations = []
45
+
46
+ # Create a temporary directory to write files to upload
47
+ # Note: api.upload_file or upload_folder can be used.
48
+ # We will use upload_file loop for simplicity with in-memory strings
49
+
50
+ # Ideally we use commit_operations for atomicity but simple upload loop is fine for MVP
51
+ # Let's use upload_file content directly
52
+
53
+ try:
54
+ for filename, content in files.items():
55
+ # Convert string content to bytes
56
+ content_bytes = content.encode('utf-8')
57
+
58
+ api.upload_file(
59
+ path_or_fileobj=content_bytes,
60
+ path_in_repo=filename,
61
+ repo_id=repo_id,
62
+ repo_type="space",
63
+ commit_message=f"Update {filename} via Agent"
64
+ )
65
+
66
+ return f"https://huggingface.co/spaces/{repo_id}"
67
+
68
+ except Exception as e:
69
+ raise RuntimeError(f"Deployment Failed: {str(e)}")
Huggface/backend/utils.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import zipfile
2
+ import io
3
+ import json
4
+
5
+ def create_zip_archive(files: dict) -> bytes:
6
+ """Creates a zip archive in memory from a dictionary of filename: content."""
7
+ zip_buffer = io.BytesIO()
8
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
9
+ for filename, content in files.items():
10
+ zip_file.writestr(filename, content)
11
+ zip_buffer.seek(0)
12
+ return zip_buffer.getvalue()
13
+
14
+ def read_file_content(file_obj) -> str:
15
+ """Reads content from a file object (GradIO file wrapper) or path."""
16
+ if hasattr(file_obj, 'name'):
17
+ path = file_obj.name
18
+ else:
19
+ path = file_obj
20
+
21
+ try:
22
+ with open(path, 'r', encoding='utf-8') as f:
23
+ return f.read()
24
+ except UnicodeDecodeError:
25
+ # Fallback for some notebook formats if needed
26
+ with open(path, 'r', encoding='latin-1') as f:
27
+ return f.read()
28
+
29
+ def extract_code_from_ipynb(ipynb_content: str) -> str:
30
+ """Extracts code cells from ipynb json string."""
31
+ try:
32
+ data = json.loads(ipynb_content)
33
+ code_cells = []
34
+ for cell in data.get('cells', []):
35
+ if cell.get('cell_type') == 'code':
36
+ source = cell.get('source', [])
37
+ if isinstance(source, list):
38
+ code_cells.append(''.join(source))
39
+ elif isinstance(source, str):
40
+ code_cells.append(source)
41
+ return '\n\n'.join(code_cells)
42
+ except json.JSONDecodeError:
43
+ return ipynb_content # Validation failed or not json, treat as raw text?
Huggface/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ langchain-groq
3
+ huggingface_hub
4
+ python-dotenv
5
+ nbconvert
6
+ beautifulsoup4