broadfield-dev commited on
Commit
8a2f1bf
·
verified ·
1 Parent(s): 0729d19

Create docs.py

Browse files
Files changed (1) hide show
  1. docs.py +215 -0
docs.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DOCUMENTATION="""# Assembler Space API Documentation
2
+
3
+ ## Overview
4
+ The **Assembler Space** is a Hugging Face Space that acts as a factory for creating new Hugging Face Spaces dynamically. It exposes a Flask-based API that accepts JSON input containing code, files, parameters, and configuration details. Upon receiving a valid request, it creates a new Space repository on Hugging Face, populates it with the provided files, and triggers its deployment. The API supports multiple Space types (e.g., `gradio`, `static`, `docker`, `streamlit`) and multi-file submissions, making it versatile for generating a wide range of applications.
5
+
6
+ The Assembler Space itself runs as a Docker-based Space on Hugging Face, accessible via a public URL: `https://broadfield-dev-assembler.hf.space`.
7
+
8
+ ## Base URL
9
+ The API is hosted at:
10
+ https://broadfield-dev-assembler.hf.space/create-space
11
+
12
+ ## Endpoints
13
+
14
+ ### `POST /create-space`
15
+ Creates a new Hugging Face Space based on the provided JSON payload.
16
+
17
+ #### Request Format
18
+ - **Method**: `POST`
19
+ - **Content-Type**: `application/json`
20
+ - **Body**: A JSON object with the following fields:
21
+
22
+ | Field | Type | Required | Description |
23
+ |--------------|----------|----------|-----------------------------------------------------------------------------|
24
+ | `space_type` | String | No | The type of Space to create. Options: `gradio`, `static`, `docker`, `streamlit`. Defaults to `gradio` if omitted. |
25
+ | `files` | Object | Yes | A dictionary where keys are filenames (e.g., `app.py`, `index.html`) and values are file contents as strings. |
26
+ | `parameters` | Object | No | A dictionary of key-value pairs to be injected into Python files as `PARAMS` or used by the generated Space’s code. |
27
+
28
+ #### Request Constraints
29
+ - At least one file must be provided in `files`.
30
+ - Filenames in `files` should include extensions (e.g., `.py`, `.html`, `.css`, `.txt`) to ensure correct handling.
31
+ - `space_type` must match one of the supported values, or the request will fail.
32
+ - File contents should be valid for the intended `space_type` (e.g., Python code for `gradio` or `docker`, HTML for `static`).
33
+
34
+ #### Response Format
35
+ - **Content-Type**: `application/json`
36
+ - **Status Codes**:
37
+ - `200 OK`: Space creation succeeded.
38
+ - `400 Bad Request`: Invalid JSON or missing/invalid fields.
39
+ - `500 Internal Server Error`: Unexpected error during Space creation.
40
+ - **Body**: A JSON object with the following fields:
41
+
42
+ | Field | Type | Description |
43
+ |-----------|--------|-----------------------------------------------------------------------------|
44
+ | `message` | String | A brief status message (e.g., `"New Space created"`). |
45
+ | `url` | String | The URL of the newly created Space (e.g., `https://huggingface.co/spaces/<username>/<space-name>`). |
46
+ | `note` | String | Additional information (e.g., deployment time warning). |
47
+ | `error` | String | (Only in error responses) Description of what went wrong. |
48
+
49
+ ### `GET /docs`
50
+ Returns this documentation as plain text in Markdown format.
51
+
52
+ #### Request Format
53
+ - **Method**: `GET`
54
+ - **Content-Type**: None required
55
+
56
+ #### Response Format
57
+ - **Content-Type**: `text/plain`
58
+ - **Status Codes**:
59
+ - `200 OK`: Documentation returned successfully.
60
+ - **Body**: The full Markdown documentation as a string.
61
+
62
+ #### Example Requests and Responses
63
+
64
+ ##### Example 1: Static Space
65
+ **Request (`POST /create-space`):**
66
+ ~~~json
67
+ {
68
+ "space_type": "static",
69
+ "files": {
70
+ "index.html": "<html><body><h1>Hello World</h1><p>Message: {{params['message']}}</p></body></html>",
71
+ "style.css": "h1 { color: green; }"
72
+ },
73
+ "parameters": {
74
+ "message": "Static Space Test"
75
+ }
76
+ }
77
+ ~~~
78
+
79
+ **Response (200 OK):**
80
+ ~~~json
81
+ {
82
+ "message": "New Space created",
83
+ "url": "https://huggingface.co/spaces/broadfield-dev/GeneratedSpace-abc123",
84
+ "note": "It may take a few minutes to build and deploy."
85
+ }
86
+ ~~~
87
+
88
+ **Notes:**
89
+ - Static Spaces don’t automatically process `parameters`. The new Space’s code must handle them (e.g., via JavaScript or server-side templating if added).
90
+
91
+ ##### Example 2: Docker Space with Flask
92
+ **Request (`POST /create-space`):**
93
+ ~~~json
94
+ {
95
+ "space_type": "docker",
96
+ "files": {
97
+ "app.py": "from flask import Flask\\napp = Flask(__name__)\\[email protected]('/')\\ndef home():\\n return f'Hello, {PARAMS['name']}'\\nif __name__ == '__main__':\\n app.run(host='0.0.0.0', port=7860)",
98
+ "requirements.txt": "flask",
99
+ "Dockerfile": "FROM python:3.10-slim\\nWORKDIR /app\\nCOPY . .\\nRUN pip install -r requirements.txt\\nEXPOSE 7860\\nCMD [\\"python\\", \\"app.py\\"]"
100
+ },
101
+ "parameters": {
102
+ "name": "Docker User"
103
+ }
104
+ }
105
+ ~~~
106
+
107
+ **Response (200 OK):**
108
+ ~~~json
109
+ {
110
+ "message": "New Space created",
111
+ "url": "https://huggingface.co/spaces/broadfield-dev/GeneratedSpace-xyz789",
112
+ "note": "It may take a few minutes to build and deploy."
113
+ }
114
+ ~~~
115
+
116
+ **Notes:**
117
+ - The `parameters` are injected into `app.py` as `PARAMS`. The port is set to 7860 to match Hugging Face’s default.
118
+
119
+ ##### Example 3: Gradio Space
120
+ **Request (`POST /create-space`):**
121
+ ~~~json
122
+ {
123
+ "space_type": "gradio",
124
+ "files": {
125
+ "app.py": "import gradio as gr\\ndef greet():\\n return f'Hi, {PARAMS['user']}'\\ninterface = gr.Interface(fn=greet, inputs=None, outputs='text')\\ninterface.launch()"
126
+ },
127
+ "parameters": {
128
+ "user": "Gradio Fan"
129
+ }
130
+ }
131
+ ~~~
132
+
133
+ **Response (200 OK):**
134
+ ~~~json
135
+ {
136
+ "message": "New Space created",
137
+ "url": "https://huggingface.co/spaces/broadfield-dev/GeneratedSpace-def456",
138
+ "note": "It may take a few minutes to build and deploy."
139
+ }
140
+ ~~~
141
+
142
+ ##### Example 4: Invalid Request
143
+ **Request (`POST /create-space`):**
144
+ ~~~json
145
+ {
146
+ "space_type": "invalid",
147
+ "files": {}
148
+ }
149
+ ~~~
150
+
151
+ **Response (400 Bad Request):**
152
+ ~~~json
153
+ {
154
+ "error": "Invalid space_type. Must be one of ['gradio', 'static', 'docker', 'streamlit']"
155
+ }
156
+ ~~~
157
+
158
+ ##### Example 5: Get Documentation
159
+ **Request (`GET /docs`):**
160
+ GET https://broadfield-dev-assembler.hf.space/docs
161
+
162
+ **Response (200 OK):**
163
+ <The full Markdown text of this documentation>
164
+ ```
165
+
166
+ Usage Example (Python)
167
+ Here’s how to call the API using Python’s requests library:
168
+ python
169
+ import requests
170
+
171
+ # Create a new Space
172
+ url = "https://broadfield-dev-assembler.hf.space/create-space"
173
+ payload = {
174
+ "space_type": "static",
175
+ "files": {
176
+ "index.html": "<html><body><h1>Test Page</h1></body></html>"
177
+ },
178
+ "parameters": {
179
+ "key": "value"
180
+ }
181
+ }
182
+ headers = {"Content-Type": "application/json"}
183
+
184
+ response = requests.post(url, json=payload)
185
+ if response.status_code == 200:
186
+ print("Success:", response.json())
187
+ else:
188
+ print("Error:", response.status_code, response.json())
189
+
190
+ # Fetch documentation
191
+ docs_url = "https://broadfield-dev-assembler.hf.space/docs"
192
+ docs_response = requests.get(docs_url)
193
+ if docs_response.status_code == 200:
194
+ print("Documentation:", docs_response.text)
195
+ Additional Details
196
+ Supported Space Types
197
+ gradio: For interactive Python apps using the Gradio framework. Requires an app.py with Gradio code.
198
+ static: For static websites. Requires at least an index.html file; supports additional files like style.css.
199
+ docker: For custom apps (e.g., Flask, FastAPI). Requires a Dockerfile or uses a default one if omitted.
200
+ streamlit: For Streamlit apps. Requires an app.py with Streamlit code.
201
+ File Handling
202
+ Python Files (.py): The parameters object is injected as a global PARAMS variable at the top of the file.
203
+ Other Files: Contents are uploaded as-is; no automatic parameter injection (e.g., HTML files need custom logic to use parameters).
204
+ Requirements: If requirements.txt isn’t provided, a default is generated based on space_type (e.g., gradio for Gradio, flask for Docker).
205
+ Deployment Notes
206
+ Build Time: New Spaces take 1-5 minutes to build and deploy on Hugging Face. The API returns immediately with a URL, but the Space won’t be live until the build completes.
207
+ Port for Docker: Hugging Face expects Docker Spaces to listen on port 7860. Ensure your Dockerfile and app code align with this (see Example 2).
208
+ Security Considerations
209
+ The Assembler doesn’t execute the provided code; it only creates a new Space. However, ensure the generated Space’s code is safe if deploying publicly.
210
+ Avoid sending sensitive data in parameters unless the new Space is private (not implemented here but can be adjusted).
211
+ Limitations
212
+ Rate Limits: Hugging Face may restrict frequent Space creation. Check their API documentation for quotas.
213
+ File Size: Large files may fail to upload; keep contents reasonable (e.g., <1MB per file).
214
+ Error Handling: Basic validation is included, but complex syntax checking isn’t performed.
215
+ """