archives.py 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841
  1. import io
  2. import logging
  3. import zipfile
  4. from pathlib import Path
  5. from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
  6. from fastapi.responses import FileResponse, Response
  7. from sqlalchemy import func, select
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from backend.app.core.config import settings
  10. from backend.app.core.database import get_db
  11. from backend.app.models.archive import PrintArchive
  12. from backend.app.models.filament import Filament
  13. from backend.app.schemas.archive import ArchiveResponse, ArchiveStats, ArchiveUpdate, ReprintRequest
  14. from backend.app.services.archive import ArchiveService
  15. logger = logging.getLogger(__name__)
  16. router = APIRouter(prefix="/archives", tags=["archives"])
  17. def compute_time_accuracy(archive: PrintArchive) -> dict:
  18. """Compute actual print time and accuracy for an archive.
  19. Returns dict with actual_time_seconds and time_accuracy.
  20. time_accuracy = (estimated / actual) * 100
  21. - 100% = perfect estimate
  22. - >100% = print was faster than estimated
  23. - <100% = print took longer than estimated
  24. """
  25. result = {"actual_time_seconds": None, "time_accuracy": None}
  26. if archive.started_at and archive.completed_at and archive.status == "completed":
  27. actual_seconds = int((archive.completed_at - archive.started_at).total_seconds())
  28. if actual_seconds > 0:
  29. result["actual_time_seconds"] = actual_seconds
  30. if archive.print_time_seconds and archive.print_time_seconds > 0:
  31. # Calculate accuracy as percentage
  32. accuracy = (archive.print_time_seconds / actual_seconds) * 100
  33. # Sanity check: skip unreasonable values (e.g., manually changed status)
  34. # Valid range: 5% to 500% (print took 20x longer to 5x faster than estimated)
  35. if 5 <= accuracy <= 500:
  36. result["time_accuracy"] = round(accuracy, 1)
  37. return result
  38. def archive_to_response(
  39. archive: PrintArchive,
  40. duplicates: list[dict] | None = None,
  41. duplicate_count: int = 0,
  42. ) -> dict:
  43. """Convert archive model to response dict with computed fields."""
  44. data = {
  45. "id": archive.id,
  46. "printer_id": archive.printer_id,
  47. "project_id": archive.project_id,
  48. "project_name": archive.project.name if archive.project else None,
  49. "filename": archive.filename,
  50. "file_path": archive.file_path,
  51. "file_size": archive.file_size,
  52. "content_hash": archive.content_hash,
  53. "thumbnail_path": archive.thumbnail_path,
  54. "timelapse_path": archive.timelapse_path,
  55. "source_3mf_path": archive.source_3mf_path,
  56. "f3d_path": archive.f3d_path,
  57. "duplicates": duplicates,
  58. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  59. "print_name": archive.print_name,
  60. "print_time_seconds": archive.print_time_seconds,
  61. "filament_used_grams": archive.filament_used_grams,
  62. "filament_type": archive.filament_type,
  63. "filament_color": archive.filament_color,
  64. "layer_height": archive.layer_height,
  65. "total_layers": archive.total_layers,
  66. "nozzle_diameter": archive.nozzle_diameter,
  67. "bed_temperature": archive.bed_temperature,
  68. "nozzle_temperature": archive.nozzle_temperature,
  69. "status": archive.status,
  70. "started_at": archive.started_at,
  71. "completed_at": archive.completed_at,
  72. "extra_data": archive.extra_data,
  73. "makerworld_url": archive.makerworld_url,
  74. "designer": archive.designer,
  75. "is_favorite": archive.is_favorite,
  76. "tags": archive.tags,
  77. "notes": archive.notes,
  78. "cost": archive.cost,
  79. "photos": archive.photos,
  80. "failure_reason": archive.failure_reason,
  81. "quantity": archive.quantity,
  82. "energy_kwh": archive.energy_kwh,
  83. "energy_cost": archive.energy_cost,
  84. "created_at": archive.created_at,
  85. }
  86. # Add computed time accuracy fields
  87. accuracy_data = compute_time_accuracy(archive)
  88. data.update(accuracy_data)
  89. return data
  90. @router.get("/", response_model=list[ArchiveResponse])
  91. async def list_archives(
  92. printer_id: int | None = None,
  93. project_id: int | None = None,
  94. limit: int = 50,
  95. offset: int = 0,
  96. db: AsyncSession = Depends(get_db),
  97. ):
  98. """List archived prints."""
  99. service = ArchiveService(db)
  100. archives = await service.list_archives(
  101. printer_id=printer_id,
  102. project_id=project_id,
  103. limit=limit,
  104. offset=offset,
  105. )
  106. # Get set of hashes that have duplicates (efficient single query)
  107. duplicate_hashes = await service.get_duplicate_hashes()
  108. # Mark archives that have duplicates
  109. result = []
  110. for a in archives:
  111. has_duplicate = a.content_hash in duplicate_hashes if a.content_hash else False
  112. result.append(archive_to_response(a, duplicate_count=1 if has_duplicate else 0))
  113. return result
  114. @router.get("/search", response_model=list[ArchiveResponse])
  115. async def search_archives(
  116. q: str = Query(..., min_length=2, description="Search query"),
  117. printer_id: int | None = None,
  118. project_id: int | None = None,
  119. status: str | None = None,
  120. limit: int = 50,
  121. offset: int = 0,
  122. db: AsyncSession = Depends(get_db),
  123. ):
  124. """Full-text search across archives.
  125. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  126. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  127. """
  128. from sqlalchemy import text
  129. from sqlalchemy.orm import selectinload
  130. # Prepare search query - add wildcard for partial matches
  131. search_term = q.strip()
  132. if not search_term.endswith("*"):
  133. search_term = f"{search_term}*"
  134. # Build the FTS query
  135. # Using MATCH for FTS5 full-text search
  136. fts_query = text("""
  137. SELECT rowid FROM archive_fts
  138. WHERE archive_fts MATCH :search_term
  139. ORDER BY rank
  140. LIMIT :limit OFFSET :offset
  141. """)
  142. try:
  143. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  144. matched_ids = [row[0] for row in result.fetchall()]
  145. except Exception as e:
  146. logger.warning(f"FTS search failed, falling back to LIKE search: {e}")
  147. # Fallback to LIKE search if FTS fails
  148. like_pattern = f"%{q}%"
  149. query = (
  150. select(PrintArchive)
  151. .options(selectinload(PrintArchive.project))
  152. .where(
  153. (PrintArchive.print_name.ilike(like_pattern))
  154. | (PrintArchive.filename.ilike(like_pattern))
  155. | (PrintArchive.tags.ilike(like_pattern))
  156. | (PrintArchive.notes.ilike(like_pattern))
  157. | (PrintArchive.designer.ilike(like_pattern))
  158. | (PrintArchive.filament_type.ilike(like_pattern))
  159. )
  160. .order_by(PrintArchive.created_at.desc())
  161. )
  162. if printer_id:
  163. query = query.where(PrintArchive.printer_id == printer_id)
  164. if project_id:
  165. query = query.where(PrintArchive.project_id == project_id)
  166. if status:
  167. query = query.where(PrintArchive.status == status)
  168. query = query.limit(limit).offset(offset)
  169. result = await db.execute(query)
  170. archives = result.scalars().all()
  171. return [archive_to_response(a) for a in archives]
  172. if not matched_ids:
  173. return []
  174. # Fetch full archive records for matched IDs
  175. query = select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id.in_(matched_ids))
  176. # Apply additional filters
  177. if printer_id:
  178. query = query.where(PrintArchive.printer_id == printer_id)
  179. if project_id:
  180. query = query.where(PrintArchive.project_id == project_id)
  181. if status:
  182. query = query.where(PrintArchive.status == status)
  183. result = await db.execute(query)
  184. archives_dict = {a.id: a for a in result.scalars().all()}
  185. # Preserve FTS ranking order and apply pagination
  186. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  187. paginated = ordered_archives[offset : offset + limit]
  188. return [archive_to_response(a) for a in paginated]
  189. @router.post("/search/rebuild-index")
  190. async def rebuild_search_index(db: AsyncSession = Depends(get_db)):
  191. """Rebuild the full-text search index from existing archives.
  192. Use this if search results seem incomplete or incorrect.
  193. """
  194. from sqlalchemy import text
  195. try:
  196. # Clear and rebuild the FTS index
  197. await db.execute(text("DELETE FROM archive_fts"))
  198. # Repopulate from print_archives
  199. await db.execute(
  200. text("""
  201. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  202. SELECT id, print_name, filename, tags, notes, designer, filament_type
  203. FROM print_archives
  204. """)
  205. )
  206. await db.commit()
  207. # Count entries
  208. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  209. count = result.scalar() or 0
  210. return {"message": f"Search index rebuilt with {count} entries"}
  211. except Exception as e:
  212. logger.error(f"Failed to rebuild search index: {e}")
  213. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  214. @router.get("/analysis/failures")
  215. async def analyze_failures(
  216. days: int = 30,
  217. printer_id: int | None = None,
  218. project_id: int | None = None,
  219. db: AsyncSession = Depends(get_db),
  220. ):
  221. """Analyze failure patterns across prints.
  222. Returns failure statistics including:
  223. - Overall failure rate
  224. - Failures by reason, filament type, printer
  225. - Time of day distribution
  226. - Recent failures
  227. - Weekly trend
  228. """
  229. from backend.app.services.failure_analysis import FailureAnalysisService
  230. service = FailureAnalysisService(db)
  231. return await service.analyze_failures(
  232. days=days,
  233. printer_id=printer_id,
  234. project_id=project_id,
  235. )
  236. @router.get("/compare")
  237. async def compare_archives(
  238. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  239. db: AsyncSession = Depends(get_db),
  240. ):
  241. """Compare multiple archives side by side.
  242. Compares print settings, filament usage, and print times.
  243. Also analyzes correlation between settings and success/failure.
  244. Args:
  245. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  246. """
  247. from backend.app.services.archive_comparison import ArchiveComparisonService
  248. # Parse and validate archive IDs
  249. try:
  250. ids = [int(id.strip()) for id in archive_ids.split(",")]
  251. except ValueError:
  252. raise HTTPException(400, "Invalid archive IDs format")
  253. if len(ids) < 2:
  254. raise HTTPException(400, "At least 2 archives required for comparison")
  255. if len(ids) > 5:
  256. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  257. service = ArchiveComparisonService(db)
  258. try:
  259. return await service.compare_archives(ids)
  260. except ValueError as e:
  261. raise HTTPException(400, str(e))
  262. @router.get("/export")
  263. async def export_archives(
  264. format: str = Query("csv", description="Export format: csv or xlsx"),
  265. fields: str | None = Query(None, description="Comma-separated field names"),
  266. printer_id: int | None = None,
  267. project_id: int | None = None,
  268. status: str | None = None,
  269. date_from: str | None = Query(None, description="Start date (ISO format)"),
  270. date_to: str | None = Query(None, description="End date (ISO format)"),
  271. search: str | None = None,
  272. db: AsyncSession = Depends(get_db),
  273. ):
  274. """Export archives to CSV or Excel format.
  275. Returns a downloadable file with archive data.
  276. """
  277. from datetime import datetime
  278. from fastapi.responses import StreamingResponse
  279. from backend.app.services.export import ExportService
  280. if format not in ("csv", "xlsx"):
  281. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  282. # Parse fields
  283. field_list = None
  284. if fields:
  285. field_list = [f.strip() for f in fields.split(",")]
  286. # Parse dates
  287. date_from_dt = None
  288. date_to_dt = None
  289. if date_from:
  290. try:
  291. date_from_dt = datetime.fromisoformat(date_from)
  292. except ValueError:
  293. raise HTTPException(400, "Invalid date_from format")
  294. if date_to:
  295. try:
  296. date_to_dt = datetime.fromisoformat(date_to)
  297. except ValueError:
  298. raise HTTPException(400, "Invalid date_to format")
  299. service = ExportService(db)
  300. try:
  301. file_bytes, filename, content_type = await service.export_archives(
  302. format=format,
  303. fields=field_list,
  304. printer_id=printer_id,
  305. project_id=project_id,
  306. status=status,
  307. date_from=date_from_dt,
  308. date_to=date_to_dt,
  309. search=search,
  310. )
  311. except ImportError as e:
  312. raise HTTPException(500, str(e))
  313. return StreamingResponse(
  314. io.BytesIO(file_bytes),
  315. media_type=content_type,
  316. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  317. )
  318. @router.get("/stats/export")
  319. async def export_stats(
  320. format: str = Query("csv", description="Export format: csv or xlsx"),
  321. days: int = 30,
  322. printer_id: int | None = None,
  323. project_id: int | None = None,
  324. db: AsyncSession = Depends(get_db),
  325. ):
  326. """Export statistics summary to CSV or Excel format."""
  327. from fastapi.responses import StreamingResponse
  328. from backend.app.services.export import ExportService
  329. if format not in ("csv", "xlsx"):
  330. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  331. service = ExportService(db)
  332. try:
  333. file_bytes, filename, content_type = await service.export_stats(
  334. format=format,
  335. days=days,
  336. printer_id=printer_id,
  337. project_id=project_id,
  338. )
  339. except ImportError as e:
  340. raise HTTPException(500, str(e))
  341. return StreamingResponse(
  342. io.BytesIO(file_bytes),
  343. media_type=content_type,
  344. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  345. )
  346. @router.get("/stats", response_model=ArchiveStats)
  347. async def get_archive_stats(db: AsyncSession = Depends(get_db)):
  348. """Get statistics across all archives."""
  349. # Total counts
  350. total_result = await db.execute(select(func.count(PrintArchive.id)))
  351. total_prints = total_result.scalar() or 0
  352. successful_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed"))
  353. successful_prints = successful_result.scalar() or 0
  354. failed_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "failed"))
  355. failed_prints = failed_result.scalar() or 0
  356. # Totals
  357. time_result = await db.execute(select(func.sum(PrintArchive.print_time_seconds)))
  358. total_time = (time_result.scalar() or 0) / 3600 # Convert to hours
  359. filament_result = await db.execute(select(func.sum(PrintArchive.filament_used_grams)))
  360. total_filament = filament_result.scalar() or 0
  361. cost_result = await db.execute(select(func.sum(PrintArchive.cost)))
  362. total_cost = cost_result.scalar() or 0
  363. # By filament type (split comma-separated values for multi-material prints)
  364. filament_type_result = await db.execute(
  365. select(PrintArchive.filament_type).where(PrintArchive.filament_type.isnot(None))
  366. )
  367. prints_by_filament: dict[str, int] = {}
  368. for (filament_types,) in filament_type_result.all():
  369. # Split by comma and count each type
  370. for ftype in filament_types.split(","):
  371. ftype = ftype.strip()
  372. if ftype:
  373. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  374. # By printer
  375. printer_result = await db.execute(
  376. select(PrintArchive.printer_id, func.count(PrintArchive.id)).group_by(PrintArchive.printer_id)
  377. )
  378. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  379. # Time accuracy statistics
  380. # Get all completed archives with both estimated and actual times
  381. accuracy_result = await db.execute(
  382. select(PrintArchive)
  383. .where(PrintArchive.status == "completed")
  384. .where(PrintArchive.print_time_seconds.isnot(None))
  385. .where(PrintArchive.started_at.isnot(None))
  386. .where(PrintArchive.completed_at.isnot(None))
  387. )
  388. archives_with_times = list(accuracy_result.scalars().all())
  389. average_accuracy = None
  390. accuracy_by_printer: dict[str, float] = {}
  391. if archives_with_times:
  392. accuracies = []
  393. printer_accuracies: dict[str, list[float]] = {}
  394. for archive in archives_with_times:
  395. acc_data = compute_time_accuracy(archive)
  396. if acc_data["time_accuracy"] is not None:
  397. accuracies.append(acc_data["time_accuracy"])
  398. # Group by printer
  399. printer_key = str(archive.printer_id) if archive.printer_id else "unknown"
  400. if printer_key not in printer_accuracies:
  401. printer_accuracies[printer_key] = []
  402. printer_accuracies[printer_key].append(acc_data["time_accuracy"])
  403. if accuracies:
  404. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  405. # Calculate per-printer averages
  406. for printer_key, accs in printer_accuracies.items():
  407. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  408. # Energy totals - check which mode to use
  409. from backend.app.api.routes.settings import get_setting
  410. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  411. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  412. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  413. if energy_tracking_mode == "total":
  414. # Total mode: sum up 'total' counter from all smart plugs (lifetime consumption)
  415. from backend.app.models.smart_plug import SmartPlug
  416. from backend.app.services.tasmota import tasmota_service
  417. plugs_result = await db.execute(select(SmartPlug))
  418. plugs = list(plugs_result.scalars().all())
  419. total_energy_kwh = 0.0
  420. for plug in plugs:
  421. energy = await tasmota_service.get_energy(plug)
  422. if energy and energy.get("total") is not None:
  423. total_energy_kwh += energy["total"]
  424. total_energy_kwh = round(total_energy_kwh, 3)
  425. total_energy_cost = round(total_energy_kwh * energy_cost_per_kwh, 2)
  426. else:
  427. # Print mode: sum up per-print energy from archives
  428. energy_kwh_result = await db.execute(select(func.sum(PrintArchive.energy_kwh)))
  429. total_energy_kwh = energy_kwh_result.scalar() or 0
  430. energy_cost_result = await db.execute(select(func.sum(PrintArchive.energy_cost)))
  431. total_energy_cost = energy_cost_result.scalar() or 0
  432. return ArchiveStats(
  433. total_prints=total_prints,
  434. successful_prints=successful_prints,
  435. failed_prints=failed_prints,
  436. total_print_time_hours=round(total_time, 1),
  437. total_filament_grams=round(total_filament, 1),
  438. total_cost=round(total_cost, 2),
  439. prints_by_filament_type=prints_by_filament,
  440. prints_by_printer=prints_by_printer,
  441. average_time_accuracy=average_accuracy,
  442. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  443. total_energy_kwh=round(total_energy_kwh, 3),
  444. total_energy_cost=round(total_energy_cost, 2),
  445. )
  446. @router.get("/{archive_id}", response_model=ArchiveResponse)
  447. async def get_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  448. """Get a specific archive."""
  449. service = ArchiveService(db)
  450. archive = await service.get_archive(archive_id)
  451. if not archive:
  452. raise HTTPException(404, "Archive not found")
  453. # Find duplicates
  454. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  455. duplicates = await service.find_duplicates(
  456. archive_id=archive.id,
  457. content_hash=archive.content_hash,
  458. print_name=archive.print_name,
  459. makerworld_model_id=makerworld_id,
  460. )
  461. return archive_to_response(archive, duplicates)
  462. @router.get("/{archive_id}/similar")
  463. async def find_similar_archives(
  464. archive_id: int,
  465. limit: int = 10,
  466. db: AsyncSession = Depends(get_db),
  467. ):
  468. """Find archives with similar settings for comparison.
  469. Returns archives that match by:
  470. - Same print name (highest priority)
  471. - Same file content hash
  472. - Same filament type
  473. """
  474. from backend.app.services.archive_comparison import ArchiveComparisonService
  475. service = ArchiveComparisonService(db)
  476. try:
  477. return await service.find_similar_archives(archive_id, limit=limit)
  478. except ValueError as e:
  479. raise HTTPException(404, str(e))
  480. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  481. async def update_archive(
  482. archive_id: int,
  483. update_data: ArchiveUpdate,
  484. db: AsyncSession = Depends(get_db),
  485. ):
  486. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  487. from sqlalchemy.orm import selectinload
  488. result = await db.execute(
  489. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  490. )
  491. archive = result.scalar_one_or_none()
  492. if not archive:
  493. raise HTTPException(404, "Archive not found")
  494. for field, value in update_data.model_dump(exclude_unset=True).items():
  495. setattr(archive, field, value)
  496. await db.commit()
  497. # Re-fetch with project relationship loaded after commit
  498. result = await db.execute(
  499. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  500. )
  501. archive = result.scalar_one_or_none()
  502. return archive_to_response(archive)
  503. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  504. async def toggle_favorite(
  505. archive_id: int,
  506. db: AsyncSession = Depends(get_db),
  507. ):
  508. """Toggle favorite status for an archive."""
  509. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  510. archive = result.scalar_one_or_none()
  511. if not archive:
  512. raise HTTPException(404, "Archive not found")
  513. archive.is_favorite = not archive.is_favorite
  514. await db.commit()
  515. await db.refresh(archive)
  516. return archive
  517. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  518. async def rescan_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  519. """Rescan the 3MF file and update metadata."""
  520. from backend.app.services.archive import ThreeMFParser
  521. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  522. archive = result.scalar_one_or_none()
  523. if not archive:
  524. raise HTTPException(404, "Archive not found")
  525. file_path = settings.base_dir / archive.file_path
  526. if not file_path.exists():
  527. raise HTTPException(404, "Archive file not found")
  528. # Parse the 3MF file
  529. parser = ThreeMFParser(file_path)
  530. metadata = parser.parse()
  531. # Update fields from metadata
  532. if metadata.get("filament_type"):
  533. archive.filament_type = metadata["filament_type"]
  534. if metadata.get("filament_color"):
  535. archive.filament_color = metadata["filament_color"]
  536. if metadata.get("print_time_seconds"):
  537. archive.print_time_seconds = metadata["print_time_seconds"]
  538. if metadata.get("filament_used_grams"):
  539. archive.filament_used_grams = metadata["filament_used_grams"]
  540. if metadata.get("layer_height"):
  541. archive.layer_height = metadata["layer_height"]
  542. if metadata.get("nozzle_diameter"):
  543. archive.nozzle_diameter = metadata["nozzle_diameter"]
  544. if metadata.get("bed_temperature"):
  545. archive.bed_temperature = metadata["bed_temperature"]
  546. if metadata.get("nozzle_temperature"):
  547. archive.nozzle_temperature = metadata["nozzle_temperature"]
  548. if metadata.get("makerworld_url"):
  549. archive.makerworld_url = metadata["makerworld_url"]
  550. if metadata.get("designer"):
  551. archive.designer = metadata["designer"]
  552. # Calculate cost based on filament usage and type
  553. if archive.filament_used_grams and archive.filament_type:
  554. primary_type = archive.filament_type.split(",")[0].strip()
  555. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  556. filament = filament_result.scalar_one_or_none()
  557. if filament:
  558. archive.cost = round((archive.filament_used_grams / 1000) * filament.cost_per_kg, 2)
  559. else:
  560. archive.cost = round((archive.filament_used_grams / 1000) * 25.0, 2)
  561. await db.commit()
  562. await db.refresh(archive)
  563. return archive
  564. @router.post("/recalculate-costs")
  565. async def recalculate_all_costs(db: AsyncSession = Depends(get_db)):
  566. """Recalculate costs for all archives based on filament usage and prices."""
  567. result = await db.execute(select(PrintArchive))
  568. archives = list(result.scalars().all())
  569. # Load all filaments for lookup
  570. filament_result = await db.execute(select(Filament))
  571. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  572. default_cost_per_kg = 25.0
  573. updated = 0
  574. for archive in archives:
  575. if archive.filament_used_grams and archive.filament_type:
  576. primary_type = archive.filament_type.split(",")[0].strip()
  577. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  578. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  579. if archive.cost != new_cost:
  580. archive.cost = new_cost
  581. updated += 1
  582. await db.commit()
  583. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  584. @router.post("/rescan-all")
  585. async def rescan_all_archives(db: AsyncSession = Depends(get_db)):
  586. """Rescan all archives and update their metadata."""
  587. from backend.app.services.archive import ThreeMFParser
  588. result = await db.execute(select(PrintArchive))
  589. archives = list(result.scalars().all())
  590. updated = 0
  591. errors = []
  592. for archive in archives:
  593. try:
  594. file_path = settings.base_dir / archive.file_path
  595. if not file_path.exists():
  596. errors.append({"id": archive.id, "error": "File not found"})
  597. continue
  598. parser = ThreeMFParser(file_path)
  599. metadata = parser.parse()
  600. if metadata.get("filament_type"):
  601. archive.filament_type = metadata["filament_type"]
  602. if metadata.get("filament_color"):
  603. archive.filament_color = metadata["filament_color"]
  604. if metadata.get("print_time_seconds"):
  605. archive.print_time_seconds = metadata["print_time_seconds"]
  606. if metadata.get("filament_used_grams"):
  607. archive.filament_used_grams = metadata["filament_used_grams"]
  608. if metadata.get("layer_height"):
  609. archive.layer_height = metadata["layer_height"]
  610. if metadata.get("nozzle_diameter"):
  611. archive.nozzle_diameter = metadata["nozzle_diameter"]
  612. if metadata.get("makerworld_url"):
  613. archive.makerworld_url = metadata["makerworld_url"]
  614. if metadata.get("designer"):
  615. archive.designer = metadata["designer"]
  616. updated += 1
  617. except Exception as e:
  618. errors.append({"id": archive.id, "error": str(e)})
  619. await db.commit()
  620. return {"updated": updated, "errors": errors}
  621. @router.get("/{archive_id}/duplicates")
  622. async def get_archive_duplicates(archive_id: int, db: AsyncSession = Depends(get_db)):
  623. """Get duplicates for a specific archive."""
  624. service = ArchiveService(db)
  625. archive = await service.get_archive(archive_id)
  626. if not archive:
  627. raise HTTPException(404, "Archive not found")
  628. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  629. duplicates = await service.find_duplicates(
  630. archive_id=archive.id,
  631. content_hash=archive.content_hash,
  632. print_name=archive.print_name,
  633. makerworld_model_id=makerworld_id,
  634. )
  635. return {"duplicates": duplicates, "count": len(duplicates)}
  636. @router.post("/backfill-hashes")
  637. async def backfill_content_hashes(db: AsyncSession = Depends(get_db)):
  638. """Compute and store content hashes for all archives missing them."""
  639. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  640. archives = list(result.scalars().all())
  641. updated = 0
  642. errors = []
  643. for archive in archives:
  644. try:
  645. file_path = settings.base_dir / archive.file_path
  646. if not file_path.exists():
  647. errors.append({"id": archive.id, "error": "File not found"})
  648. continue
  649. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  650. updated += 1
  651. except Exception as e:
  652. errors.append({"id": archive.id, "error": str(e)})
  653. await db.commit()
  654. return {"updated": updated, "errors": errors}
  655. @router.delete("/{archive_id}")
  656. async def delete_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  657. """Delete an archive."""
  658. service = ArchiveService(db)
  659. if not await service.delete_archive(archive_id):
  660. raise HTTPException(404, "Archive not found")
  661. return {"status": "deleted"}
  662. @router.get("/{archive_id}/download")
  663. async def download_archive(
  664. archive_id: int,
  665. inline: bool = False,
  666. db: AsyncSession = Depends(get_db),
  667. ):
  668. """Download the 3MF file."""
  669. service = ArchiveService(db)
  670. archive = await service.get_archive(archive_id)
  671. if not archive:
  672. raise HTTPException(404, "Archive not found")
  673. file_path = settings.base_dir / archive.file_path
  674. if not file_path.exists():
  675. raise HTTPException(404, "File not found")
  676. # Use inline disposition to let browser/OS handle file association
  677. content_disposition = "inline" if inline else "attachment"
  678. return FileResponse(
  679. path=file_path,
  680. filename=archive.filename,
  681. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  682. content_disposition_type=content_disposition,
  683. )
  684. @router.get("/{archive_id}/file/{filename}")
  685. async def download_archive_with_filename(
  686. archive_id: int,
  687. filename: str,
  688. db: AsyncSession = Depends(get_db),
  689. ):
  690. """Download the 3MF file with filename in URL (for Bambu Studio protocol)."""
  691. service = ArchiveService(db)
  692. archive = await service.get_archive(archive_id)
  693. if not archive:
  694. raise HTTPException(404, "Archive not found")
  695. file_path = settings.base_dir / archive.file_path
  696. if not file_path.exists():
  697. raise HTTPException(404, "File not found")
  698. return FileResponse(
  699. path=file_path,
  700. filename=archive.filename,
  701. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  702. )
  703. @router.get("/{archive_id}/thumbnail")
  704. async def get_thumbnail(archive_id: int, db: AsyncSession = Depends(get_db)):
  705. """Get the thumbnail image."""
  706. service = ArchiveService(db)
  707. archive = await service.get_archive(archive_id)
  708. if not archive or not archive.thumbnail_path:
  709. raise HTTPException(404, "Thumbnail not found")
  710. thumb_path = settings.base_dir / archive.thumbnail_path
  711. if not thumb_path.exists():
  712. raise HTTPException(404, "Thumbnail file not found")
  713. # Use file modification time as ETag to bust cache
  714. mtime = int(thumb_path.stat().st_mtime)
  715. return FileResponse(
  716. path=thumb_path,
  717. media_type="image/png",
  718. headers={
  719. "Cache-Control": "no-cache, must-revalidate",
  720. "ETag": f'"{mtime}"',
  721. },
  722. )
  723. @router.get("/{archive_id}/timelapse")
  724. async def get_timelapse(archive_id: int, db: AsyncSession = Depends(get_db)):
  725. """Get the timelapse video."""
  726. service = ArchiveService(db)
  727. archive = await service.get_archive(archive_id)
  728. if not archive or not archive.timelapse_path:
  729. raise HTTPException(404, "Timelapse not found")
  730. timelapse_path = settings.base_dir / archive.timelapse_path
  731. if not timelapse_path.exists():
  732. raise HTTPException(404, "Timelapse file not found")
  733. # Use file modification time as ETag to bust cache after processing
  734. mtime = int(timelapse_path.stat().st_mtime)
  735. return FileResponse(
  736. path=timelapse_path,
  737. media_type="video/mp4",
  738. filename=f"{archive.print_name or 'timelapse'}.mp4",
  739. headers={
  740. "Cache-Control": "no-cache, must-revalidate",
  741. "ETag": f'"{mtime}"',
  742. },
  743. )
  744. @router.post("/{archive_id}/timelapse/scan")
  745. async def scan_timelapse(
  746. archive_id: int,
  747. db: AsyncSession = Depends(get_db),
  748. ):
  749. """Scan printer for timelapse matching this archive and attach it."""
  750. from backend.app.models.printer import Printer
  751. from backend.app.services.bambu_ftp import (
  752. download_file_bytes_async,
  753. get_ftp_retry_settings,
  754. list_files_async,
  755. with_ftp_retry,
  756. )
  757. service = ArchiveService(db)
  758. archive = await service.get_archive(archive_id)
  759. if not archive:
  760. raise HTTPException(404, "Archive not found")
  761. if archive.timelapse_path:
  762. return {"status": "exists", "message": "Timelapse already attached"}
  763. if not archive.printer_id:
  764. raise HTTPException(400, "Archive has no associated printer")
  765. # Get printer
  766. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  767. printer = result.scalar_one_or_none()
  768. if not printer:
  769. raise HTTPException(404, "Printer not found")
  770. # Get base name from archive filename (without .3mf extension)
  771. base_name = Path(archive.filename).stem
  772. # Scan timelapse directory on printer
  773. # Try both /timelapse and /timelapse/video (different printer models use different paths)
  774. files = []
  775. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  776. try:
  777. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  778. if files:
  779. break
  780. except Exception:
  781. continue
  782. if not files:
  783. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  784. # Look for matching timelapse
  785. matching_file = None
  786. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  787. # Strategy 1: Match by print name in filename
  788. for f in mp4_files:
  789. fname = f.get("name", "")
  790. if base_name.lower() in fname.lower():
  791. matching_file = f
  792. break
  793. # Strategy 2: Match by timestamp proximity
  794. # Bambu timelapse filename uses the print START time (when recording began)
  795. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  796. import re
  797. from datetime import datetime, timedelta
  798. # Prefer started_at since video filename is the print start time
  799. # Fall back to completed_at or created_at if started_at is not available
  800. archive_start = archive.started_at
  801. archive_end = archive.completed_at or archive.created_at
  802. best_match = None
  803. best_diff = timedelta(hours=24) # Max 24 hour difference
  804. for f in mp4_files:
  805. fname = f.get("name", "")
  806. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  807. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  808. if match:
  809. try:
  810. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  811. # Try multiple timezone offsets since printer timezone can vary
  812. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  813. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  814. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  815. # Check against start time (video filename = print start)
  816. if archive_start:
  817. diff = abs(adjusted_file_time - archive_start)
  818. if diff < best_diff:
  819. best_diff = diff
  820. best_match = f
  821. logger.debug(
  822. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  823. f"diff from start: {diff}"
  824. )
  825. # Also check against end time with a buffer
  826. # (video timestamp should be BEFORE completion time)
  827. if archive_end:
  828. # The video timestamp should be within the print duration before completion
  829. if adjusted_file_time < archive_end:
  830. diff = archive_end - adjusted_file_time
  831. # Reasonable print duration: up to 48 hours
  832. if diff < timedelta(hours=48) and diff < best_diff:
  833. best_diff = diff
  834. best_match = f
  835. logger.debug(
  836. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  837. f"diff: {diff}"
  838. )
  839. except ValueError:
  840. continue
  841. # Accept match within 4 hours (more lenient for timezone issues)
  842. if best_match and best_diff < timedelta(hours=4):
  843. matching_file = best_match
  844. logger.info(f"Matched timelapse by timestamp: {best_match.get('name')} (diff: {best_diff})")
  845. # Strategy 3: Use file modification time from FTP listing
  846. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  847. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  848. from datetime import datetime, timedelta
  849. archive_start = archive.started_at
  850. archive_end = archive.completed_at or archive.created_at
  851. best_match = None
  852. best_diff = timedelta(hours=24)
  853. for f in mp4_files:
  854. mtime = f.get("mtime")
  855. if mtime:
  856. # Timelapse file should be modified during or shortly after the print
  857. # The mtime should be close to completion time (video finishes when print ends)
  858. if archive_end:
  859. diff = abs(mtime - archive_end)
  860. if diff < best_diff:
  861. best_diff = diff
  862. best_match = f
  863. logger.debug(
  864. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  865. )
  866. if best_match and best_diff < timedelta(hours=2):
  867. matching_file = best_match
  868. logger.info(f"Matched timelapse by file mtime: {best_match.get('name')} (diff: {best_diff})")
  869. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  870. # This handles cases where printer clock is wrong or timezone issues exist
  871. if not matching_file and len(mp4_files) == 1:
  872. from datetime import datetime, timedelta
  873. archive_completed = archive.completed_at or archive.created_at
  874. if archive_completed:
  875. time_since_completion = datetime.now() - archive_completed
  876. # If archive was completed within the last hour, assume the single timelapse is for it
  877. if time_since_completion < timedelta(hours=1):
  878. matching_file = mp4_files[0]
  879. logger.info(f"Using single timelapse file as fallback: {mp4_files[0].get('name')}")
  880. # Note: We intentionally don't use a "most recent file" fallback because
  881. # we can't verify if timelapse was actually enabled for this print.
  882. # Instead, return the list of available files for manual selection.
  883. if not matching_file:
  884. # Return available files for manual selection
  885. available_files = [
  886. {
  887. "name": f.get("name"),
  888. "path": f.get("path"),
  889. "size": f.get("size"),
  890. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  891. }
  892. for f in mp4_files
  893. ]
  894. # Sort by mtime descending (most recent first)
  895. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  896. return {
  897. "status": "not_found",
  898. "message": "No matching timelapse found - please select manually",
  899. "available_files": available_files,
  900. }
  901. # Download the timelapse - use the full path from the file listing
  902. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  903. # Get FTP retry settings
  904. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  905. if ftp_retry_enabled:
  906. timelapse_data = await with_ftp_retry(
  907. download_file_bytes_async,
  908. printer.ip_address,
  909. printer.access_code,
  910. remote_path,
  911. socket_timeout=ftp_timeout,
  912. printer_model=printer.model,
  913. max_retries=ftp_retry_count,
  914. retry_delay=ftp_retry_delay,
  915. operation_name=f"Download timelapse {matching_file['name']}",
  916. )
  917. else:
  918. timelapse_data = await download_file_bytes_async(
  919. printer.ip_address,
  920. printer.access_code,
  921. remote_path,
  922. socket_timeout=ftp_timeout,
  923. printer_model=printer.model,
  924. )
  925. if not timelapse_data:
  926. raise HTTPException(500, "Failed to download timelapse")
  927. # Attach timelapse to archive
  928. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  929. if not success:
  930. raise HTTPException(500, "Failed to attach timelapse")
  931. return {
  932. "status": "attached",
  933. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  934. "filename": matching_file["name"],
  935. }
  936. @router.post("/{archive_id}/timelapse/select")
  937. async def select_timelapse(
  938. archive_id: int,
  939. filename: str = Query(..., description="Timelapse filename to attach"),
  940. db: AsyncSession = Depends(get_db),
  941. ):
  942. """Manually select a timelapse from the printer to attach."""
  943. from backend.app.models.printer import Printer
  944. from backend.app.services.bambu_ftp import (
  945. download_file_bytes_async,
  946. get_ftp_retry_settings,
  947. list_files_async,
  948. with_ftp_retry,
  949. )
  950. service = ArchiveService(db)
  951. archive = await service.get_archive(archive_id)
  952. if not archive:
  953. raise HTTPException(404, "Archive not found")
  954. if not archive.printer_id:
  955. raise HTTPException(400, "Archive has no associated printer")
  956. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  957. printer = result.scalar_one_or_none()
  958. if not printer:
  959. raise HTTPException(404, "Printer not found")
  960. # Find the file on the printer
  961. files = []
  962. remote_path = None
  963. for timelapse_dir in ["/timelapse", "/timelapse/video"]:
  964. try:
  965. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_dir)
  966. for f in files:
  967. if f.get("name") == filename:
  968. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  969. break
  970. if remote_path:
  971. break
  972. except Exception:
  973. continue
  974. if not remote_path:
  975. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  976. # Download and attach
  977. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  978. if ftp_retry_enabled:
  979. timelapse_data = await with_ftp_retry(
  980. download_file_bytes_async,
  981. printer.ip_address,
  982. printer.access_code,
  983. remote_path,
  984. socket_timeout=ftp_timeout,
  985. printer_model=printer.model,
  986. max_retries=ftp_retry_count,
  987. retry_delay=ftp_retry_delay,
  988. operation_name=f"Download timelapse {filename}",
  989. )
  990. else:
  991. timelapse_data = await download_file_bytes_async(
  992. printer.ip_address,
  993. printer.access_code,
  994. remote_path,
  995. socket_timeout=ftp_timeout,
  996. printer_model=printer.model,
  997. )
  998. if not timelapse_data:
  999. raise HTTPException(500, "Failed to download timelapse")
  1000. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  1001. if not success:
  1002. raise HTTPException(500, "Failed to attach timelapse")
  1003. return {
  1004. "status": "attached",
  1005. "message": f"Timelapse '{filename}' attached successfully",
  1006. "filename": filename,
  1007. }
  1008. @router.post("/{archive_id}/timelapse/upload")
  1009. async def upload_timelapse(
  1010. archive_id: int,
  1011. file: UploadFile = File(...),
  1012. db: AsyncSession = Depends(get_db),
  1013. ):
  1014. """Manually upload a timelapse video to an archive."""
  1015. service = ArchiveService(db)
  1016. archive = await service.get_archive(archive_id)
  1017. if not archive:
  1018. raise HTTPException(404, "Archive not found")
  1019. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  1020. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  1021. content = await file.read()
  1022. success = await service.attach_timelapse(archive_id, content, file.filename)
  1023. if not success:
  1024. raise HTTPException(500, "Failed to attach timelapse")
  1025. return {"status": "attached", "filename": file.filename}
  1026. @router.get("/{archive_id}/timelapse/info")
  1027. async def get_timelapse_info(archive_id: int, db: AsyncSession = Depends(get_db)):
  1028. """Get timelapse video metadata for editor."""
  1029. from backend.app.schemas.timelapse import TimelapseInfoResponse
  1030. from backend.app.services.timelapse_processor import TimelapseProcessor
  1031. service = ArchiveService(db)
  1032. archive = await service.get_archive(archive_id)
  1033. if not archive or not archive.timelapse_path:
  1034. raise HTTPException(404, "Timelapse not found")
  1035. timelapse_path = settings.base_dir / archive.timelapse_path
  1036. if not timelapse_path.exists():
  1037. raise HTTPException(404, "Timelapse file not found")
  1038. try:
  1039. processor = TimelapseProcessor(timelapse_path)
  1040. info = await processor.get_info()
  1041. return TimelapseInfoResponse(**info)
  1042. except Exception as e:
  1043. logger.error(f"Failed to get timelapse info: {e}")
  1044. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  1045. @router.get("/{archive_id}/timelapse/thumbnails")
  1046. async def get_timelapse_thumbnails(
  1047. archive_id: int,
  1048. count: int = Query(10, ge=1, le=30),
  1049. width: int = Query(160, ge=80, le=320),
  1050. db: AsyncSession = Depends(get_db),
  1051. ):
  1052. """Generate timeline thumbnail frames for visual scrubbing."""
  1053. import base64
  1054. from backend.app.schemas.timelapse import ThumbnailResponse
  1055. from backend.app.services.timelapse_processor import TimelapseProcessor
  1056. service = ArchiveService(db)
  1057. archive = await service.get_archive(archive_id)
  1058. if not archive or not archive.timelapse_path:
  1059. raise HTTPException(404, "Timelapse not found")
  1060. timelapse_path = settings.base_dir / archive.timelapse_path
  1061. if not timelapse_path.exists():
  1062. raise HTTPException(404, "Timelapse file not found")
  1063. try:
  1064. processor = TimelapseProcessor(timelapse_path)
  1065. thumbnails = await processor.generate_thumbnails(count, width)
  1066. return ThumbnailResponse(
  1067. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1068. timestamps=[ts for ts, _ in thumbnails],
  1069. )
  1070. except Exception as e:
  1071. logger.error(f"Failed to generate thumbnails: {e}")
  1072. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1073. @router.post("/{archive_id}/timelapse/process")
  1074. async def process_timelapse(
  1075. archive_id: int,
  1076. trim_start: float = Form(0),
  1077. trim_end: float = Form(None),
  1078. speed: float = Form(1.0),
  1079. save_mode: str = Form("new"),
  1080. output_filename: str = Form(None),
  1081. audio: UploadFile = File(None),
  1082. db: AsyncSession = Depends(get_db),
  1083. ):
  1084. """Process timelapse with trim, speed, and optional audio overlay."""
  1085. import shutil
  1086. import tempfile
  1087. from backend.app.schemas.timelapse import ProcessResponse
  1088. from backend.app.services.timelapse_processor import TimelapseProcessor
  1089. # Validate speed
  1090. if not 0.25 <= speed <= 4.0:
  1091. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1092. if save_mode not in ("replace", "new"):
  1093. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1094. service = ArchiveService(db)
  1095. archive = await service.get_archive(archive_id)
  1096. if not archive or not archive.timelapse_path:
  1097. raise HTTPException(404, "Timelapse not found")
  1098. timelapse_path = settings.base_dir / archive.timelapse_path
  1099. if not timelapse_path.exists():
  1100. raise HTTPException(404, "Timelapse file not found")
  1101. archive_dir = timelapse_path.parent
  1102. # Handle audio file
  1103. audio_temp_path = None
  1104. if audio and audio.filename:
  1105. # Validate audio file extension
  1106. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  1107. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  1108. audio_content = await audio.read()
  1109. suffix = Path(audio.filename).suffix
  1110. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  1111. audio_temp_path.write_bytes(audio_content)
  1112. try:
  1113. processor = TimelapseProcessor(timelapse_path)
  1114. # Determine output path
  1115. if save_mode == "replace":
  1116. # Process to temp file first, then replace
  1117. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  1118. output_path = temp_output
  1119. else:
  1120. # Save as new file alongside original
  1121. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  1122. # Sanitize filename
  1123. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  1124. if not filename.endswith(".mp4"):
  1125. filename += ".mp4"
  1126. output_path = archive_dir / filename
  1127. success = await processor.process(
  1128. output_path=output_path,
  1129. trim_start=trim_start,
  1130. trim_end=trim_end,
  1131. speed=speed,
  1132. audio_path=audio_temp_path,
  1133. )
  1134. if not success:
  1135. raise HTTPException(500, "Video processing failed")
  1136. # Handle save mode
  1137. if save_mode == "replace":
  1138. # Replace original file
  1139. shutil.move(str(output_path), str(timelapse_path))
  1140. final_path = archive.timelapse_path
  1141. message = "Timelapse replaced successfully"
  1142. else:
  1143. final_path = str(output_path.relative_to(settings.base_dir))
  1144. message = f"Saved as {output_path.name}"
  1145. return ProcessResponse(
  1146. status="completed",
  1147. output_path=final_path,
  1148. message=message,
  1149. )
  1150. except HTTPException:
  1151. raise
  1152. except Exception as e:
  1153. logger.error(f"Timelapse processing failed: {e}")
  1154. raise HTTPException(500, f"Processing failed: {str(e)}")
  1155. finally:
  1156. # Cleanup temp audio file
  1157. if audio_temp_path and audio_temp_path.exists():
  1158. audio_temp_path.unlink()
  1159. # ============================================
  1160. # Photo Endpoints
  1161. # ============================================
  1162. @router.post("/{archive_id}/photos")
  1163. async def upload_photo(
  1164. archive_id: int,
  1165. file: UploadFile = File(...),
  1166. db: AsyncSession = Depends(get_db),
  1167. ):
  1168. """Upload a photo of the printed result."""
  1169. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1170. archive = result.scalar_one_or_none()
  1171. if not archive:
  1172. raise HTTPException(404, "Archive not found")
  1173. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  1174. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  1175. # Get archive directory
  1176. file_path = settings.base_dir / archive.file_path
  1177. archive_dir = file_path.parent
  1178. photos_dir = archive_dir / "photos"
  1179. photos_dir.mkdir(exist_ok=True)
  1180. # Generate unique filename
  1181. import uuid
  1182. ext = Path(file.filename).suffix.lower()
  1183. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  1184. photo_path = photos_dir / photo_filename
  1185. # Save file
  1186. content = await file.read()
  1187. photo_path.write_bytes(content)
  1188. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  1189. photos = list(archive.photos or [])
  1190. photos.append(photo_filename)
  1191. archive.photos = photos
  1192. await db.commit()
  1193. await db.refresh(archive)
  1194. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  1195. @router.get("/{archive_id}/photos/{filename}")
  1196. async def get_photo(
  1197. archive_id: int,
  1198. filename: str,
  1199. db: AsyncSession = Depends(get_db),
  1200. ):
  1201. """Get a specific photo."""
  1202. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1203. archive = result.scalar_one_or_none()
  1204. if not archive:
  1205. raise HTTPException(404, "Archive not found")
  1206. file_path = settings.base_dir / archive.file_path
  1207. photo_path = file_path.parent / "photos" / filename
  1208. if not photo_path.exists():
  1209. raise HTTPException(404, "Photo not found")
  1210. # Determine media type
  1211. ext = Path(filename).suffix.lower()
  1212. media_types = {
  1213. ".jpg": "image/jpeg",
  1214. ".jpeg": "image/jpeg",
  1215. ".png": "image/png",
  1216. ".webp": "image/webp",
  1217. }
  1218. media_type = media_types.get(ext, "image/jpeg")
  1219. return FileResponse(path=photo_path, media_type=media_type)
  1220. @router.delete("/{archive_id}/photos/{filename}")
  1221. async def delete_photo(
  1222. archive_id: int,
  1223. filename: str,
  1224. db: AsyncSession = Depends(get_db),
  1225. ):
  1226. """Delete a photo."""
  1227. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1228. archive = result.scalar_one_or_none()
  1229. if not archive:
  1230. raise HTTPException(404, "Archive not found")
  1231. if not archive.photos or filename not in archive.photos:
  1232. raise HTTPException(404, "Photo not found")
  1233. # Delete file
  1234. file_path = settings.base_dir / archive.file_path
  1235. photo_path = file_path.parent / "photos" / filename
  1236. if photo_path.exists():
  1237. photo_path.unlink()
  1238. # Update archive photos list
  1239. photos = [p for p in archive.photos if p != filename]
  1240. archive.photos = photos if photos else None
  1241. await db.commit()
  1242. return {"status": "deleted", "photos": archive.photos}
  1243. # ============================================
  1244. # QR Code Endpoint
  1245. # ============================================
  1246. @router.get("/{archive_id}/qrcode")
  1247. async def get_qrcode(
  1248. archive_id: int,
  1249. request: Request,
  1250. size: int = 200,
  1251. db: AsyncSession = Depends(get_db),
  1252. ):
  1253. """Generate a QR code that links to this archive."""
  1254. try:
  1255. import qrcode
  1256. from PIL import Image as PILImage
  1257. except ImportError:
  1258. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  1259. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1260. archive = result.scalar_one_or_none()
  1261. if not archive:
  1262. raise HTTPException(404, "Archive not found")
  1263. # Build URL to archive download
  1264. base_url = str(request.base_url).rstrip("/")
  1265. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  1266. # Generate QR code
  1267. qr = qrcode.QRCode(
  1268. version=1,
  1269. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1270. box_size=10,
  1271. border=2,
  1272. )
  1273. qr.add_data(archive_url)
  1274. qr.make(fit=True)
  1275. img = qr.make_image(fill_color="black", back_color="white")
  1276. # Convert to PIL Image for resizing
  1277. pil_img = img.get_image()
  1278. # Resize if needed
  1279. if size != 200:
  1280. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  1281. # Convert to bytes
  1282. buffer = io.BytesIO()
  1283. pil_img.save(buffer, format="PNG")
  1284. buffer.seek(0)
  1285. return Response(
  1286. content=buffer.getvalue(),
  1287. media_type="image/png",
  1288. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1289. )
  1290. @router.get("/{archive_id}/capabilities")
  1291. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  1292. """Check what viewing capabilities are available for this 3MF file."""
  1293. import json
  1294. import xml.etree.ElementTree as ET
  1295. service = ArchiveService(db)
  1296. archive = await service.get_archive(archive_id)
  1297. if not archive:
  1298. raise HTTPException(404, "Archive not found")
  1299. file_path = settings.base_dir / archive.file_path
  1300. if not file_path.exists():
  1301. raise HTTPException(404, "File not found")
  1302. has_model = False
  1303. has_gcode = False
  1304. has_source = False
  1305. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1306. filament_colors: list[str] = []
  1307. # Check if source 3MF exists - this is where actual mesh data typically lives
  1308. source_path = None
  1309. if archive.source_3mf_path:
  1310. source_path = settings.base_dir / archive.source_3mf_path
  1311. if source_path.exists():
  1312. has_source = True
  1313. # Helper function to check for mesh data and extract colors from a 3MF file
  1314. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  1315. """Extract mesh presence, colors, and build volume from a 3MF file."""
  1316. found_mesh = False
  1317. colors: list[str] = []
  1318. volume = {"x": 256, "y": 256, "z": 256}
  1319. try:
  1320. with zipfile.ZipFile(zf_path, "r") as zf:
  1321. names = zf.namelist()
  1322. # Check for 3D model - look for actual mesh data
  1323. for name in names:
  1324. if name.endswith(".model"):
  1325. try:
  1326. content = zf.read(name).decode("utf-8")
  1327. if "<vertex" in content or "<mesh" in content:
  1328. found_mesh = True
  1329. break
  1330. except Exception:
  1331. pass
  1332. # Extract filament colors from project_settings.config
  1333. if "Metadata/project_settings.config" in names:
  1334. try:
  1335. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1336. config_data = json.loads(config_content)
  1337. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1338. printable_area = config_data.get("printable_area", [])
  1339. if printable_area and len(printable_area) >= 3:
  1340. max_x = 0
  1341. max_y = 0
  1342. for coord in printable_area:
  1343. if "x" in coord:
  1344. parts = coord.split("x")
  1345. if len(parts) == 2:
  1346. try:
  1347. x, y = int(parts[0]), int(parts[1])
  1348. max_x = max(max_x, x)
  1349. max_y = max(max_y, y)
  1350. except ValueError:
  1351. pass
  1352. if max_x > 0 and max_y > 0:
  1353. volume["x"] = max_x
  1354. volume["y"] = max_y
  1355. # Parse printable_height
  1356. printable_height = config_data.get("printable_height")
  1357. if printable_height:
  1358. try:
  1359. volume["z"] = int(printable_height)
  1360. except (ValueError, TypeError):
  1361. pass
  1362. # Extract filament colors
  1363. raw_colors = config_data.get("filament_colour", [])
  1364. if raw_colors:
  1365. for color in raw_colors:
  1366. if color and isinstance(color, str):
  1367. colors.append(color)
  1368. except Exception:
  1369. pass
  1370. except zipfile.BadZipFile:
  1371. pass
  1372. return found_mesh, colors, volume
  1373. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  1374. if has_source and source_path:
  1375. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  1376. if source_has_mesh:
  1377. has_model = True
  1378. if source_colors:
  1379. filament_colors = source_colors
  1380. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  1381. build_volume = source_volume
  1382. try:
  1383. with zipfile.ZipFile(file_path, "r") as zf:
  1384. names = zf.namelist()
  1385. # Check for G-code in the sliced file
  1386. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1387. # Check for 3D model in sliced file (fallback if no source)
  1388. if not has_model:
  1389. for name in names:
  1390. if name.endswith(".model"):
  1391. try:
  1392. content = zf.read(name).decode("utf-8")
  1393. if "<vertex" in content or "<mesh" in content:
  1394. has_model = True
  1395. break
  1396. except Exception:
  1397. pass
  1398. # Extract filament colors from slice_info.config (for gcode preview)
  1399. # These are the actual filaments used in the print, indexed by tool/extruder
  1400. slice_colors: list[str] = []
  1401. if "Metadata/slice_info.config" in names:
  1402. try:
  1403. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1404. root = ET.fromstring(slice_content)
  1405. filaments = root.findall(".//filament")
  1406. filament_map: dict[int, str] = {}
  1407. for f in filaments:
  1408. fid = f.get("id")
  1409. fcolor = f.get("color")
  1410. used_g = f.get("used_g", "0")
  1411. try:
  1412. used_amount = float(used_g)
  1413. except (ValueError, TypeError):
  1414. used_amount = 0
  1415. if fid is not None and fcolor:
  1416. try:
  1417. tool_id = int(fid) - 1
  1418. if tool_id >= 0 and used_amount > 0:
  1419. filament_map[tool_id] = fcolor
  1420. except ValueError:
  1421. pass
  1422. if filament_map:
  1423. max_tool = max(filament_map.keys())
  1424. for i in range(max_tool + 1):
  1425. slice_colors.append(filament_map.get(i, "#00AE42"))
  1426. except Exception:
  1427. pass
  1428. # Use slice_info colors if we don't have colors from source yet
  1429. if not filament_colors and slice_colors:
  1430. filament_colors = slice_colors
  1431. # Extract build volume from sliced file if not already set from source
  1432. if build_volume["x"] == 256 and build_volume["y"] == 256:
  1433. if "Metadata/project_settings.config" in names:
  1434. try:
  1435. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1436. config_data = json.loads(config_content)
  1437. printable_area = config_data.get("printable_area", [])
  1438. if printable_area and len(printable_area) >= 3:
  1439. max_x = 0
  1440. max_y = 0
  1441. for coord in printable_area:
  1442. if "x" in coord:
  1443. parts = coord.split("x")
  1444. if len(parts) == 2:
  1445. try:
  1446. x, y = int(parts[0]), int(parts[1])
  1447. max_x = max(max_x, x)
  1448. max_y = max(max_y, y)
  1449. except ValueError:
  1450. pass
  1451. if max_x > 0 and max_y > 0:
  1452. build_volume["x"] = max_x
  1453. build_volume["y"] = max_y
  1454. printable_height = config_data.get("printable_height")
  1455. if printable_height:
  1456. try:
  1457. build_volume["z"] = int(printable_height)
  1458. except (ValueError, TypeError):
  1459. pass
  1460. # Fallback colors from project_settings if still empty
  1461. if not filament_colors:
  1462. raw_colors = config_data.get("filament_colour", [])
  1463. if raw_colors:
  1464. for color in raw_colors:
  1465. if color and isinstance(color, str):
  1466. filament_colors.append(color)
  1467. except Exception:
  1468. pass
  1469. except zipfile.BadZipFile:
  1470. raise HTTPException(400, "Invalid 3MF file")
  1471. return {
  1472. "has_model": has_model,
  1473. "has_gcode": has_gcode,
  1474. "has_source": has_source,
  1475. "build_volume": build_volume,
  1476. "filament_colors": filament_colors,
  1477. }
  1478. @router.get("/{archive_id}/gcode")
  1479. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  1480. """Extract and return G-code from the 3MF file."""
  1481. service = ArchiveService(db)
  1482. archive = await service.get_archive(archive_id)
  1483. if not archive:
  1484. raise HTTPException(404, "Archive not found")
  1485. file_path = settings.base_dir / archive.file_path
  1486. if not file_path.exists():
  1487. raise HTTPException(404, "File not found")
  1488. try:
  1489. with zipfile.ZipFile(file_path, "r") as zf:
  1490. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1491. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1492. if not gcode_files:
  1493. raise HTTPException(
  1494. 404,
  1495. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1496. )
  1497. # Get the first plate's G-code (usually plate_1.gcode)
  1498. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1499. return Response(content=gcode_content, media_type="text/plain")
  1500. except zipfile.BadZipFile:
  1501. raise HTTPException(400, "Invalid 3MF file")
  1502. except HTTPException:
  1503. raise
  1504. except Exception as e:
  1505. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1506. @router.get("/{archive_id}/plate-preview")
  1507. async def get_plate_preview(archive_id: int, db: AsyncSession = Depends(get_db)):
  1508. """Get the plate preview image from the 3MF file.
  1509. Returns the slicer-generated plate thumbnail which shows the model
  1510. with correct colors and positioning.
  1511. """
  1512. service = ArchiveService(db)
  1513. archive = await service.get_archive(archive_id)
  1514. if not archive:
  1515. raise HTTPException(404, "Archive not found")
  1516. file_path = settings.base_dir / archive.file_path
  1517. if not file_path.exists():
  1518. raise HTTPException(404, "File not found")
  1519. try:
  1520. with zipfile.ZipFile(file_path, "r") as zf:
  1521. names = zf.namelist()
  1522. # Try to find plate preview images in order of preference
  1523. # First look for the specific plate being printed (check slice_info for plate index)
  1524. plate_num = 1
  1525. if "Metadata/slice_info.config" in names:
  1526. try:
  1527. import xml.etree.ElementTree as ET
  1528. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1529. root = ET.fromstring(slice_content)
  1530. plate_elem = root.find(".//plate/metadata[@key='index']")
  1531. if plate_elem is not None:
  1532. plate_num = int(plate_elem.get("value", "1"))
  1533. except Exception:
  1534. pass
  1535. # Try plate-specific image first, then fall back to plate_1
  1536. preview_paths = [
  1537. f"Metadata/plate_{plate_num}.png",
  1538. "Metadata/plate_1.png",
  1539. "Metadata/thumbnail.png",
  1540. ]
  1541. for preview_path in preview_paths:
  1542. if preview_path in names:
  1543. image_data = zf.read(preview_path)
  1544. return Response(content=image_data, media_type="image/png")
  1545. # If no plate image, try any PNG in Metadata
  1546. for name in names:
  1547. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  1548. image_data = zf.read(name)
  1549. return Response(content=image_data, media_type="image/png")
  1550. raise HTTPException(404, "No plate preview found in 3MF file")
  1551. except zipfile.BadZipFile:
  1552. raise HTTPException(400, "Invalid 3MF file")
  1553. except HTTPException:
  1554. raise
  1555. except Exception as e:
  1556. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  1557. @router.post("/upload")
  1558. async def upload_archive(
  1559. file: UploadFile = File(...),
  1560. printer_id: int | None = None,
  1561. db: AsyncSession = Depends(get_db),
  1562. ):
  1563. """Manually upload a 3MF file to archive."""
  1564. if not file.filename or not file.filename.endswith(".3mf"):
  1565. raise HTTPException(400, "File must be a .3mf file")
  1566. # Save uploaded file temporarily
  1567. temp_path = settings.archive_dir / "temp" / file.filename
  1568. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1569. try:
  1570. content = await file.read()
  1571. temp_path.write_bytes(content)
  1572. service = ArchiveService(db)
  1573. archive = await service.archive_print(
  1574. printer_id=printer_id,
  1575. source_file=temp_path,
  1576. )
  1577. if not archive:
  1578. raise HTTPException(400, "Failed to archive file")
  1579. return ArchiveResponse.model_validate(archive)
  1580. finally:
  1581. if temp_path.exists():
  1582. temp_path.unlink()
  1583. @router.post("/upload-bulk")
  1584. async def upload_archives_bulk(
  1585. files: list[UploadFile] = File(...),
  1586. printer_id: int | None = None,
  1587. db: AsyncSession = Depends(get_db),
  1588. ):
  1589. """Bulk upload multiple 3MF files to archive."""
  1590. results = []
  1591. errors = []
  1592. for file in files:
  1593. if not file.filename or not file.filename.endswith(".3mf"):
  1594. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1595. continue
  1596. temp_path = settings.archive_dir / "temp" / file.filename
  1597. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1598. try:
  1599. content = await file.read()
  1600. temp_path.write_bytes(content)
  1601. service = ArchiveService(db)
  1602. archive = await service.archive_print(
  1603. printer_id=printer_id,
  1604. source_file=temp_path,
  1605. )
  1606. if archive:
  1607. results.append(
  1608. {
  1609. "filename": file.filename,
  1610. "id": archive.id,
  1611. "status": "success",
  1612. }
  1613. )
  1614. else:
  1615. errors.append({"filename": file.filename, "error": "Failed to process"})
  1616. except Exception as e:
  1617. errors.append({"filename": file.filename, "error": str(e)})
  1618. finally:
  1619. if temp_path.exists():
  1620. temp_path.unlink()
  1621. return {
  1622. "uploaded": len(results),
  1623. "failed": len(errors),
  1624. "results": results,
  1625. "errors": errors,
  1626. }
  1627. @router.get("/{archive_id}/plates")
  1628. async def get_archive_plates(
  1629. archive_id: int,
  1630. db: AsyncSession = Depends(get_db),
  1631. ):
  1632. """Get available plates from a multi-plate 3MF archive.
  1633. Returns a list of plates with their index, name, thumbnail availability,
  1634. and filament requirements. For single-plate exports, returns a single plate.
  1635. """
  1636. import xml.etree.ElementTree as ET
  1637. service = ArchiveService(db)
  1638. archive = await service.get_archive(archive_id)
  1639. if not archive:
  1640. raise HTTPException(404, "Archive not found")
  1641. file_path = settings.base_dir / archive.file_path
  1642. if not file_path.exists():
  1643. raise HTTPException(404, "Archive file not found")
  1644. plates = []
  1645. try:
  1646. with zipfile.ZipFile(file_path, "r") as zf:
  1647. namelist = zf.namelist()
  1648. # Find all plate gcode files to determine available plates
  1649. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1650. if not gcode_files:
  1651. # No sliced plates found
  1652. return {"archive_id": archive_id, "filename": archive.filename, "plates": []}
  1653. # Extract plate indices from gcode filenames
  1654. plate_indices = []
  1655. for gf in gcode_files:
  1656. # "Metadata/plate_5.gcode" -> 5
  1657. try:
  1658. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1659. plate_indices.append(int(plate_str))
  1660. except ValueError:
  1661. pass
  1662. plate_indices.sort()
  1663. # Parse model_settings.config for plate names
  1664. # Plate names are stored with plater_id and plater_name keys
  1665. plate_names = {} # plater_id -> name
  1666. if "Metadata/model_settings.config" in namelist:
  1667. try:
  1668. model_content = zf.read("Metadata/model_settings.config").decode()
  1669. model_root = ET.fromstring(model_content)
  1670. for plate_elem in model_root.findall(".//plate"):
  1671. plater_id = None
  1672. plater_name = None
  1673. for meta in plate_elem.findall("metadata"):
  1674. key = meta.get("key")
  1675. value = meta.get("value")
  1676. if key == "plater_id" and value:
  1677. try:
  1678. plater_id = int(value)
  1679. except ValueError:
  1680. pass
  1681. elif key == "plater_name" and value:
  1682. plater_name = value.strip()
  1683. if plater_id is not None and plater_name:
  1684. plate_names[plater_id] = plater_name
  1685. except Exception:
  1686. pass # model_settings.config parsing is optional
  1687. # Parse slice_info.config for plate metadata
  1688. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  1689. if "Metadata/slice_info.config" in namelist:
  1690. content = zf.read("Metadata/slice_info.config").decode()
  1691. root = ET.fromstring(content)
  1692. for plate_elem in root.findall(".//plate"):
  1693. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1694. # Get plate index from metadata
  1695. plate_index = None
  1696. for meta in plate_elem.findall("metadata"):
  1697. key = meta.get("key")
  1698. value = meta.get("value")
  1699. if key == "index" and value:
  1700. try:
  1701. plate_index = int(value)
  1702. except ValueError:
  1703. pass
  1704. elif key == "prediction" and value:
  1705. try:
  1706. plate_info["prediction"] = int(value)
  1707. except ValueError:
  1708. pass
  1709. elif key == "weight" and value:
  1710. try:
  1711. plate_info["weight"] = float(value)
  1712. except ValueError:
  1713. pass
  1714. # Get filaments used in this plate
  1715. for filament_elem in plate_elem.findall("filament"):
  1716. filament_id = filament_elem.get("id")
  1717. filament_type = filament_elem.get("type", "")
  1718. filament_color = filament_elem.get("color", "")
  1719. used_g = filament_elem.get("used_g", "0")
  1720. used_m = filament_elem.get("used_m", "0")
  1721. try:
  1722. used_grams = float(used_g)
  1723. except (ValueError, TypeError):
  1724. used_grams = 0
  1725. if used_grams > 0 and filament_id:
  1726. plate_info["filaments"].append(
  1727. {
  1728. "slot_id": int(filament_id),
  1729. "type": filament_type,
  1730. "color": filament_color,
  1731. "used_grams": round(used_grams, 1),
  1732. "used_meters": float(used_m) if used_m else 0,
  1733. }
  1734. )
  1735. # Sort filaments by slot ID
  1736. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  1737. # Collect all object names on this plate
  1738. for obj_elem in plate_elem.findall("object"):
  1739. obj_name = obj_elem.get("name")
  1740. if obj_name and obj_name not in plate_info["objects"]:
  1741. plate_info["objects"].append(obj_name)
  1742. # Set plate name: prefer custom name from model_settings.config,
  1743. # fall back to first object name if no custom name was set
  1744. if plate_index is not None:
  1745. custom_name = plate_names.get(plate_index)
  1746. if custom_name:
  1747. plate_info["name"] = custom_name
  1748. else:
  1749. # Fall back to first object name as hint
  1750. if plate_info["objects"]:
  1751. plate_info["name"] = plate_info["objects"][0]
  1752. plate_metadata[plate_index] = plate_info
  1753. # Build plate list
  1754. for idx in plate_indices:
  1755. meta = plate_metadata.get(idx, {})
  1756. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1757. plates.append(
  1758. {
  1759. "index": idx,
  1760. "name": meta.get("name"),
  1761. "objects": meta.get("objects", []),
  1762. "has_thumbnail": has_thumbnail,
  1763. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  1764. if has_thumbnail
  1765. else None,
  1766. "print_time_seconds": meta.get("prediction"),
  1767. "filament_used_grams": meta.get("weight"),
  1768. "filaments": meta.get("filaments", []),
  1769. }
  1770. )
  1771. except Exception as e:
  1772. logger.warning(f"Failed to parse plates from archive {archive_id}: {e}")
  1773. return {
  1774. "archive_id": archive_id,
  1775. "filename": archive.filename,
  1776. "plates": plates,
  1777. "is_multi_plate": len(plates) > 1,
  1778. }
  1779. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  1780. async def get_plate_thumbnail(
  1781. archive_id: int,
  1782. plate_index: int,
  1783. db: AsyncSession = Depends(get_db),
  1784. ):
  1785. """Get the thumbnail image for a specific plate."""
  1786. service = ArchiveService(db)
  1787. archive = await service.get_archive(archive_id)
  1788. if not archive:
  1789. raise HTTPException(404, "Archive not found")
  1790. file_path = settings.base_dir / archive.file_path
  1791. if not file_path.exists():
  1792. raise HTTPException(404, "Archive file not found")
  1793. try:
  1794. with zipfile.ZipFile(file_path, "r") as zf:
  1795. thumb_path = f"Metadata/plate_{plate_index}.png"
  1796. if thumb_path in zf.namelist():
  1797. data = zf.read(thumb_path)
  1798. return Response(content=data, media_type="image/png")
  1799. except Exception:
  1800. pass
  1801. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  1802. @router.get("/{archive_id}/filament-requirements")
  1803. async def get_filament_requirements(
  1804. archive_id: int,
  1805. plate_id: int | None = None,
  1806. db: AsyncSession = Depends(get_db),
  1807. ):
  1808. """Get filament requirements from the archived 3MF file.
  1809. Returns the filaments used in this print with their slot IDs, types, colors,
  1810. and usage amounts. This can be compared with current AMS state before reprinting.
  1811. Args:
  1812. archive_id: The archive ID
  1813. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  1814. """
  1815. import xml.etree.ElementTree as ET
  1816. service = ArchiveService(db)
  1817. archive = await service.get_archive(archive_id)
  1818. if not archive:
  1819. raise HTTPException(404, "Archive not found")
  1820. file_path = settings.base_dir / archive.file_path
  1821. if not file_path.exists():
  1822. raise HTTPException(404, "Archive file not found")
  1823. filaments = []
  1824. try:
  1825. with zipfile.ZipFile(file_path, "r") as zf:
  1826. # Parse slice_info.config for filament requirements
  1827. if "Metadata/slice_info.config" in zf.namelist():
  1828. content = zf.read("Metadata/slice_info.config").decode()
  1829. root = ET.fromstring(content)
  1830. # If plate_id is specified, find filaments for that specific plate
  1831. if plate_id is not None:
  1832. # Find the plate element with matching index
  1833. for plate_elem in root.findall(".//plate"):
  1834. plate_index = None
  1835. for meta in plate_elem.findall("metadata"):
  1836. if meta.get("key") == "index":
  1837. try:
  1838. plate_index = int(meta.get("value", "0"))
  1839. except ValueError:
  1840. pass
  1841. break
  1842. if plate_index == plate_id:
  1843. # Extract filaments from this plate element
  1844. for filament_elem in plate_elem.findall("filament"):
  1845. filament_id = filament_elem.get("id")
  1846. filament_type = filament_elem.get("type", "")
  1847. filament_color = filament_elem.get("color", "")
  1848. used_g = filament_elem.get("used_g", "0")
  1849. used_m = filament_elem.get("used_m", "0")
  1850. try:
  1851. used_grams = float(used_g)
  1852. except (ValueError, TypeError):
  1853. used_grams = 0
  1854. if used_grams > 0 and filament_id:
  1855. filaments.append(
  1856. {
  1857. "slot_id": int(filament_id),
  1858. "type": filament_type,
  1859. "color": filament_color,
  1860. "used_grams": round(used_grams, 1),
  1861. "used_meters": float(used_m) if used_m else 0,
  1862. }
  1863. )
  1864. break
  1865. else:
  1866. # No plate_id specified - extract all filaments with used_g > 0
  1867. # This is the legacy behavior for single-plate files
  1868. for filament_elem in root.findall(".//filament"):
  1869. filament_id = filament_elem.get("id")
  1870. filament_type = filament_elem.get("type", "")
  1871. filament_color = filament_elem.get("color", "")
  1872. used_g = filament_elem.get("used_g", "0")
  1873. used_m = filament_elem.get("used_m", "0")
  1874. # Only include filaments that are actually used
  1875. try:
  1876. used_grams = float(used_g)
  1877. except (ValueError, TypeError):
  1878. used_grams = 0
  1879. if used_grams > 0 and filament_id:
  1880. filaments.append(
  1881. {
  1882. "slot_id": int(filament_id),
  1883. "type": filament_type,
  1884. "color": filament_color,
  1885. "used_grams": round(used_grams, 1),
  1886. "used_meters": float(used_m) if used_m else 0,
  1887. }
  1888. )
  1889. # Sort by slot ID
  1890. filaments.sort(key=lambda x: x["slot_id"])
  1891. except Exception as e:
  1892. logger.warning(f"Failed to parse filament requirements from archive {archive_id}: {e}")
  1893. return {
  1894. "archive_id": archive_id,
  1895. "filename": archive.filename,
  1896. "plate_id": plate_id,
  1897. "filaments": filaments,
  1898. }
  1899. @router.post("/{archive_id}/reprint")
  1900. async def reprint_archive(
  1901. archive_id: int,
  1902. printer_id: int,
  1903. body: ReprintRequest | None = None,
  1904. db: AsyncSession = Depends(get_db),
  1905. ):
  1906. """Send an archived 3MF file to a printer and start printing."""
  1907. from backend.app.main import register_expected_print
  1908. from backend.app.models.printer import Printer
  1909. from backend.app.services.bambu_ftp import (
  1910. get_ftp_retry_settings,
  1911. upload_file_async,
  1912. with_ftp_retry,
  1913. )
  1914. from backend.app.services.printer_manager import printer_manager
  1915. # Use defaults if no body provided
  1916. if body is None:
  1917. body = ReprintRequest()
  1918. # Get archive
  1919. service = ArchiveService(db)
  1920. archive = await service.get_archive(archive_id)
  1921. if not archive:
  1922. raise HTTPException(404, "Archive not found")
  1923. # Get printer
  1924. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1925. printer = result.scalar_one_or_none()
  1926. if not printer:
  1927. raise HTTPException(404, "Printer not found")
  1928. # Check printer is connected
  1929. if not printer_manager.is_connected(printer_id):
  1930. raise HTTPException(400, "Printer is not connected")
  1931. # Get the sliced 3MF file path
  1932. file_path = settings.base_dir / archive.file_path
  1933. if not file_path.exists():
  1934. raise HTTPException(404, "Archive file not found")
  1935. # Upload file to printer via FTP
  1936. from backend.app.services.bambu_ftp import delete_file_async
  1937. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1938. # The printer might reject filenames with unusual extensions
  1939. base_name = archive.filename
  1940. if base_name.endswith(".gcode.3mf"):
  1941. base_name = base_name[:-10] # Remove .gcode.3mf
  1942. elif base_name.endswith(".3mf"):
  1943. base_name = base_name[:-4] # Remove .3mf
  1944. remote_filename = f"{base_name}.3mf"
  1945. remote_path = f"/{remote_filename}"
  1946. # Get FTP retry settings
  1947. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1948. # Delete existing file if present (avoids 553 error)
  1949. await delete_file_async(
  1950. printer.ip_address,
  1951. printer.access_code,
  1952. remote_path,
  1953. socket_timeout=ftp_timeout,
  1954. printer_model=printer.model,
  1955. )
  1956. if ftp_retry_enabled:
  1957. uploaded = await with_ftp_retry(
  1958. upload_file_async,
  1959. printer.ip_address,
  1960. printer.access_code,
  1961. file_path,
  1962. remote_path,
  1963. socket_timeout=ftp_timeout,
  1964. printer_model=printer.model,
  1965. max_retries=ftp_retry_count,
  1966. retry_delay=ftp_retry_delay,
  1967. operation_name=f"Upload for reprint to {printer.name}",
  1968. )
  1969. else:
  1970. uploaded = await upload_file_async(
  1971. printer.ip_address,
  1972. printer.access_code,
  1973. file_path,
  1974. remote_path,
  1975. socket_timeout=ftp_timeout,
  1976. printer_model=printer.model,
  1977. )
  1978. if not uploaded:
  1979. raise HTTPException(500, "Failed to upload file to printer")
  1980. # Register this as an expected print so we don't create a duplicate archive
  1981. register_expected_print(printer_id, remote_filename, archive_id)
  1982. # Use plate_id from request if provided, otherwise auto-detect from 3MF file
  1983. if body.plate_id is not None:
  1984. plate_id = body.plate_id
  1985. else:
  1986. # Auto-detect plate ID from 3MF file (legacy behavior for single-plate files)
  1987. plate_id = 1
  1988. try:
  1989. with zipfile.ZipFile(file_path, "r") as zf:
  1990. for name in zf.namelist():
  1991. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1992. # Extract plate number from "Metadata/plate_X.gcode"
  1993. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1994. plate_id = int(plate_str)
  1995. break
  1996. except Exception:
  1997. pass # Default to plate 1 if detection fails
  1998. logger.info(
  1999. f"Reprint archive {archive_id}: plate_id={plate_id}, "
  2000. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}, "
  2001. f"flow_cali={body.flow_cali}, vibration_cali={body.vibration_cali}, "
  2002. f"layer_inspect={body.layer_inspect}, timelapse={body.timelapse}"
  2003. )
  2004. # Start the print with options
  2005. started = printer_manager.start_print(
  2006. printer_id,
  2007. remote_filename,
  2008. plate_id,
  2009. ams_mapping=body.ams_mapping,
  2010. timelapse=body.timelapse,
  2011. bed_levelling=body.bed_levelling,
  2012. flow_cali=body.flow_cali,
  2013. vibration_cali=body.vibration_cali,
  2014. layer_inspect=body.layer_inspect,
  2015. use_ams=body.use_ams,
  2016. )
  2017. if not started:
  2018. raise HTTPException(500, "Failed to start print")
  2019. return {
  2020. "status": "printing",
  2021. "printer_id": printer_id,
  2022. "archive_id": archive_id,
  2023. "filename": archive.filename,
  2024. }
  2025. # =============================================================================
  2026. # Project Page API
  2027. # =============================================================================
  2028. @router.get("/{archive_id}/project-page")
  2029. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  2030. """Get the project page data from the 3MF file."""
  2031. from backend.app.schemas.archive import ProjectPageResponse
  2032. from backend.app.services.archive import ProjectPageParser
  2033. service = ArchiveService(db)
  2034. archive = await service.get_archive(archive_id)
  2035. if not archive:
  2036. raise HTTPException(404, "Archive not found")
  2037. file_path = settings.base_dir / archive.file_path
  2038. if not file_path.exists():
  2039. raise HTTPException(404, "Archive file not found")
  2040. parser = ProjectPageParser(file_path)
  2041. data = parser.parse(archive_id)
  2042. return ProjectPageResponse(**data)
  2043. @router.patch("/{archive_id}/project-page")
  2044. async def update_project_page(
  2045. archive_id: int,
  2046. update_data: dict,
  2047. db: AsyncSession = Depends(get_db),
  2048. ):
  2049. """Update project page metadata in the 3MF file."""
  2050. from backend.app.services.archive import ProjectPageParser
  2051. service = ArchiveService(db)
  2052. archive = await service.get_archive(archive_id)
  2053. if not archive:
  2054. raise HTTPException(404, "Archive not found")
  2055. file_path = settings.base_dir / archive.file_path
  2056. if not file_path.exists():
  2057. raise HTTPException(404, "Archive file not found")
  2058. parser = ProjectPageParser(file_path)
  2059. success = parser.update_metadata(update_data)
  2060. if not success:
  2061. raise HTTPException(500, "Failed to update project page")
  2062. # Return updated data
  2063. data = parser.parse(archive_id)
  2064. return data
  2065. @router.get("/{archive_id}/project-image/{image_path:path}")
  2066. async def get_project_image(
  2067. archive_id: int,
  2068. image_path: str,
  2069. db: AsyncSession = Depends(get_db),
  2070. ):
  2071. """Get an image from the 3MF project page."""
  2072. from backend.app.services.archive import ProjectPageParser
  2073. service = ArchiveService(db)
  2074. archive = await service.get_archive(archive_id)
  2075. if not archive:
  2076. raise HTTPException(404, "Archive not found")
  2077. file_path = settings.base_dir / archive.file_path
  2078. if not file_path.exists():
  2079. raise HTTPException(404, "Archive file not found")
  2080. parser = ProjectPageParser(file_path)
  2081. result = parser.get_image(image_path)
  2082. if not result:
  2083. raise HTTPException(404, "Image not found in 3MF file")
  2084. image_data, content_type = result
  2085. return Response(
  2086. content=image_data,
  2087. media_type=content_type,
  2088. headers={"Cache-Control": "max-age=3600"},
  2089. )
  2090. # =============================================================================
  2091. # Source 3MF API (Original Project Files)
  2092. # =============================================================================
  2093. @router.post("/{archive_id}/source")
  2094. async def upload_source_3mf(
  2095. archive_id: int,
  2096. file: UploadFile = File(...),
  2097. db: AsyncSession = Depends(get_db),
  2098. ):
  2099. """Upload the original source 3MF project file for an archive."""
  2100. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2101. archive = result.scalar_one_or_none()
  2102. if not archive:
  2103. raise HTTPException(404, "Archive not found")
  2104. if not file.filename or not file.filename.endswith(".3mf"):
  2105. raise HTTPException(400, "File must be a .3mf file")
  2106. # Get archive directory and create source subdirectory
  2107. file_path = settings.base_dir / archive.file_path
  2108. archive_dir = file_path.parent
  2109. source_dir = archive_dir / "source"
  2110. source_dir.mkdir(exist_ok=True)
  2111. # Delete old source file if exists
  2112. if archive.source_3mf_path:
  2113. old_source_path = settings.base_dir / archive.source_3mf_path
  2114. if old_source_path.exists():
  2115. old_source_path.unlink()
  2116. # Save the source 3MF file - preserve original filename
  2117. source_filename = file.filename
  2118. source_path = source_dir / source_filename
  2119. content = await file.read()
  2120. source_path.write_bytes(content)
  2121. # Update archive with source path (relative to base_dir)
  2122. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2123. await db.commit()
  2124. await db.refresh(archive)
  2125. return {
  2126. "status": "uploaded",
  2127. "source_3mf_path": archive.source_3mf_path,
  2128. "filename": source_filename,
  2129. }
  2130. @router.get("/{archive_id}/source")
  2131. async def download_source_3mf(
  2132. archive_id: int,
  2133. db: AsyncSession = Depends(get_db),
  2134. ):
  2135. """Download the source 3MF project file."""
  2136. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2137. archive = result.scalar_one_or_none()
  2138. if not archive:
  2139. raise HTTPException(404, "Archive not found")
  2140. if not archive.source_3mf_path:
  2141. raise HTTPException(404, "No source 3MF attached to this archive")
  2142. source_path = settings.base_dir / archive.source_3mf_path
  2143. if not source_path.exists():
  2144. raise HTTPException(404, "Source 3MF file not found on disk")
  2145. # Use the actual filename from the path
  2146. filename = source_path.name
  2147. return FileResponse(
  2148. path=source_path,
  2149. filename=filename,
  2150. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2151. )
  2152. @router.get("/{archive_id}/source/{filename}")
  2153. async def download_source_3mf_for_slicer(
  2154. archive_id: int,
  2155. filename: str,
  2156. db: AsyncSession = Depends(get_db),
  2157. ):
  2158. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  2159. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2160. archive = result.scalar_one_or_none()
  2161. if not archive:
  2162. raise HTTPException(404, "Archive not found")
  2163. if not archive.source_3mf_path:
  2164. raise HTTPException(404, "No source 3MF attached to this archive")
  2165. source_path = settings.base_dir / archive.source_3mf_path
  2166. if not source_path.exists():
  2167. raise HTTPException(404, "Source 3MF file not found on disk")
  2168. return FileResponse(
  2169. path=source_path,
  2170. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  2171. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2172. )
  2173. @router.post("/upload-source")
  2174. async def upload_source_3mf_by_name(
  2175. file: UploadFile = File(...),
  2176. print_name: str = Query(None, description="Match archive by print name"),
  2177. db: AsyncSession = Depends(get_db),
  2178. ):
  2179. """Upload source 3MF and match to archive by print name.
  2180. This endpoint is designed for slicer post-processing scripts.
  2181. It finds the most recent archive matching the print name and attaches the source.
  2182. """
  2183. if not file.filename or not file.filename.endswith(".3mf"):
  2184. raise HTTPException(400, "File must be a .3mf file")
  2185. # Derive print name from filename if not provided
  2186. if not print_name:
  2187. # Remove .3mf extension and common suffixes
  2188. print_name = file.filename.rsplit(".3mf", 1)[0]
  2189. # Remove _source suffix if present
  2190. if print_name.endswith("_source"):
  2191. print_name = print_name[:-7]
  2192. # Find matching archive - try exact match first, then fuzzy
  2193. result = await db.execute(
  2194. select(PrintArchive)
  2195. .where(PrintArchive.print_name == print_name)
  2196. .order_by(PrintArchive.created_at.desc())
  2197. .limit(1)
  2198. )
  2199. archive = result.scalar_one_or_none()
  2200. if not archive:
  2201. # Try matching filename without .gcode.3mf
  2202. result = await db.execute(
  2203. select(PrintArchive)
  2204. .where(PrintArchive.filename.like(f"{print_name}%"))
  2205. .order_by(PrintArchive.created_at.desc())
  2206. .limit(1)
  2207. )
  2208. archive = result.scalar_one_or_none()
  2209. if not archive:
  2210. # Try case-insensitive partial match on print_name
  2211. result = await db.execute(
  2212. select(PrintArchive)
  2213. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  2214. .order_by(PrintArchive.created_at.desc())
  2215. .limit(1)
  2216. )
  2217. archive = result.scalar_one_or_none()
  2218. if not archive:
  2219. raise HTTPException(404, f"No archive found matching '{print_name}'")
  2220. # Get archive directory and create source subdirectory
  2221. file_path = settings.base_dir / archive.file_path
  2222. archive_dir = file_path.parent
  2223. source_dir = archive_dir / "source"
  2224. source_dir.mkdir(exist_ok=True)
  2225. # Delete old source file if exists
  2226. if archive.source_3mf_path:
  2227. old_source_path = settings.base_dir / archive.source_3mf_path
  2228. if old_source_path.exists():
  2229. old_source_path.unlink()
  2230. # Save the source 3MF file - preserve original filename
  2231. source_filename = file.filename
  2232. source_path = source_dir / source_filename
  2233. content = await file.read()
  2234. source_path.write_bytes(content)
  2235. # Update archive with source path
  2236. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2237. await db.commit()
  2238. await db.refresh(archive)
  2239. return {
  2240. "status": "uploaded",
  2241. "archive_id": archive.id,
  2242. "archive_name": archive.print_name or archive.filename,
  2243. "source_3mf_path": archive.source_3mf_path,
  2244. "filename": source_filename,
  2245. }
  2246. @router.delete("/{archive_id}/source")
  2247. async def delete_source_3mf(
  2248. archive_id: int,
  2249. db: AsyncSession = Depends(get_db),
  2250. ):
  2251. """Delete the source 3MF project file from an archive."""
  2252. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2253. archive = result.scalar_one_or_none()
  2254. if not archive:
  2255. raise HTTPException(404, "Archive not found")
  2256. if not archive.source_3mf_path:
  2257. raise HTTPException(404, "No source 3MF attached to this archive")
  2258. # Delete the file
  2259. source_path = settings.base_dir / archive.source_3mf_path
  2260. if source_path.exists():
  2261. source_path.unlink()
  2262. # Clear the path in database
  2263. archive.source_3mf_path = None
  2264. await db.commit()
  2265. return {"status": "deleted"}
  2266. # =============================================================================
  2267. # F3D API (Fusion 360 Design Files)
  2268. # =============================================================================
  2269. @router.post("/{archive_id}/f3d")
  2270. async def upload_f3d(
  2271. archive_id: int,
  2272. file: UploadFile = File(...),
  2273. db: AsyncSession = Depends(get_db),
  2274. ):
  2275. """Upload a Fusion 360 design file for an archive."""
  2276. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2277. archive = result.scalar_one_or_none()
  2278. if not archive:
  2279. raise HTTPException(404, "Archive not found")
  2280. if not file.filename or not file.filename.endswith(".f3d"):
  2281. raise HTTPException(400, "File must be a .f3d file")
  2282. # Get archive directory and create f3d subdirectory
  2283. file_path = settings.base_dir / archive.file_path
  2284. archive_dir = file_path.parent
  2285. f3d_dir = archive_dir / "f3d"
  2286. f3d_dir.mkdir(exist_ok=True)
  2287. # Delete old F3D file if exists
  2288. if archive.f3d_path:
  2289. old_f3d_path = settings.base_dir / archive.f3d_path
  2290. if old_f3d_path.exists():
  2291. old_f3d_path.unlink()
  2292. # Save the F3D file - preserve original filename
  2293. f3d_filename = file.filename
  2294. f3d_path = f3d_dir / f3d_filename
  2295. content = await file.read()
  2296. f3d_path.write_bytes(content)
  2297. # Update archive with F3D path (relative to base_dir)
  2298. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  2299. await db.commit()
  2300. await db.refresh(archive)
  2301. return {
  2302. "status": "uploaded",
  2303. "f3d_path": archive.f3d_path,
  2304. "filename": f3d_filename,
  2305. }
  2306. @router.get("/{archive_id}/f3d")
  2307. async def download_f3d(
  2308. archive_id: int,
  2309. db: AsyncSession = Depends(get_db),
  2310. ):
  2311. """Download the Fusion 360 design file."""
  2312. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2313. archive = result.scalar_one_or_none()
  2314. if not archive:
  2315. raise HTTPException(404, "Archive not found")
  2316. if not archive.f3d_path:
  2317. raise HTTPException(404, "No F3D file attached to this archive")
  2318. f3d_path = settings.base_dir / archive.f3d_path
  2319. if not f3d_path.exists():
  2320. raise HTTPException(404, "F3D file not found on disk")
  2321. # Use the actual filename from the path
  2322. filename = f3d_path.name
  2323. return FileResponse(
  2324. path=f3d_path,
  2325. filename=filename,
  2326. media_type="application/octet-stream",
  2327. )
  2328. @router.delete("/{archive_id}/f3d")
  2329. async def delete_f3d(
  2330. archive_id: int,
  2331. db: AsyncSession = Depends(get_db),
  2332. ):
  2333. """Delete the Fusion 360 design file from an archive."""
  2334. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2335. archive = result.scalar_one_or_none()
  2336. if not archive:
  2337. raise HTTPException(404, "Archive not found")
  2338. if not archive.f3d_path:
  2339. raise HTTPException(404, "No F3D file attached to this archive")
  2340. # Delete the file
  2341. f3d_path = settings.base_dir / archive.f3d_path
  2342. if f3d_path.exists():
  2343. f3d_path.unlink()
  2344. # Clear the path in database
  2345. archive.f3d_path = None
  2346. await db.commit()
  2347. return {"status": "deleted"}