AdriBat1 commited on
Commit
8ba3f09
Β·
1 Parent(s): 5f654f8

Add output streaming endpoint

Browse files
Files changed (1) hide show
  1. remote-gpu-server/app.py +88 -1
remote-gpu-server/app.py CHANGED
@@ -72,7 +72,7 @@ def execute_code(python_code: str) -> dict:
72
  output_parts.append(f"{status}")
73
 
74
  # Cerca file generati (immagini, csv, json)
75
- for ext in ['*.png', '*.jpg', '*.svg', '*.csv', '*.json', '*.txt']:
76
  if ext == '*.txt': continue # Salta txt per evitare di rileggere log
77
  for filepath in glob.glob(os.path.join(work_dir, ext)):
78
  filename = os.path.basename(filepath)
@@ -154,6 +154,93 @@ demo = gr.Interface(
154
  # Monta Gradio su FastAPI
155
  app = gr.mount_gradio_app(app, demo, path="/gradio")
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  if __name__ == "__main__":
158
  import uvicorn
159
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
72
  output_parts.append(f"{status}")
73
 
74
  # Cerca file generati (immagini, csv, json)
75
+ for ext in ['*.png', '*.jpg', '*.svg', '*.csv', '*.json', '*.txt', '*.pth', '*.pt']:
76
  if ext == '*.txt': continue # Salta txt per evitare di rileggere log
77
  for filepath in glob.glob(os.path.join(work_dir, ext)):
78
  filename = os.path.basename(filepath)
 
154
  # Monta Gradio su FastAPI
155
  app = gr.mount_gradio_app(app, demo, path="/gradio")
156
 
157
+ from fastapi.responses import StreamingResponse
158
+
159
+ # ... existing code ...
160
+
161
+ def stream_code_execution(python_code: str):
162
+ """
163
+ Generatore che esegue codice e yielda output riga per riga.
164
+ Alla fine yielda un JSON speciale con i file.
165
+ """
166
+ if not python_code or not python_code.strip():
167
+ yield "❌ Errore: Nessun codice ricevuto.\n"
168
+ return
169
+
170
+ work_dir = tempfile.mkdtemp()
171
+ script_path = os.path.join(work_dir, "script.py")
172
+
173
+ with open(script_path, 'w', encoding='utf-8') as f:
174
+ f.write(python_code)
175
+
176
+ yield "πŸš€ Avvio esecuzione (STREAMING)...\n"
177
+ yield f"πŸ“‚ Directory: {work_dir}\n"
178
+ yield "=" * 50 + "\n"
179
+
180
+ try:
181
+ # Popen per leggere output in tempo reale
182
+ process = subprocess.Popen(
183
+ [sys.executable, script_path],
184
+ stdout=subprocess.PIPE,
185
+ stderr=subprocess.STDOUT, # Combina stderr in stdout
186
+ text=True,
187
+ cwd=work_dir,
188
+ env={**os.environ, "PYTHONUNBUFFERED": "1"},
189
+ bufsize=1 # Line buffered
190
+ )
191
+
192
+ # Leggi riga per riga
193
+ for line in process.stdout:
194
+ yield line
195
+
196
+ process.wait()
197
+
198
+ yield "=" * 50 + "\n"
199
+ status = "βœ… Successo" if process.returncode == 0 else f"❌ Errore ({process.returncode})"
200
+ yield f"{status}\n"
201
+
202
+ # RACCOLTA FILE FINALI
203
+ generated_files = []
204
+ # Cerca file generati (immagini, csv, json)
205
+ for ext in ['*.png', '*.jpg', '*.svg', '*.csv', '*.json', '*.txt', '*.pth', '*.pt']:
206
+ if ext == '*.txt': continue
207
+ for filepath in glob.glob(os.path.join(work_dir, ext)):
208
+ filename = os.path.basename(filepath)
209
+ try:
210
+ with open(filepath, "rb") as f:
211
+ if os.path.getsize(filepath) > 10 * 1024 * 1024:
212
+ yield f"⚠️ File '{filename}' troppo grande (>10MB), saltato.\n"
213
+ continue
214
+ encoded = base64.b64encode(f.read()).decode('utf-8')
215
+ generated_files.append({
216
+ "name": filename,
217
+ "data": encoded,
218
+ "mime": "application/octet-stream"
219
+ })
220
+ yield f"πŸ“¦ File generato: {filename}\n"
221
+ except Exception as e:
222
+ yield f"❌ Errore lettura {filename}: {e}\n"
223
+
224
+ # Special marker for files payload
225
+ if generated_files:
226
+ payload = json.dumps({"files": generated_files})
227
+ yield f"__ANTIGRAVITY_FILES_JSON__:{payload}\n"
228
+
229
+ except Exception as e:
230
+ import traceback
231
+ yield f"❌ Eccezione: {str(e)}\n{traceback.format_exc()}\n"
232
+
233
+ finally:
234
+ shutil.rmtree(work_dir, ignore_errors=True)
235
+
236
+
237
+ @app.post("/execute_stream")
238
+ async def execute_stream(data: dict):
239
+ """Endpoint POST per eseguire codice Python con output streaming"""
240
+ code = data.get("code", "")
241
+ return StreamingResponse(stream_code_execution(code), media_type="text/plain")
242
+
243
+
244
  if __name__ == "__main__":
245
  import uvicorn
246
  uvicorn.run(app, host="0.0.0.0", port=7860)