-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgui_app.py
More file actions
370 lines (297 loc) · 10.3 KB
/
gui_app.py
File metadata and controls
370 lines (297 loc) · 10.3 KB
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import os
import sys
import shutil
import asyncio
import threading
import multiprocessing
import webbrowser
import time
from fastapi import FastAPI, File, UploadFile, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from dotenv import load_dotenv
import uvicorn
# ------------------------------------------------------------
# WINDOWS ENCODING FIX
# ------------------------------------------------------------
if sys.platform == "win32":
os.environ["PYTHONIOENCODING"] = "utf-8"
if sys.stdout:
try:
sys.stdout.reconfigure(encoding="utf-8")
except:
pass
if sys.stderr:
try:
sys.stderr.reconfigure(encoding="utf-8")
except:
pass
def safe_print(msg):
try:
print(msg)
except:
pass
# ------------------------------------------------------------
# FASTAPI SETUP
# ------------------------------------------------------------
def get_base_dir():
"""Restituisce la cartella dell'eseguibile o dello script, gestendo i bundle .app di macOS."""
if getattr(sys, 'frozen', False):
path = os.path.dirname(sys.executable)
if ".app/Contents/MacOS" in path:
return os.path.abspath(os.path.join(path, "../../../"))
return path
return os.path.dirname(os.path.abspath(__file__))
BASE_DIR = get_base_dir()
OUTPUT_ROOT = os.path.join(BASE_DIR, "output")
TEMP_UPLOADS = os.path.join(BASE_DIR, "temp_uploads")
ENV_PATH = os.path.join(BASE_DIR, ".env")
load_dotenv(ENV_PATH, override=True)
app = FastAPI()
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = BASE_DIR
return os.path.join(base_path, relative_path)
web_folder = resource_path("web")
os.makedirs(OUTPUT_ROOT, exist_ok=True)
# 🔧 STARTUP CLEANUP: Reset the temp folder every time the app opens
if os.path.exists(TEMP_UPLOADS):
try:
shutil.rmtree(TEMP_UPLOADS)
except Exception as e:
safe_print(f"Warning: Could not clear temp folder at startup: {e}")
os.makedirs(TEMP_UPLOADS, exist_ok=True)
app.mount("/static", StaticFiles(directory=web_folder), name="static")
# ------------------------------------------------------------
# ROUTES
# ------------------------------------------------------------
# Root (index.html): main menu
@app.get("/")
async def index():
return FileResponse(os.path.join(web_folder, "index.html"))
# Outputs (folder where appunti.pdf is saved)
@app.get("/outputs")
async def list_outputs():
files = []
for root, _, filenames in os.walk(OUTPUT_ROOT):
for f in filenames:
if f.endswith(".pdf"):
full = os.path.join(root, f)
rel = os.path.relpath(full, OUTPUT_ROOT).replace("\\", "/")
files.append({
"filename": f,
"path": rel,
"folder": os.path.basename(root)
})
return JSONResponse(content=files)
# View PDF (open in browser)
@app.get("/view/{folder}/{filename}")
async def view_pdf(folder: str, filename: str):
path = os.path.join(OUTPUT_ROOT, folder, filename)
if os.path.exists(path):
return FileResponse(path, media_type="application/pdf", content_disposition_type="inline")
return JSONResponse(status_code=404, content={"message": "Not found"})
# Download PDF (download from browser)
@app.get("/download/{folder}/{filename}")
async def download_pdf(folder: str, filename: str):
path = os.path.join("output", folder, filename)
if os.path.exists(path):
return FileResponse(path, filename=filename)
return JSONResponse(status_code=404, content={"message": "Not found"})
# ------------------------------------------------------------
# SETTINGS API
# ------------------------------------------------------------
class ApiKeyRequest(BaseModel):
api_key: str
# Check API key status
@app.get("/api/key-status")
async def key_status():
load_dotenv(override=True)
return {"is_set": bool(os.getenv("GEMINI_API_KEY"))}
# Save API key
@app.post("/api/key")
async def save_key(req: ApiKeyRequest):
key = req.api_key.strip()
env_path = ENV_PATH
lines = []
if os.path.exists(env_path):
with open(env_path, "r", encoding="utf-8") as f:
lines = f.readlines()
found = False
new_lines = []
for l in lines:
if l.startswith("GEMINI_API_KEY="):
new_lines.append(f"GEMINI_API_KEY={key}\n")
found = True
else:
new_lines.append(l)
if not found:
new_lines.append(f"GEMINI_API_KEY={key}\n")
with open(env_path, "w", encoding="utf-8") as f:
f.writelines(new_lines)
os.environ["GEMINI_API_KEY"] = key
return {"message": "API key saved"}
class ThreadConfig(BaseModel):
threads: int
# Get app info
@app.get("/api/info")
async def app_info():
return {
"cpu_count": multiprocessing.cpu_count(),
"saved_threads": int(os.getenv("THREADS", "4"))
}
# Save threads
@app.post("/api/save-threads")
async def save_threads(cfg: ThreadConfig):
env_path = ".env"
lines = []
if os.path.exists(env_path):
with open(env_path, "r", encoding="utf-8") as f:
lines = f.readlines()
found = False
out = []
for l in lines:
if l.startswith("THREADS="):
out.append(f"THREADS={cfg.threads}\n")
found = True
else:
out.append(l)
if not found:
out.append(f"THREADS={cfg.threads}\n")
with open(env_path, "w", encoding="utf-8") as f:
f.writelines(out)
os.environ["THREADS"] = str(cfg.threads)
return {"message": "Threads saved"}
# ------------------------------------------------------------
# FILE UPLOAD
# ------------------------------------------------------------
# Upload file
@app.post("/upload")
async def upload(file: UploadFile = File(...)):
path = os.path.join(TEMP_UPLOADS, file.filename)
with open(path, "wb") as f:
shutil.copyfileobj(file.file, f)
return {"filename": file.filename}
# ------------------------------------------------------------
# WEBSOCKET PROCESS
# ------------------------------------------------------------
# Process audio
@app.websocket("/ws/process")
async def process_ws(ws: WebSocket):
await ws.accept()
files_to_delete = []
try:
data = await ws.receive_json()
audio = data.get("audio_filename")
video = data.get("video_filename")
slides = data.get("slides_filename")
pages = data.get("pages")
threads = data.get("threads")
if not audio and not video:
await ws.send_text("❌ No audio or video file provided")
return
if not os.getenv("GEMINI_API_KEY"):
await ws.send_text("❌ API key missing")
return
# Determine the source file (audio or video)
if video:
audio_path = os.path.join(TEMP_UPLOADS, video)
else:
audio_path = os.path.join(TEMP_UPLOADS, audio)
if audio_path:
files_to_delete.append(audio_path)
args = [audio_path]
if slides:
slides_path = os.path.join(TEMP_UPLOADS, slides)
args += ["--slides", slides_path]
files_to_delete.append(slides_path)
if pages:
args += ["--pages", pages]
if threads:
args += ["--threads", str(threads)]
await ws.send_text(f"🚀 Processing (threads={threads})")
loop = asyncio.get_running_loop()
await asyncio.to_thread(run_audiotto, args, loop, ws)
await ws.send_text("✅ Done")
await ws.send_text("REFRESH_OUTPUTS")
except WebSocketDisconnect:
pass
except Exception as e:
await ws.send_text(f"❌ Error: {e}")
finally:
# 🧹 SESSION CLEANUP: Remove files immediately after processing
for fpath in files_to_delete:
if fpath and os.path.exists(fpath):
try:
os.remove(fpath)
safe_print(f"Cleanup: Removed {os.path.basename(fpath)}")
except Exception as e:
safe_print(f"Cleanup failed for {fpath}: {e}")
try:
await ws.close()
except:
pass
def run_audiotto(args, loop, ws):
# 🔥 LAZY IMPORT (CRITICO)
import AudioTTo
def logger(msg):
async def send():
try:
await ws.send_text(msg)
except:
pass
asyncio.run_coroutine_threadsafe(send(), loop)
AudioTTo.set_logger(logger)
try:
AudioTTo.main(args)
except Exception as e:
logger(f"❌ {e}")
finally:
AudioTTo.set_logger(None)
# ------------------------------------------------------------
# SERVER START
# ------------------------------------------------------------
# Start server
def start_server():
uvicorn.run(
app,
host="127.0.0.1",
port=8000,
log_level="info",
loop="asyncio"
)
# ------------------------------------------------------------
# MAIN
# ------------------------------------------------------------
# ------------------------------------------------------------
# MAIN
# ------------------------------------------------------------
if __name__ == "__main__":
multiprocessing.freeze_support()
# 🔧 FIX PYTHONNET (WINDOWS + PYINSTALLER)
# Keeping this for potential future needs, though pywebview is gone
if sys.platform == "win32" and getattr(sys, "frozen", False):
base = sys._MEIPASS
for f in os.listdir(base):
if f.lower().startswith("python") and f.lower().endswith(".dll"):
os.environ["PYTHONNET_PYDLL"] = os.path.join(base, f)
break
# Open browser automatically after a short delay
def open_browser():
time.sleep(1.5)
webbrowser.open("http://127.0.0.1:8000")
threading.Thread(target=open_browser, daemon=True).start()
try:
start_server()
except KeyboardInterrupt:
pass
finally:
# 🧹 SHUTDOWN CLEANUP: Ensure absolute path is cleared
if os.path.exists(TEMP_UPLOADS):
try:
shutil.rmtree(TEMP_UPLOADS)
except:
pass