archives.py 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850
  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.api.routes.settings import get_setting
  521. from backend.app.services.archive import ThreeMFParser
  522. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  523. archive = result.scalar_one_or_none()
  524. if not archive:
  525. raise HTTPException(404, "Archive not found")
  526. file_path = settings.base_dir / archive.file_path
  527. if not file_path.exists():
  528. raise HTTPException(404, "Archive file not found")
  529. # Parse the 3MF file
  530. parser = ThreeMFParser(file_path)
  531. metadata = parser.parse()
  532. # Update fields from metadata
  533. if metadata.get("filament_type"):
  534. archive.filament_type = metadata["filament_type"]
  535. if metadata.get("filament_color"):
  536. archive.filament_color = metadata["filament_color"]
  537. if metadata.get("print_time_seconds"):
  538. archive.print_time_seconds = metadata["print_time_seconds"]
  539. if metadata.get("filament_used_grams"):
  540. archive.filament_used_grams = metadata["filament_used_grams"]
  541. if metadata.get("layer_height"):
  542. archive.layer_height = metadata["layer_height"]
  543. if metadata.get("nozzle_diameter"):
  544. archive.nozzle_diameter = metadata["nozzle_diameter"]
  545. if metadata.get("bed_temperature"):
  546. archive.bed_temperature = metadata["bed_temperature"]
  547. if metadata.get("nozzle_temperature"):
  548. archive.nozzle_temperature = metadata["nozzle_temperature"]
  549. if metadata.get("makerworld_url"):
  550. archive.makerworld_url = metadata["makerworld_url"]
  551. if metadata.get("designer"):
  552. archive.designer = metadata["designer"]
  553. # Calculate cost based on filament usage and type
  554. if archive.filament_used_grams and archive.filament_type:
  555. primary_type = archive.filament_type.split(",")[0].strip()
  556. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  557. filament = filament_result.scalar_one_or_none()
  558. if filament:
  559. archive.cost = round((archive.filament_used_grams / 1000) * filament.cost_per_kg, 2)
  560. else:
  561. # Use default filament cost from settings
  562. default_cost_setting = await get_setting(db, "default_filament_cost")
  563. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  564. archive.cost = round((archive.filament_used_grams / 1000) * default_cost_per_kg, 2)
  565. await db.commit()
  566. await db.refresh(archive)
  567. return archive
  568. @router.post("/recalculate-costs")
  569. async def recalculate_all_costs(db: AsyncSession = Depends(get_db)):
  570. """Recalculate costs for all archives based on filament usage and prices."""
  571. from backend.app.api.routes.settings import get_setting
  572. result = await db.execute(select(PrintArchive))
  573. archives = list(result.scalars().all())
  574. # Load all filaments for lookup
  575. filament_result = await db.execute(select(Filament))
  576. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  577. # Get default filament cost from settings
  578. default_cost_setting = await get_setting(db, "default_filament_cost")
  579. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  580. updated = 0
  581. for archive in archives:
  582. if archive.filament_used_grams and archive.filament_type:
  583. primary_type = archive.filament_type.split(",")[0].strip()
  584. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  585. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  586. if archive.cost != new_cost:
  587. archive.cost = new_cost
  588. updated += 1
  589. await db.commit()
  590. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  591. @router.post("/rescan-all")
  592. async def rescan_all_archives(db: AsyncSession = Depends(get_db)):
  593. """Rescan all archives and update their metadata."""
  594. from backend.app.services.archive import ThreeMFParser
  595. result = await db.execute(select(PrintArchive))
  596. archives = list(result.scalars().all())
  597. updated = 0
  598. errors = []
  599. for archive in archives:
  600. try:
  601. file_path = settings.base_dir / archive.file_path
  602. if not file_path.exists():
  603. errors.append({"id": archive.id, "error": "File not found"})
  604. continue
  605. parser = ThreeMFParser(file_path)
  606. metadata = parser.parse()
  607. if metadata.get("filament_type"):
  608. archive.filament_type = metadata["filament_type"]
  609. if metadata.get("filament_color"):
  610. archive.filament_color = metadata["filament_color"]
  611. if metadata.get("print_time_seconds"):
  612. archive.print_time_seconds = metadata["print_time_seconds"]
  613. if metadata.get("filament_used_grams"):
  614. archive.filament_used_grams = metadata["filament_used_grams"]
  615. if metadata.get("layer_height"):
  616. archive.layer_height = metadata["layer_height"]
  617. if metadata.get("nozzle_diameter"):
  618. archive.nozzle_diameter = metadata["nozzle_diameter"]
  619. if metadata.get("makerworld_url"):
  620. archive.makerworld_url = metadata["makerworld_url"]
  621. if metadata.get("designer"):
  622. archive.designer = metadata["designer"]
  623. updated += 1
  624. except Exception as e:
  625. errors.append({"id": archive.id, "error": str(e)})
  626. await db.commit()
  627. return {"updated": updated, "errors": errors}
  628. @router.get("/{archive_id}/duplicates")
  629. async def get_archive_duplicates(archive_id: int, db: AsyncSession = Depends(get_db)):
  630. """Get duplicates for a specific archive."""
  631. service = ArchiveService(db)
  632. archive = await service.get_archive(archive_id)
  633. if not archive:
  634. raise HTTPException(404, "Archive not found")
  635. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  636. duplicates = await service.find_duplicates(
  637. archive_id=archive.id,
  638. content_hash=archive.content_hash,
  639. print_name=archive.print_name,
  640. makerworld_model_id=makerworld_id,
  641. )
  642. return {"duplicates": duplicates, "count": len(duplicates)}
  643. @router.post("/backfill-hashes")
  644. async def backfill_content_hashes(db: AsyncSession = Depends(get_db)):
  645. """Compute and store content hashes for all archives missing them."""
  646. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  647. archives = list(result.scalars().all())
  648. updated = 0
  649. errors = []
  650. for archive in archives:
  651. try:
  652. file_path = settings.base_dir / archive.file_path
  653. if not file_path.exists():
  654. errors.append({"id": archive.id, "error": "File not found"})
  655. continue
  656. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  657. updated += 1
  658. except Exception as e:
  659. errors.append({"id": archive.id, "error": str(e)})
  660. await db.commit()
  661. return {"updated": updated, "errors": errors}
  662. @router.delete("/{archive_id}")
  663. async def delete_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  664. """Delete an archive."""
  665. service = ArchiveService(db)
  666. if not await service.delete_archive(archive_id):
  667. raise HTTPException(404, "Archive not found")
  668. return {"status": "deleted"}
  669. @router.get("/{archive_id}/download")
  670. async def download_archive(
  671. archive_id: int,
  672. inline: bool = False,
  673. db: AsyncSession = Depends(get_db),
  674. ):
  675. """Download the 3MF file."""
  676. service = ArchiveService(db)
  677. archive = await service.get_archive(archive_id)
  678. if not archive:
  679. raise HTTPException(404, "Archive not found")
  680. file_path = settings.base_dir / archive.file_path
  681. if not file_path.exists():
  682. raise HTTPException(404, "File not found")
  683. # Use inline disposition to let browser/OS handle file association
  684. content_disposition = "inline" if inline else "attachment"
  685. return FileResponse(
  686. path=file_path,
  687. filename=archive.filename,
  688. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  689. content_disposition_type=content_disposition,
  690. )
  691. @router.get("/{archive_id}/file/{filename}")
  692. async def download_archive_with_filename(
  693. archive_id: int,
  694. filename: str,
  695. db: AsyncSession = Depends(get_db),
  696. ):
  697. """Download the 3MF file with filename in URL (for Bambu Studio protocol)."""
  698. service = ArchiveService(db)
  699. archive = await service.get_archive(archive_id)
  700. if not archive:
  701. raise HTTPException(404, "Archive not found")
  702. file_path = settings.base_dir / archive.file_path
  703. if not file_path.exists():
  704. raise HTTPException(404, "File not found")
  705. return FileResponse(
  706. path=file_path,
  707. filename=archive.filename,
  708. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  709. )
  710. @router.get("/{archive_id}/thumbnail")
  711. async def get_thumbnail(archive_id: int, db: AsyncSession = Depends(get_db)):
  712. """Get the thumbnail image."""
  713. service = ArchiveService(db)
  714. archive = await service.get_archive(archive_id)
  715. if not archive or not archive.thumbnail_path:
  716. raise HTTPException(404, "Thumbnail not found")
  717. thumb_path = settings.base_dir / archive.thumbnail_path
  718. if not thumb_path.exists():
  719. raise HTTPException(404, "Thumbnail file not found")
  720. # Use file modification time as ETag to bust cache
  721. mtime = int(thumb_path.stat().st_mtime)
  722. return FileResponse(
  723. path=thumb_path,
  724. media_type="image/png",
  725. headers={
  726. "Cache-Control": "no-cache, must-revalidate",
  727. "ETag": f'"{mtime}"',
  728. },
  729. )
  730. @router.get("/{archive_id}/timelapse")
  731. async def get_timelapse(archive_id: int, db: AsyncSession = Depends(get_db)):
  732. """Get the timelapse video."""
  733. service = ArchiveService(db)
  734. archive = await service.get_archive(archive_id)
  735. if not archive or not archive.timelapse_path:
  736. raise HTTPException(404, "Timelapse not found")
  737. timelapse_path = settings.base_dir / archive.timelapse_path
  738. if not timelapse_path.exists():
  739. raise HTTPException(404, "Timelapse file not found")
  740. # Use file modification time as ETag to bust cache after processing
  741. mtime = int(timelapse_path.stat().st_mtime)
  742. return FileResponse(
  743. path=timelapse_path,
  744. media_type="video/mp4",
  745. filename=f"{archive.print_name or 'timelapse'}.mp4",
  746. headers={
  747. "Cache-Control": "no-cache, must-revalidate",
  748. "ETag": f'"{mtime}"',
  749. },
  750. )
  751. @router.post("/{archive_id}/timelapse/scan")
  752. async def scan_timelapse(
  753. archive_id: int,
  754. db: AsyncSession = Depends(get_db),
  755. ):
  756. """Scan printer for timelapse matching this archive and attach it."""
  757. from backend.app.models.printer import Printer
  758. from backend.app.services.bambu_ftp import (
  759. download_file_bytes_async,
  760. get_ftp_retry_settings,
  761. list_files_async,
  762. with_ftp_retry,
  763. )
  764. service = ArchiveService(db)
  765. archive = await service.get_archive(archive_id)
  766. if not archive:
  767. raise HTTPException(404, "Archive not found")
  768. if archive.timelapse_path:
  769. return {"status": "exists", "message": "Timelapse already attached"}
  770. if not archive.printer_id:
  771. raise HTTPException(400, "Archive has no associated printer")
  772. # Get printer
  773. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  774. printer = result.scalar_one_or_none()
  775. if not printer:
  776. raise HTTPException(404, "Printer not found")
  777. # Get base name from archive filename (without .3mf extension)
  778. base_name = Path(archive.filename).stem
  779. # Scan timelapse directory on printer
  780. # Try both /timelapse and /timelapse/video (different printer models use different paths)
  781. files = []
  782. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  783. try:
  784. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  785. if files:
  786. break
  787. except Exception:
  788. continue
  789. if not files:
  790. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  791. # Look for matching timelapse
  792. matching_file = None
  793. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  794. # Strategy 1: Match by print name in filename
  795. for f in mp4_files:
  796. fname = f.get("name", "")
  797. if base_name.lower() in fname.lower():
  798. matching_file = f
  799. break
  800. # Strategy 2: Match by timestamp proximity
  801. # Bambu timelapse filename uses the print START time (when recording began)
  802. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  803. import re
  804. from datetime import datetime, timedelta
  805. # Prefer started_at since video filename is the print start time
  806. # Fall back to completed_at or created_at if started_at is not available
  807. archive_start = archive.started_at
  808. archive_end = archive.completed_at or archive.created_at
  809. best_match = None
  810. best_diff = timedelta(hours=24) # Max 24 hour difference
  811. for f in mp4_files:
  812. fname = f.get("name", "")
  813. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  814. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  815. if match:
  816. try:
  817. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  818. # Try multiple timezone offsets since printer timezone can vary
  819. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  820. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  821. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  822. # Check against start time (video filename = print start)
  823. if archive_start:
  824. diff = abs(adjusted_file_time - archive_start)
  825. if diff < best_diff:
  826. best_diff = diff
  827. best_match = f
  828. logger.debug(
  829. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  830. f"diff from start: {diff}"
  831. )
  832. # Also check against end time with a buffer
  833. # (video timestamp should be BEFORE completion time)
  834. if archive_end:
  835. # The video timestamp should be within the print duration before completion
  836. if adjusted_file_time < archive_end:
  837. diff = archive_end - adjusted_file_time
  838. # Reasonable print duration: up to 48 hours
  839. if diff < timedelta(hours=48) and diff < best_diff:
  840. best_diff = diff
  841. best_match = f
  842. logger.debug(
  843. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  844. f"diff: {diff}"
  845. )
  846. except ValueError:
  847. continue
  848. # Accept match within 4 hours (more lenient for timezone issues)
  849. if best_match and best_diff < timedelta(hours=4):
  850. matching_file = best_match
  851. logger.info(f"Matched timelapse by timestamp: {best_match.get('name')} (diff: {best_diff})")
  852. # Strategy 3: Use file modification time from FTP listing
  853. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  854. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  855. from datetime import datetime, timedelta
  856. archive_start = archive.started_at
  857. archive_end = archive.completed_at or archive.created_at
  858. best_match = None
  859. best_diff = timedelta(hours=24)
  860. for f in mp4_files:
  861. mtime = f.get("mtime")
  862. if mtime:
  863. # Timelapse file should be modified during or shortly after the print
  864. # The mtime should be close to completion time (video finishes when print ends)
  865. if archive_end:
  866. diff = abs(mtime - archive_end)
  867. if diff < best_diff:
  868. best_diff = diff
  869. best_match = f
  870. logger.debug(
  871. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  872. )
  873. if best_match and best_diff < timedelta(hours=2):
  874. matching_file = best_match
  875. logger.info(f"Matched timelapse by file mtime: {best_match.get('name')} (diff: {best_diff})")
  876. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  877. # This handles cases where printer clock is wrong or timezone issues exist
  878. if not matching_file and len(mp4_files) == 1:
  879. from datetime import datetime, timedelta
  880. archive_completed = archive.completed_at or archive.created_at
  881. if archive_completed:
  882. time_since_completion = datetime.now() - archive_completed
  883. # If archive was completed within the last hour, assume the single timelapse is for it
  884. if time_since_completion < timedelta(hours=1):
  885. matching_file = mp4_files[0]
  886. logger.info(f"Using single timelapse file as fallback: {mp4_files[0].get('name')}")
  887. # Note: We intentionally don't use a "most recent file" fallback because
  888. # we can't verify if timelapse was actually enabled for this print.
  889. # Instead, return the list of available files for manual selection.
  890. if not matching_file:
  891. # Return available files for manual selection
  892. available_files = [
  893. {
  894. "name": f.get("name"),
  895. "path": f.get("path"),
  896. "size": f.get("size"),
  897. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  898. }
  899. for f in mp4_files
  900. ]
  901. # Sort by mtime descending (most recent first)
  902. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  903. return {
  904. "status": "not_found",
  905. "message": "No matching timelapse found - please select manually",
  906. "available_files": available_files,
  907. }
  908. # Download the timelapse - use the full path from the file listing
  909. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  910. # Get FTP retry settings
  911. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  912. if ftp_retry_enabled:
  913. timelapse_data = await with_ftp_retry(
  914. download_file_bytes_async,
  915. printer.ip_address,
  916. printer.access_code,
  917. remote_path,
  918. socket_timeout=ftp_timeout,
  919. printer_model=printer.model,
  920. max_retries=ftp_retry_count,
  921. retry_delay=ftp_retry_delay,
  922. operation_name=f"Download timelapse {matching_file['name']}",
  923. )
  924. else:
  925. timelapse_data = await download_file_bytes_async(
  926. printer.ip_address,
  927. printer.access_code,
  928. remote_path,
  929. socket_timeout=ftp_timeout,
  930. printer_model=printer.model,
  931. )
  932. if not timelapse_data:
  933. raise HTTPException(500, "Failed to download timelapse")
  934. # Attach timelapse to archive
  935. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  936. if not success:
  937. raise HTTPException(500, "Failed to attach timelapse")
  938. return {
  939. "status": "attached",
  940. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  941. "filename": matching_file["name"],
  942. }
  943. @router.post("/{archive_id}/timelapse/select")
  944. async def select_timelapse(
  945. archive_id: int,
  946. filename: str = Query(..., description="Timelapse filename to attach"),
  947. db: AsyncSession = Depends(get_db),
  948. ):
  949. """Manually select a timelapse from the printer to attach."""
  950. from backend.app.models.printer import Printer
  951. from backend.app.services.bambu_ftp import (
  952. download_file_bytes_async,
  953. get_ftp_retry_settings,
  954. list_files_async,
  955. with_ftp_retry,
  956. )
  957. service = ArchiveService(db)
  958. archive = await service.get_archive(archive_id)
  959. if not archive:
  960. raise HTTPException(404, "Archive not found")
  961. if not archive.printer_id:
  962. raise HTTPException(400, "Archive has no associated printer")
  963. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  964. printer = result.scalar_one_or_none()
  965. if not printer:
  966. raise HTTPException(404, "Printer not found")
  967. # Find the file on the printer
  968. files = []
  969. remote_path = None
  970. for timelapse_dir in ["/timelapse", "/timelapse/video"]:
  971. try:
  972. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_dir)
  973. for f in files:
  974. if f.get("name") == filename:
  975. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  976. break
  977. if remote_path:
  978. break
  979. except Exception:
  980. continue
  981. if not remote_path:
  982. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  983. # Download and attach
  984. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  985. if ftp_retry_enabled:
  986. timelapse_data = await with_ftp_retry(
  987. download_file_bytes_async,
  988. printer.ip_address,
  989. printer.access_code,
  990. remote_path,
  991. socket_timeout=ftp_timeout,
  992. printer_model=printer.model,
  993. max_retries=ftp_retry_count,
  994. retry_delay=ftp_retry_delay,
  995. operation_name=f"Download timelapse {filename}",
  996. )
  997. else:
  998. timelapse_data = await download_file_bytes_async(
  999. printer.ip_address,
  1000. printer.access_code,
  1001. remote_path,
  1002. socket_timeout=ftp_timeout,
  1003. printer_model=printer.model,
  1004. )
  1005. if not timelapse_data:
  1006. raise HTTPException(500, "Failed to download timelapse")
  1007. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  1008. if not success:
  1009. raise HTTPException(500, "Failed to attach timelapse")
  1010. return {
  1011. "status": "attached",
  1012. "message": f"Timelapse '{filename}' attached successfully",
  1013. "filename": filename,
  1014. }
  1015. @router.post("/{archive_id}/timelapse/upload")
  1016. async def upload_timelapse(
  1017. archive_id: int,
  1018. file: UploadFile = File(...),
  1019. db: AsyncSession = Depends(get_db),
  1020. ):
  1021. """Manually upload a timelapse video to an archive."""
  1022. service = ArchiveService(db)
  1023. archive = await service.get_archive(archive_id)
  1024. if not archive:
  1025. raise HTTPException(404, "Archive not found")
  1026. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  1027. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  1028. content = await file.read()
  1029. success = await service.attach_timelapse(archive_id, content, file.filename)
  1030. if not success:
  1031. raise HTTPException(500, "Failed to attach timelapse")
  1032. return {"status": "attached", "filename": file.filename}
  1033. @router.get("/{archive_id}/timelapse/info")
  1034. async def get_timelapse_info(archive_id: int, db: AsyncSession = Depends(get_db)):
  1035. """Get timelapse video metadata for editor."""
  1036. from backend.app.schemas.timelapse import TimelapseInfoResponse
  1037. from backend.app.services.timelapse_processor import TimelapseProcessor
  1038. service = ArchiveService(db)
  1039. archive = await service.get_archive(archive_id)
  1040. if not archive or not archive.timelapse_path:
  1041. raise HTTPException(404, "Timelapse not found")
  1042. timelapse_path = settings.base_dir / archive.timelapse_path
  1043. if not timelapse_path.exists():
  1044. raise HTTPException(404, "Timelapse file not found")
  1045. try:
  1046. processor = TimelapseProcessor(timelapse_path)
  1047. info = await processor.get_info()
  1048. return TimelapseInfoResponse(**info)
  1049. except Exception as e:
  1050. logger.error(f"Failed to get timelapse info: {e}")
  1051. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  1052. @router.get("/{archive_id}/timelapse/thumbnails")
  1053. async def get_timelapse_thumbnails(
  1054. archive_id: int,
  1055. count: int = Query(10, ge=1, le=30),
  1056. width: int = Query(160, ge=80, le=320),
  1057. db: AsyncSession = Depends(get_db),
  1058. ):
  1059. """Generate timeline thumbnail frames for visual scrubbing."""
  1060. import base64
  1061. from backend.app.schemas.timelapse import ThumbnailResponse
  1062. from backend.app.services.timelapse_processor import TimelapseProcessor
  1063. service = ArchiveService(db)
  1064. archive = await service.get_archive(archive_id)
  1065. if not archive or not archive.timelapse_path:
  1066. raise HTTPException(404, "Timelapse not found")
  1067. timelapse_path = settings.base_dir / archive.timelapse_path
  1068. if not timelapse_path.exists():
  1069. raise HTTPException(404, "Timelapse file not found")
  1070. try:
  1071. processor = TimelapseProcessor(timelapse_path)
  1072. thumbnails = await processor.generate_thumbnails(count, width)
  1073. return ThumbnailResponse(
  1074. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1075. timestamps=[ts for ts, _ in thumbnails],
  1076. )
  1077. except Exception as e:
  1078. logger.error(f"Failed to generate thumbnails: {e}")
  1079. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1080. @router.post("/{archive_id}/timelapse/process")
  1081. async def process_timelapse(
  1082. archive_id: int,
  1083. trim_start: float = Form(0),
  1084. trim_end: float = Form(None),
  1085. speed: float = Form(1.0),
  1086. save_mode: str = Form("new"),
  1087. output_filename: str = Form(None),
  1088. audio: UploadFile = File(None),
  1089. db: AsyncSession = Depends(get_db),
  1090. ):
  1091. """Process timelapse with trim, speed, and optional audio overlay."""
  1092. import shutil
  1093. import tempfile
  1094. from backend.app.schemas.timelapse import ProcessResponse
  1095. from backend.app.services.timelapse_processor import TimelapseProcessor
  1096. # Validate speed
  1097. if not 0.25 <= speed <= 4.0:
  1098. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1099. if save_mode not in ("replace", "new"):
  1100. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1101. service = ArchiveService(db)
  1102. archive = await service.get_archive(archive_id)
  1103. if not archive or not archive.timelapse_path:
  1104. raise HTTPException(404, "Timelapse not found")
  1105. timelapse_path = settings.base_dir / archive.timelapse_path
  1106. if not timelapse_path.exists():
  1107. raise HTTPException(404, "Timelapse file not found")
  1108. archive_dir = timelapse_path.parent
  1109. # Handle audio file
  1110. audio_temp_path = None
  1111. if audio and audio.filename:
  1112. # Validate audio file extension
  1113. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  1114. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  1115. audio_content = await audio.read()
  1116. suffix = Path(audio.filename).suffix
  1117. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  1118. audio_temp_path.write_bytes(audio_content)
  1119. try:
  1120. processor = TimelapseProcessor(timelapse_path)
  1121. # Determine output path
  1122. if save_mode == "replace":
  1123. # Process to temp file first, then replace
  1124. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  1125. output_path = temp_output
  1126. else:
  1127. # Save as new file alongside original
  1128. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  1129. # Sanitize filename
  1130. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  1131. if not filename.endswith(".mp4"):
  1132. filename += ".mp4"
  1133. output_path = archive_dir / filename
  1134. success = await processor.process(
  1135. output_path=output_path,
  1136. trim_start=trim_start,
  1137. trim_end=trim_end,
  1138. speed=speed,
  1139. audio_path=audio_temp_path,
  1140. )
  1141. if not success:
  1142. raise HTTPException(500, "Video processing failed")
  1143. # Handle save mode
  1144. if save_mode == "replace":
  1145. # Replace original file
  1146. shutil.move(str(output_path), str(timelapse_path))
  1147. final_path = archive.timelapse_path
  1148. message = "Timelapse replaced successfully"
  1149. else:
  1150. final_path = str(output_path.relative_to(settings.base_dir))
  1151. message = f"Saved as {output_path.name}"
  1152. return ProcessResponse(
  1153. status="completed",
  1154. output_path=final_path,
  1155. message=message,
  1156. )
  1157. except HTTPException:
  1158. raise
  1159. except Exception as e:
  1160. logger.error(f"Timelapse processing failed: {e}")
  1161. raise HTTPException(500, f"Processing failed: {str(e)}")
  1162. finally:
  1163. # Cleanup temp audio file
  1164. if audio_temp_path and audio_temp_path.exists():
  1165. audio_temp_path.unlink()
  1166. # ============================================
  1167. # Photo Endpoints
  1168. # ============================================
  1169. @router.post("/{archive_id}/photos")
  1170. async def upload_photo(
  1171. archive_id: int,
  1172. file: UploadFile = File(...),
  1173. db: AsyncSession = Depends(get_db),
  1174. ):
  1175. """Upload a photo of the printed result."""
  1176. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1177. archive = result.scalar_one_or_none()
  1178. if not archive:
  1179. raise HTTPException(404, "Archive not found")
  1180. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  1181. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  1182. # Get archive directory
  1183. file_path = settings.base_dir / archive.file_path
  1184. archive_dir = file_path.parent
  1185. photos_dir = archive_dir / "photos"
  1186. photos_dir.mkdir(exist_ok=True)
  1187. # Generate unique filename
  1188. import uuid
  1189. ext = Path(file.filename).suffix.lower()
  1190. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  1191. photo_path = photos_dir / photo_filename
  1192. # Save file
  1193. content = await file.read()
  1194. photo_path.write_bytes(content)
  1195. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  1196. photos = list(archive.photos or [])
  1197. photos.append(photo_filename)
  1198. archive.photos = photos
  1199. await db.commit()
  1200. await db.refresh(archive)
  1201. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  1202. @router.get("/{archive_id}/photos/{filename}")
  1203. async def get_photo(
  1204. archive_id: int,
  1205. filename: str,
  1206. db: AsyncSession = Depends(get_db),
  1207. ):
  1208. """Get a specific photo."""
  1209. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1210. archive = result.scalar_one_or_none()
  1211. if not archive:
  1212. raise HTTPException(404, "Archive not found")
  1213. file_path = settings.base_dir / archive.file_path
  1214. photo_path = file_path.parent / "photos" / filename
  1215. if not photo_path.exists():
  1216. raise HTTPException(404, "Photo not found")
  1217. # Determine media type
  1218. ext = Path(filename).suffix.lower()
  1219. media_types = {
  1220. ".jpg": "image/jpeg",
  1221. ".jpeg": "image/jpeg",
  1222. ".png": "image/png",
  1223. ".webp": "image/webp",
  1224. }
  1225. media_type = media_types.get(ext, "image/jpeg")
  1226. return FileResponse(path=photo_path, media_type=media_type)
  1227. @router.delete("/{archive_id}/photos/{filename}")
  1228. async def delete_photo(
  1229. archive_id: int,
  1230. filename: str,
  1231. db: AsyncSession = Depends(get_db),
  1232. ):
  1233. """Delete a photo."""
  1234. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1235. archive = result.scalar_one_or_none()
  1236. if not archive:
  1237. raise HTTPException(404, "Archive not found")
  1238. if not archive.photos or filename not in archive.photos:
  1239. raise HTTPException(404, "Photo not found")
  1240. # Delete file
  1241. file_path = settings.base_dir / archive.file_path
  1242. photo_path = file_path.parent / "photos" / filename
  1243. if photo_path.exists():
  1244. photo_path.unlink()
  1245. # Update archive photos list
  1246. photos = [p for p in archive.photos if p != filename]
  1247. archive.photos = photos if photos else None
  1248. await db.commit()
  1249. return {"status": "deleted", "photos": archive.photos}
  1250. # ============================================
  1251. # QR Code Endpoint
  1252. # ============================================
  1253. @router.get("/{archive_id}/qrcode")
  1254. async def get_qrcode(
  1255. archive_id: int,
  1256. request: Request,
  1257. size: int = 200,
  1258. db: AsyncSession = Depends(get_db),
  1259. ):
  1260. """Generate a QR code that links to this archive."""
  1261. try:
  1262. import qrcode
  1263. from PIL import Image as PILImage
  1264. except ImportError:
  1265. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  1266. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1267. archive = result.scalar_one_or_none()
  1268. if not archive:
  1269. raise HTTPException(404, "Archive not found")
  1270. # Build URL to archive download
  1271. base_url = str(request.base_url).rstrip("/")
  1272. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  1273. # Generate QR code
  1274. qr = qrcode.QRCode(
  1275. version=1,
  1276. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1277. box_size=10,
  1278. border=2,
  1279. )
  1280. qr.add_data(archive_url)
  1281. qr.make(fit=True)
  1282. img = qr.make_image(fill_color="black", back_color="white")
  1283. # Convert to PIL Image for resizing
  1284. pil_img = img.get_image()
  1285. # Resize if needed
  1286. if size != 200:
  1287. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  1288. # Convert to bytes
  1289. buffer = io.BytesIO()
  1290. pil_img.save(buffer, format="PNG")
  1291. buffer.seek(0)
  1292. return Response(
  1293. content=buffer.getvalue(),
  1294. media_type="image/png",
  1295. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1296. )
  1297. @router.get("/{archive_id}/capabilities")
  1298. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  1299. """Check what viewing capabilities are available for this 3MF file."""
  1300. import json
  1301. import xml.etree.ElementTree as ET
  1302. service = ArchiveService(db)
  1303. archive = await service.get_archive(archive_id)
  1304. if not archive:
  1305. raise HTTPException(404, "Archive not found")
  1306. file_path = settings.base_dir / archive.file_path
  1307. if not file_path.exists():
  1308. raise HTTPException(404, "File not found")
  1309. has_model = False
  1310. has_gcode = False
  1311. has_source = False
  1312. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1313. filament_colors: list[str] = []
  1314. # Check if source 3MF exists - this is where actual mesh data typically lives
  1315. source_path = None
  1316. if archive.source_3mf_path:
  1317. source_path = settings.base_dir / archive.source_3mf_path
  1318. if source_path.exists():
  1319. has_source = True
  1320. # Helper function to check for mesh data and extract colors from a 3MF file
  1321. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  1322. """Extract mesh presence, colors, and build volume from a 3MF file."""
  1323. found_mesh = False
  1324. colors: list[str] = []
  1325. volume = {"x": 256, "y": 256, "z": 256}
  1326. try:
  1327. with zipfile.ZipFile(zf_path, "r") as zf:
  1328. names = zf.namelist()
  1329. # Check for 3D model - look for actual mesh data
  1330. for name in names:
  1331. if name.endswith(".model"):
  1332. try:
  1333. content = zf.read(name).decode("utf-8")
  1334. if "<vertex" in content or "<mesh" in content:
  1335. found_mesh = True
  1336. break
  1337. except Exception:
  1338. pass
  1339. # Extract filament colors from project_settings.config
  1340. if "Metadata/project_settings.config" in names:
  1341. try:
  1342. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1343. config_data = json.loads(config_content)
  1344. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1345. printable_area = config_data.get("printable_area", [])
  1346. if printable_area and len(printable_area) >= 3:
  1347. max_x = 0
  1348. max_y = 0
  1349. for coord in printable_area:
  1350. if "x" in coord:
  1351. parts = coord.split("x")
  1352. if len(parts) == 2:
  1353. try:
  1354. x, y = int(parts[0]), int(parts[1])
  1355. max_x = max(max_x, x)
  1356. max_y = max(max_y, y)
  1357. except ValueError:
  1358. pass
  1359. if max_x > 0 and max_y > 0:
  1360. volume["x"] = max_x
  1361. volume["y"] = max_y
  1362. # Parse printable_height
  1363. printable_height = config_data.get("printable_height")
  1364. if printable_height:
  1365. try:
  1366. volume["z"] = int(printable_height)
  1367. except (ValueError, TypeError):
  1368. pass
  1369. # Extract filament colors
  1370. raw_colors = config_data.get("filament_colour", [])
  1371. if raw_colors:
  1372. for color in raw_colors:
  1373. if color and isinstance(color, str):
  1374. colors.append(color)
  1375. except Exception:
  1376. pass
  1377. except zipfile.BadZipFile:
  1378. pass
  1379. return found_mesh, colors, volume
  1380. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  1381. if has_source and source_path:
  1382. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  1383. if source_has_mesh:
  1384. has_model = True
  1385. if source_colors:
  1386. filament_colors = source_colors
  1387. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  1388. build_volume = source_volume
  1389. try:
  1390. with zipfile.ZipFile(file_path, "r") as zf:
  1391. names = zf.namelist()
  1392. # Check for G-code in the sliced file
  1393. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1394. # Check for 3D model in sliced file (fallback if no source)
  1395. if not has_model:
  1396. for name in names:
  1397. if name.endswith(".model"):
  1398. try:
  1399. content = zf.read(name).decode("utf-8")
  1400. if "<vertex" in content or "<mesh" in content:
  1401. has_model = True
  1402. break
  1403. except Exception:
  1404. pass
  1405. # Extract filament colors from slice_info.config (for gcode preview)
  1406. # These are the actual filaments used in the print, indexed by tool/extruder
  1407. slice_colors: list[str] = []
  1408. if "Metadata/slice_info.config" in names:
  1409. try:
  1410. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1411. root = ET.fromstring(slice_content)
  1412. filaments = root.findall(".//filament")
  1413. filament_map: dict[int, str] = {}
  1414. for f in filaments:
  1415. fid = f.get("id")
  1416. fcolor = f.get("color")
  1417. used_g = f.get("used_g", "0")
  1418. try:
  1419. used_amount = float(used_g)
  1420. except (ValueError, TypeError):
  1421. used_amount = 0
  1422. if fid is not None and fcolor:
  1423. try:
  1424. tool_id = int(fid) - 1
  1425. if tool_id >= 0 and used_amount > 0:
  1426. filament_map[tool_id] = fcolor
  1427. except ValueError:
  1428. pass
  1429. if filament_map:
  1430. max_tool = max(filament_map.keys())
  1431. for i in range(max_tool + 1):
  1432. slice_colors.append(filament_map.get(i, "#00AE42"))
  1433. except Exception:
  1434. pass
  1435. # Use slice_info colors if we don't have colors from source yet
  1436. if not filament_colors and slice_colors:
  1437. filament_colors = slice_colors
  1438. # Extract build volume from sliced file if not already set from source
  1439. if build_volume["x"] == 256 and build_volume["y"] == 256:
  1440. if "Metadata/project_settings.config" in names:
  1441. try:
  1442. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1443. config_data = json.loads(config_content)
  1444. printable_area = config_data.get("printable_area", [])
  1445. if printable_area and len(printable_area) >= 3:
  1446. max_x = 0
  1447. max_y = 0
  1448. for coord in printable_area:
  1449. if "x" in coord:
  1450. parts = coord.split("x")
  1451. if len(parts) == 2:
  1452. try:
  1453. x, y = int(parts[0]), int(parts[1])
  1454. max_x = max(max_x, x)
  1455. max_y = max(max_y, y)
  1456. except ValueError:
  1457. pass
  1458. if max_x > 0 and max_y > 0:
  1459. build_volume["x"] = max_x
  1460. build_volume["y"] = max_y
  1461. printable_height = config_data.get("printable_height")
  1462. if printable_height:
  1463. try:
  1464. build_volume["z"] = int(printable_height)
  1465. except (ValueError, TypeError):
  1466. pass
  1467. # Fallback colors from project_settings if still empty
  1468. if not filament_colors:
  1469. raw_colors = config_data.get("filament_colour", [])
  1470. if raw_colors:
  1471. for color in raw_colors:
  1472. if color and isinstance(color, str):
  1473. filament_colors.append(color)
  1474. except Exception:
  1475. pass
  1476. except zipfile.BadZipFile:
  1477. raise HTTPException(400, "Invalid 3MF file")
  1478. return {
  1479. "has_model": has_model,
  1480. "has_gcode": has_gcode,
  1481. "has_source": has_source,
  1482. "build_volume": build_volume,
  1483. "filament_colors": filament_colors,
  1484. }
  1485. @router.get("/{archive_id}/gcode")
  1486. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  1487. """Extract and return G-code from the 3MF file."""
  1488. service = ArchiveService(db)
  1489. archive = await service.get_archive(archive_id)
  1490. if not archive:
  1491. raise HTTPException(404, "Archive not found")
  1492. file_path = settings.base_dir / archive.file_path
  1493. if not file_path.exists():
  1494. raise HTTPException(404, "File not found")
  1495. try:
  1496. with zipfile.ZipFile(file_path, "r") as zf:
  1497. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1498. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1499. if not gcode_files:
  1500. raise HTTPException(
  1501. 404,
  1502. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1503. )
  1504. # Get the first plate's G-code (usually plate_1.gcode)
  1505. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1506. return Response(content=gcode_content, media_type="text/plain")
  1507. except zipfile.BadZipFile:
  1508. raise HTTPException(400, "Invalid 3MF file")
  1509. except HTTPException:
  1510. raise
  1511. except Exception as e:
  1512. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1513. @router.get("/{archive_id}/plate-preview")
  1514. async def get_plate_preview(archive_id: int, db: AsyncSession = Depends(get_db)):
  1515. """Get the plate preview image from the 3MF file.
  1516. Returns the slicer-generated plate thumbnail which shows the model
  1517. with correct colors and positioning.
  1518. """
  1519. service = ArchiveService(db)
  1520. archive = await service.get_archive(archive_id)
  1521. if not archive:
  1522. raise HTTPException(404, "Archive not found")
  1523. file_path = settings.base_dir / archive.file_path
  1524. if not file_path.exists():
  1525. raise HTTPException(404, "File not found")
  1526. try:
  1527. with zipfile.ZipFile(file_path, "r") as zf:
  1528. names = zf.namelist()
  1529. # Try to find plate preview images in order of preference
  1530. # First look for the specific plate being printed (check slice_info for plate index)
  1531. plate_num = 1
  1532. if "Metadata/slice_info.config" in names:
  1533. try:
  1534. import xml.etree.ElementTree as ET
  1535. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1536. root = ET.fromstring(slice_content)
  1537. plate_elem = root.find(".//plate/metadata[@key='index']")
  1538. if plate_elem is not None:
  1539. plate_num = int(plate_elem.get("value", "1"))
  1540. except Exception:
  1541. pass
  1542. # Try plate-specific image first, then fall back to plate_1
  1543. preview_paths = [
  1544. f"Metadata/plate_{plate_num}.png",
  1545. "Metadata/plate_1.png",
  1546. "Metadata/thumbnail.png",
  1547. ]
  1548. for preview_path in preview_paths:
  1549. if preview_path in names:
  1550. image_data = zf.read(preview_path)
  1551. return Response(content=image_data, media_type="image/png")
  1552. # If no plate image, try any PNG in Metadata
  1553. for name in names:
  1554. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  1555. image_data = zf.read(name)
  1556. return Response(content=image_data, media_type="image/png")
  1557. raise HTTPException(404, "No plate preview found in 3MF file")
  1558. except zipfile.BadZipFile:
  1559. raise HTTPException(400, "Invalid 3MF file")
  1560. except HTTPException:
  1561. raise
  1562. except Exception as e:
  1563. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  1564. @router.post("/upload")
  1565. async def upload_archive(
  1566. file: UploadFile = File(...),
  1567. printer_id: int | None = None,
  1568. db: AsyncSession = Depends(get_db),
  1569. ):
  1570. """Manually upload a 3MF file to archive."""
  1571. if not file.filename or not file.filename.endswith(".3mf"):
  1572. raise HTTPException(400, "File must be a .3mf file")
  1573. # Save uploaded file temporarily
  1574. temp_path = settings.archive_dir / "temp" / file.filename
  1575. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1576. try:
  1577. content = await file.read()
  1578. temp_path.write_bytes(content)
  1579. service = ArchiveService(db)
  1580. archive = await service.archive_print(
  1581. printer_id=printer_id,
  1582. source_file=temp_path,
  1583. )
  1584. if not archive:
  1585. raise HTTPException(400, "Failed to archive file")
  1586. return ArchiveResponse.model_validate(archive)
  1587. finally:
  1588. if temp_path.exists():
  1589. temp_path.unlink()
  1590. @router.post("/upload-bulk")
  1591. async def upload_archives_bulk(
  1592. files: list[UploadFile] = File(...),
  1593. printer_id: int | None = None,
  1594. db: AsyncSession = Depends(get_db),
  1595. ):
  1596. """Bulk upload multiple 3MF files to archive."""
  1597. results = []
  1598. errors = []
  1599. for file in files:
  1600. if not file.filename or not file.filename.endswith(".3mf"):
  1601. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1602. continue
  1603. temp_path = settings.archive_dir / "temp" / file.filename
  1604. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1605. try:
  1606. content = await file.read()
  1607. temp_path.write_bytes(content)
  1608. service = ArchiveService(db)
  1609. archive = await service.archive_print(
  1610. printer_id=printer_id,
  1611. source_file=temp_path,
  1612. )
  1613. if archive:
  1614. results.append(
  1615. {
  1616. "filename": file.filename,
  1617. "id": archive.id,
  1618. "status": "success",
  1619. }
  1620. )
  1621. else:
  1622. errors.append({"filename": file.filename, "error": "Failed to process"})
  1623. except Exception as e:
  1624. errors.append({"filename": file.filename, "error": str(e)})
  1625. finally:
  1626. if temp_path.exists():
  1627. temp_path.unlink()
  1628. return {
  1629. "uploaded": len(results),
  1630. "failed": len(errors),
  1631. "results": results,
  1632. "errors": errors,
  1633. }
  1634. @router.get("/{archive_id}/plates")
  1635. async def get_archive_plates(
  1636. archive_id: int,
  1637. db: AsyncSession = Depends(get_db),
  1638. ):
  1639. """Get available plates from a multi-plate 3MF archive.
  1640. Returns a list of plates with their index, name, thumbnail availability,
  1641. and filament requirements. For single-plate exports, returns a single plate.
  1642. """
  1643. import xml.etree.ElementTree as ET
  1644. service = ArchiveService(db)
  1645. archive = await service.get_archive(archive_id)
  1646. if not archive:
  1647. raise HTTPException(404, "Archive not found")
  1648. file_path = settings.base_dir / archive.file_path
  1649. if not file_path.exists():
  1650. raise HTTPException(404, "Archive file not found")
  1651. plates = []
  1652. try:
  1653. with zipfile.ZipFile(file_path, "r") as zf:
  1654. namelist = zf.namelist()
  1655. # Find all plate gcode files to determine available plates
  1656. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1657. if not gcode_files:
  1658. # No sliced plates found
  1659. return {"archive_id": archive_id, "filename": archive.filename, "plates": []}
  1660. # Extract plate indices from gcode filenames
  1661. plate_indices = []
  1662. for gf in gcode_files:
  1663. # "Metadata/plate_5.gcode" -> 5
  1664. try:
  1665. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1666. plate_indices.append(int(plate_str))
  1667. except ValueError:
  1668. pass
  1669. plate_indices.sort()
  1670. # Parse model_settings.config for plate names
  1671. # Plate names are stored with plater_id and plater_name keys
  1672. plate_names = {} # plater_id -> name
  1673. if "Metadata/model_settings.config" in namelist:
  1674. try:
  1675. model_content = zf.read("Metadata/model_settings.config").decode()
  1676. model_root = ET.fromstring(model_content)
  1677. for plate_elem in model_root.findall(".//plate"):
  1678. plater_id = None
  1679. plater_name = None
  1680. for meta in plate_elem.findall("metadata"):
  1681. key = meta.get("key")
  1682. value = meta.get("value")
  1683. if key == "plater_id" and value:
  1684. try:
  1685. plater_id = int(value)
  1686. except ValueError:
  1687. pass
  1688. elif key == "plater_name" and value:
  1689. plater_name = value.strip()
  1690. if plater_id is not None and plater_name:
  1691. plate_names[plater_id] = plater_name
  1692. except Exception:
  1693. pass # model_settings.config parsing is optional
  1694. # Parse slice_info.config for plate metadata
  1695. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  1696. if "Metadata/slice_info.config" in namelist:
  1697. content = zf.read("Metadata/slice_info.config").decode()
  1698. root = ET.fromstring(content)
  1699. for plate_elem in root.findall(".//plate"):
  1700. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1701. # Get plate index from metadata
  1702. plate_index = None
  1703. for meta in plate_elem.findall("metadata"):
  1704. key = meta.get("key")
  1705. value = meta.get("value")
  1706. if key == "index" and value:
  1707. try:
  1708. plate_index = int(value)
  1709. except ValueError:
  1710. pass
  1711. elif key == "prediction" and value:
  1712. try:
  1713. plate_info["prediction"] = int(value)
  1714. except ValueError:
  1715. pass
  1716. elif key == "weight" and value:
  1717. try:
  1718. plate_info["weight"] = float(value)
  1719. except ValueError:
  1720. pass
  1721. # Get filaments used in this plate
  1722. for filament_elem in plate_elem.findall("filament"):
  1723. filament_id = filament_elem.get("id")
  1724. filament_type = filament_elem.get("type", "")
  1725. filament_color = filament_elem.get("color", "")
  1726. used_g = filament_elem.get("used_g", "0")
  1727. used_m = filament_elem.get("used_m", "0")
  1728. try:
  1729. used_grams = float(used_g)
  1730. except (ValueError, TypeError):
  1731. used_grams = 0
  1732. if used_grams > 0 and filament_id:
  1733. plate_info["filaments"].append(
  1734. {
  1735. "slot_id": int(filament_id),
  1736. "type": filament_type,
  1737. "color": filament_color,
  1738. "used_grams": round(used_grams, 1),
  1739. "used_meters": float(used_m) if used_m else 0,
  1740. }
  1741. )
  1742. # Sort filaments by slot ID
  1743. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  1744. # Collect all object names on this plate
  1745. for obj_elem in plate_elem.findall("object"):
  1746. obj_name = obj_elem.get("name")
  1747. if obj_name and obj_name not in plate_info["objects"]:
  1748. plate_info["objects"].append(obj_name)
  1749. # Set plate name: prefer custom name from model_settings.config,
  1750. # fall back to first object name if no custom name was set
  1751. if plate_index is not None:
  1752. custom_name = plate_names.get(plate_index)
  1753. if custom_name:
  1754. plate_info["name"] = custom_name
  1755. else:
  1756. # Fall back to first object name as hint
  1757. if plate_info["objects"]:
  1758. plate_info["name"] = plate_info["objects"][0]
  1759. plate_metadata[plate_index] = plate_info
  1760. # Build plate list
  1761. for idx in plate_indices:
  1762. meta = plate_metadata.get(idx, {})
  1763. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1764. plates.append(
  1765. {
  1766. "index": idx,
  1767. "name": meta.get("name"),
  1768. "objects": meta.get("objects", []),
  1769. "has_thumbnail": has_thumbnail,
  1770. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  1771. if has_thumbnail
  1772. else None,
  1773. "print_time_seconds": meta.get("prediction"),
  1774. "filament_used_grams": meta.get("weight"),
  1775. "filaments": meta.get("filaments", []),
  1776. }
  1777. )
  1778. except Exception as e:
  1779. logger.warning(f"Failed to parse plates from archive {archive_id}: {e}")
  1780. return {
  1781. "archive_id": archive_id,
  1782. "filename": archive.filename,
  1783. "plates": plates,
  1784. "is_multi_plate": len(plates) > 1,
  1785. }
  1786. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  1787. async def get_plate_thumbnail(
  1788. archive_id: int,
  1789. plate_index: int,
  1790. db: AsyncSession = Depends(get_db),
  1791. ):
  1792. """Get the thumbnail image for a specific plate."""
  1793. service = ArchiveService(db)
  1794. archive = await service.get_archive(archive_id)
  1795. if not archive:
  1796. raise HTTPException(404, "Archive not found")
  1797. file_path = settings.base_dir / archive.file_path
  1798. if not file_path.exists():
  1799. raise HTTPException(404, "Archive file not found")
  1800. try:
  1801. with zipfile.ZipFile(file_path, "r") as zf:
  1802. thumb_path = f"Metadata/plate_{plate_index}.png"
  1803. if thumb_path in zf.namelist():
  1804. data = zf.read(thumb_path)
  1805. return Response(content=data, media_type="image/png")
  1806. except Exception:
  1807. pass
  1808. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  1809. @router.get("/{archive_id}/filament-requirements")
  1810. async def get_filament_requirements(
  1811. archive_id: int,
  1812. plate_id: int | None = None,
  1813. db: AsyncSession = Depends(get_db),
  1814. ):
  1815. """Get filament requirements from the archived 3MF file.
  1816. Returns the filaments used in this print with their slot IDs, types, colors,
  1817. and usage amounts. This can be compared with current AMS state before reprinting.
  1818. Args:
  1819. archive_id: The archive ID
  1820. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  1821. """
  1822. import xml.etree.ElementTree as ET
  1823. service = ArchiveService(db)
  1824. archive = await service.get_archive(archive_id)
  1825. if not archive:
  1826. raise HTTPException(404, "Archive not found")
  1827. file_path = settings.base_dir / archive.file_path
  1828. if not file_path.exists():
  1829. raise HTTPException(404, "Archive file not found")
  1830. filaments = []
  1831. try:
  1832. with zipfile.ZipFile(file_path, "r") as zf:
  1833. # Parse slice_info.config for filament requirements
  1834. if "Metadata/slice_info.config" in zf.namelist():
  1835. content = zf.read("Metadata/slice_info.config").decode()
  1836. root = ET.fromstring(content)
  1837. # If plate_id is specified, find filaments for that specific plate
  1838. if plate_id is not None:
  1839. # Find the plate element with matching index
  1840. for plate_elem in root.findall(".//plate"):
  1841. plate_index = None
  1842. for meta in plate_elem.findall("metadata"):
  1843. if meta.get("key") == "index":
  1844. try:
  1845. plate_index = int(meta.get("value", "0"))
  1846. except ValueError:
  1847. pass
  1848. break
  1849. if plate_index == plate_id:
  1850. # Extract filaments from this plate element
  1851. for filament_elem in plate_elem.findall("filament"):
  1852. filament_id = filament_elem.get("id")
  1853. filament_type = filament_elem.get("type", "")
  1854. filament_color = filament_elem.get("color", "")
  1855. used_g = filament_elem.get("used_g", "0")
  1856. used_m = filament_elem.get("used_m", "0")
  1857. try:
  1858. used_grams = float(used_g)
  1859. except (ValueError, TypeError):
  1860. used_grams = 0
  1861. if used_grams > 0 and filament_id:
  1862. filaments.append(
  1863. {
  1864. "slot_id": int(filament_id),
  1865. "type": filament_type,
  1866. "color": filament_color,
  1867. "used_grams": round(used_grams, 1),
  1868. "used_meters": float(used_m) if used_m else 0,
  1869. }
  1870. )
  1871. break
  1872. else:
  1873. # No plate_id specified - extract all filaments with used_g > 0
  1874. # This is the legacy behavior for single-plate files
  1875. for filament_elem in root.findall(".//filament"):
  1876. filament_id = filament_elem.get("id")
  1877. filament_type = filament_elem.get("type", "")
  1878. filament_color = filament_elem.get("color", "")
  1879. used_g = filament_elem.get("used_g", "0")
  1880. used_m = filament_elem.get("used_m", "0")
  1881. # Only include filaments that are actually used
  1882. try:
  1883. used_grams = float(used_g)
  1884. except (ValueError, TypeError):
  1885. used_grams = 0
  1886. if used_grams > 0 and filament_id:
  1887. filaments.append(
  1888. {
  1889. "slot_id": int(filament_id),
  1890. "type": filament_type,
  1891. "color": filament_color,
  1892. "used_grams": round(used_grams, 1),
  1893. "used_meters": float(used_m) if used_m else 0,
  1894. }
  1895. )
  1896. # Sort by slot ID
  1897. filaments.sort(key=lambda x: x["slot_id"])
  1898. except Exception as e:
  1899. logger.warning(f"Failed to parse filament requirements from archive {archive_id}: {e}")
  1900. return {
  1901. "archive_id": archive_id,
  1902. "filename": archive.filename,
  1903. "plate_id": plate_id,
  1904. "filaments": filaments,
  1905. }
  1906. @router.post("/{archive_id}/reprint")
  1907. async def reprint_archive(
  1908. archive_id: int,
  1909. printer_id: int,
  1910. body: ReprintRequest | None = None,
  1911. db: AsyncSession = Depends(get_db),
  1912. ):
  1913. """Send an archived 3MF file to a printer and start printing."""
  1914. from backend.app.main import register_expected_print
  1915. from backend.app.models.printer import Printer
  1916. from backend.app.services.bambu_ftp import (
  1917. get_ftp_retry_settings,
  1918. upload_file_async,
  1919. with_ftp_retry,
  1920. )
  1921. from backend.app.services.printer_manager import printer_manager
  1922. # Use defaults if no body provided
  1923. if body is None:
  1924. body = ReprintRequest()
  1925. # Get archive
  1926. service = ArchiveService(db)
  1927. archive = await service.get_archive(archive_id)
  1928. if not archive:
  1929. raise HTTPException(404, "Archive not found")
  1930. # Get printer
  1931. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1932. printer = result.scalar_one_or_none()
  1933. if not printer:
  1934. raise HTTPException(404, "Printer not found")
  1935. # Check printer is connected
  1936. if not printer_manager.is_connected(printer_id):
  1937. raise HTTPException(400, "Printer is not connected")
  1938. # Get the sliced 3MF file path
  1939. file_path = settings.base_dir / archive.file_path
  1940. if not file_path.exists():
  1941. raise HTTPException(404, "Archive file not found")
  1942. # Upload file to printer via FTP
  1943. from backend.app.services.bambu_ftp import delete_file_async
  1944. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1945. # The printer might reject filenames with unusual extensions
  1946. base_name = archive.filename
  1947. if base_name.endswith(".gcode.3mf"):
  1948. base_name = base_name[:-10] # Remove .gcode.3mf
  1949. elif base_name.endswith(".3mf"):
  1950. base_name = base_name[:-4] # Remove .3mf
  1951. remote_filename = f"{base_name}.3mf"
  1952. remote_path = f"/{remote_filename}"
  1953. # Get FTP retry settings
  1954. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1955. # Delete existing file if present (avoids 553 error)
  1956. await delete_file_async(
  1957. printer.ip_address,
  1958. printer.access_code,
  1959. remote_path,
  1960. socket_timeout=ftp_timeout,
  1961. printer_model=printer.model,
  1962. )
  1963. if ftp_retry_enabled:
  1964. uploaded = await with_ftp_retry(
  1965. upload_file_async,
  1966. printer.ip_address,
  1967. printer.access_code,
  1968. file_path,
  1969. remote_path,
  1970. socket_timeout=ftp_timeout,
  1971. printer_model=printer.model,
  1972. max_retries=ftp_retry_count,
  1973. retry_delay=ftp_retry_delay,
  1974. operation_name=f"Upload for reprint to {printer.name}",
  1975. )
  1976. else:
  1977. uploaded = await upload_file_async(
  1978. printer.ip_address,
  1979. printer.access_code,
  1980. file_path,
  1981. remote_path,
  1982. socket_timeout=ftp_timeout,
  1983. printer_model=printer.model,
  1984. )
  1985. if not uploaded:
  1986. raise HTTPException(500, "Failed to upload file to printer")
  1987. # Register this as an expected print so we don't create a duplicate archive
  1988. register_expected_print(printer_id, remote_filename, archive_id)
  1989. # Use plate_id from request if provided, otherwise auto-detect from 3MF file
  1990. if body.plate_id is not None:
  1991. plate_id = body.plate_id
  1992. else:
  1993. # Auto-detect plate ID from 3MF file (legacy behavior for single-plate files)
  1994. plate_id = 1
  1995. try:
  1996. with zipfile.ZipFile(file_path, "r") as zf:
  1997. for name in zf.namelist():
  1998. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1999. # Extract plate number from "Metadata/plate_X.gcode"
  2000. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  2001. plate_id = int(plate_str)
  2002. break
  2003. except Exception:
  2004. pass # Default to plate 1 if detection fails
  2005. logger.info(
  2006. f"Reprint archive {archive_id}: plate_id={plate_id}, "
  2007. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}, "
  2008. f"flow_cali={body.flow_cali}, vibration_cali={body.vibration_cali}, "
  2009. f"layer_inspect={body.layer_inspect}, timelapse={body.timelapse}"
  2010. )
  2011. # Start the print with options
  2012. started = printer_manager.start_print(
  2013. printer_id,
  2014. remote_filename,
  2015. plate_id,
  2016. ams_mapping=body.ams_mapping,
  2017. timelapse=body.timelapse,
  2018. bed_levelling=body.bed_levelling,
  2019. flow_cali=body.flow_cali,
  2020. vibration_cali=body.vibration_cali,
  2021. layer_inspect=body.layer_inspect,
  2022. use_ams=body.use_ams,
  2023. )
  2024. if not started:
  2025. raise HTTPException(500, "Failed to start print")
  2026. return {
  2027. "status": "printing",
  2028. "printer_id": printer_id,
  2029. "archive_id": archive_id,
  2030. "filename": archive.filename,
  2031. }
  2032. # =============================================================================
  2033. # Project Page API
  2034. # =============================================================================
  2035. @router.get("/{archive_id}/project-page")
  2036. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  2037. """Get the project page data from the 3MF file."""
  2038. from backend.app.schemas.archive import ProjectPageResponse
  2039. from backend.app.services.archive import ProjectPageParser
  2040. service = ArchiveService(db)
  2041. archive = await service.get_archive(archive_id)
  2042. if not archive:
  2043. raise HTTPException(404, "Archive not found")
  2044. file_path = settings.base_dir / archive.file_path
  2045. if not file_path.exists():
  2046. raise HTTPException(404, "Archive file not found")
  2047. parser = ProjectPageParser(file_path)
  2048. data = parser.parse(archive_id)
  2049. return ProjectPageResponse(**data)
  2050. @router.patch("/{archive_id}/project-page")
  2051. async def update_project_page(
  2052. archive_id: int,
  2053. update_data: dict,
  2054. db: AsyncSession = Depends(get_db),
  2055. ):
  2056. """Update project page metadata in the 3MF file."""
  2057. from backend.app.services.archive import ProjectPageParser
  2058. service = ArchiveService(db)
  2059. archive = await service.get_archive(archive_id)
  2060. if not archive:
  2061. raise HTTPException(404, "Archive not found")
  2062. file_path = settings.base_dir / archive.file_path
  2063. if not file_path.exists():
  2064. raise HTTPException(404, "Archive file not found")
  2065. parser = ProjectPageParser(file_path)
  2066. success = parser.update_metadata(update_data)
  2067. if not success:
  2068. raise HTTPException(500, "Failed to update project page")
  2069. # Return updated data
  2070. data = parser.parse(archive_id)
  2071. return data
  2072. @router.get("/{archive_id}/project-image/{image_path:path}")
  2073. async def get_project_image(
  2074. archive_id: int,
  2075. image_path: str,
  2076. db: AsyncSession = Depends(get_db),
  2077. ):
  2078. """Get an image from the 3MF project page."""
  2079. from backend.app.services.archive import ProjectPageParser
  2080. service = ArchiveService(db)
  2081. archive = await service.get_archive(archive_id)
  2082. if not archive:
  2083. raise HTTPException(404, "Archive not found")
  2084. file_path = settings.base_dir / archive.file_path
  2085. if not file_path.exists():
  2086. raise HTTPException(404, "Archive file not found")
  2087. parser = ProjectPageParser(file_path)
  2088. result = parser.get_image(image_path)
  2089. if not result:
  2090. raise HTTPException(404, "Image not found in 3MF file")
  2091. image_data, content_type = result
  2092. return Response(
  2093. content=image_data,
  2094. media_type=content_type,
  2095. headers={"Cache-Control": "max-age=3600"},
  2096. )
  2097. # =============================================================================
  2098. # Source 3MF API (Original Project Files)
  2099. # =============================================================================
  2100. @router.post("/{archive_id}/source")
  2101. async def upload_source_3mf(
  2102. archive_id: int,
  2103. file: UploadFile = File(...),
  2104. db: AsyncSession = Depends(get_db),
  2105. ):
  2106. """Upload the original source 3MF project file for an archive."""
  2107. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2108. archive = result.scalar_one_or_none()
  2109. if not archive:
  2110. raise HTTPException(404, "Archive not found")
  2111. if not file.filename or not file.filename.endswith(".3mf"):
  2112. raise HTTPException(400, "File must be a .3mf file")
  2113. # Get archive directory and create source subdirectory
  2114. file_path = settings.base_dir / archive.file_path
  2115. archive_dir = file_path.parent
  2116. source_dir = archive_dir / "source"
  2117. source_dir.mkdir(exist_ok=True)
  2118. # Delete old source file if exists
  2119. if archive.source_3mf_path:
  2120. old_source_path = settings.base_dir / archive.source_3mf_path
  2121. if old_source_path.exists():
  2122. old_source_path.unlink()
  2123. # Save the source 3MF file - preserve original filename
  2124. source_filename = file.filename
  2125. source_path = source_dir / source_filename
  2126. content = await file.read()
  2127. source_path.write_bytes(content)
  2128. # Update archive with source path (relative to base_dir)
  2129. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2130. await db.commit()
  2131. await db.refresh(archive)
  2132. return {
  2133. "status": "uploaded",
  2134. "source_3mf_path": archive.source_3mf_path,
  2135. "filename": source_filename,
  2136. }
  2137. @router.get("/{archive_id}/source")
  2138. async def download_source_3mf(
  2139. archive_id: int,
  2140. db: AsyncSession = Depends(get_db),
  2141. ):
  2142. """Download the source 3MF project file."""
  2143. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2144. archive = result.scalar_one_or_none()
  2145. if not archive:
  2146. raise HTTPException(404, "Archive not found")
  2147. if not archive.source_3mf_path:
  2148. raise HTTPException(404, "No source 3MF attached to this archive")
  2149. source_path = settings.base_dir / archive.source_3mf_path
  2150. if not source_path.exists():
  2151. raise HTTPException(404, "Source 3MF file not found on disk")
  2152. # Use the actual filename from the path
  2153. filename = source_path.name
  2154. return FileResponse(
  2155. path=source_path,
  2156. filename=filename,
  2157. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2158. )
  2159. @router.get("/{archive_id}/source/{filename}")
  2160. async def download_source_3mf_for_slicer(
  2161. archive_id: int,
  2162. filename: str,
  2163. db: AsyncSession = Depends(get_db),
  2164. ):
  2165. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  2166. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2167. archive = result.scalar_one_or_none()
  2168. if not archive:
  2169. raise HTTPException(404, "Archive not found")
  2170. if not archive.source_3mf_path:
  2171. raise HTTPException(404, "No source 3MF attached to this archive")
  2172. source_path = settings.base_dir / archive.source_3mf_path
  2173. if not source_path.exists():
  2174. raise HTTPException(404, "Source 3MF file not found on disk")
  2175. return FileResponse(
  2176. path=source_path,
  2177. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  2178. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2179. )
  2180. @router.post("/upload-source")
  2181. async def upload_source_3mf_by_name(
  2182. file: UploadFile = File(...),
  2183. print_name: str = Query(None, description="Match archive by print name"),
  2184. db: AsyncSession = Depends(get_db),
  2185. ):
  2186. """Upload source 3MF and match to archive by print name.
  2187. This endpoint is designed for slicer post-processing scripts.
  2188. It finds the most recent archive matching the print name and attaches the source.
  2189. """
  2190. if not file.filename or not file.filename.endswith(".3mf"):
  2191. raise HTTPException(400, "File must be a .3mf file")
  2192. # Derive print name from filename if not provided
  2193. if not print_name:
  2194. # Remove .3mf extension and common suffixes
  2195. print_name = file.filename.rsplit(".3mf", 1)[0]
  2196. # Remove _source suffix if present
  2197. if print_name.endswith("_source"):
  2198. print_name = print_name[:-7]
  2199. # Find matching archive - try exact match first, then fuzzy
  2200. result = await db.execute(
  2201. select(PrintArchive)
  2202. .where(PrintArchive.print_name == print_name)
  2203. .order_by(PrintArchive.created_at.desc())
  2204. .limit(1)
  2205. )
  2206. archive = result.scalar_one_or_none()
  2207. if not archive:
  2208. # Try matching filename without .gcode.3mf
  2209. result = await db.execute(
  2210. select(PrintArchive)
  2211. .where(PrintArchive.filename.like(f"{print_name}%"))
  2212. .order_by(PrintArchive.created_at.desc())
  2213. .limit(1)
  2214. )
  2215. archive = result.scalar_one_or_none()
  2216. if not archive:
  2217. # Try case-insensitive partial match on print_name
  2218. result = await db.execute(
  2219. select(PrintArchive)
  2220. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  2221. .order_by(PrintArchive.created_at.desc())
  2222. .limit(1)
  2223. )
  2224. archive = result.scalar_one_or_none()
  2225. if not archive:
  2226. raise HTTPException(404, f"No archive found matching '{print_name}'")
  2227. # Get archive directory and create source subdirectory
  2228. file_path = settings.base_dir / archive.file_path
  2229. archive_dir = file_path.parent
  2230. source_dir = archive_dir / "source"
  2231. source_dir.mkdir(exist_ok=True)
  2232. # Delete old source file if exists
  2233. if archive.source_3mf_path:
  2234. old_source_path = settings.base_dir / archive.source_3mf_path
  2235. if old_source_path.exists():
  2236. old_source_path.unlink()
  2237. # Save the source 3MF file - preserve original filename
  2238. source_filename = file.filename
  2239. source_path = source_dir / source_filename
  2240. content = await file.read()
  2241. source_path.write_bytes(content)
  2242. # Update archive with source path
  2243. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2244. await db.commit()
  2245. await db.refresh(archive)
  2246. return {
  2247. "status": "uploaded",
  2248. "archive_id": archive.id,
  2249. "archive_name": archive.print_name or archive.filename,
  2250. "source_3mf_path": archive.source_3mf_path,
  2251. "filename": source_filename,
  2252. }
  2253. @router.delete("/{archive_id}/source")
  2254. async def delete_source_3mf(
  2255. archive_id: int,
  2256. db: AsyncSession = Depends(get_db),
  2257. ):
  2258. """Delete the source 3MF project file from an archive."""
  2259. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2260. archive = result.scalar_one_or_none()
  2261. if not archive:
  2262. raise HTTPException(404, "Archive not found")
  2263. if not archive.source_3mf_path:
  2264. raise HTTPException(404, "No source 3MF attached to this archive")
  2265. # Delete the file
  2266. source_path = settings.base_dir / archive.source_3mf_path
  2267. if source_path.exists():
  2268. source_path.unlink()
  2269. # Clear the path in database
  2270. archive.source_3mf_path = None
  2271. await db.commit()
  2272. return {"status": "deleted"}
  2273. # =============================================================================
  2274. # F3D API (Fusion 360 Design Files)
  2275. # =============================================================================
  2276. @router.post("/{archive_id}/f3d")
  2277. async def upload_f3d(
  2278. archive_id: int,
  2279. file: UploadFile = File(...),
  2280. db: AsyncSession = Depends(get_db),
  2281. ):
  2282. """Upload a Fusion 360 design file for an archive."""
  2283. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2284. archive = result.scalar_one_or_none()
  2285. if not archive:
  2286. raise HTTPException(404, "Archive not found")
  2287. if not file.filename or not file.filename.endswith(".f3d"):
  2288. raise HTTPException(400, "File must be a .f3d file")
  2289. # Get archive directory and create f3d subdirectory
  2290. file_path = settings.base_dir / archive.file_path
  2291. archive_dir = file_path.parent
  2292. f3d_dir = archive_dir / "f3d"
  2293. f3d_dir.mkdir(exist_ok=True)
  2294. # Delete old F3D file if exists
  2295. if archive.f3d_path:
  2296. old_f3d_path = settings.base_dir / archive.f3d_path
  2297. if old_f3d_path.exists():
  2298. old_f3d_path.unlink()
  2299. # Save the F3D file - preserve original filename
  2300. f3d_filename = file.filename
  2301. f3d_path = f3d_dir / f3d_filename
  2302. content = await file.read()
  2303. f3d_path.write_bytes(content)
  2304. # Update archive with F3D path (relative to base_dir)
  2305. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  2306. await db.commit()
  2307. await db.refresh(archive)
  2308. return {
  2309. "status": "uploaded",
  2310. "f3d_path": archive.f3d_path,
  2311. "filename": f3d_filename,
  2312. }
  2313. @router.get("/{archive_id}/f3d")
  2314. async def download_f3d(
  2315. archive_id: int,
  2316. db: AsyncSession = Depends(get_db),
  2317. ):
  2318. """Download the Fusion 360 design file."""
  2319. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2320. archive = result.scalar_one_or_none()
  2321. if not archive:
  2322. raise HTTPException(404, "Archive not found")
  2323. if not archive.f3d_path:
  2324. raise HTTPException(404, "No F3D file attached to this archive")
  2325. f3d_path = settings.base_dir / archive.f3d_path
  2326. if not f3d_path.exists():
  2327. raise HTTPException(404, "F3D file not found on disk")
  2328. # Use the actual filename from the path
  2329. filename = f3d_path.name
  2330. return FileResponse(
  2331. path=f3d_path,
  2332. filename=filename,
  2333. media_type="application/octet-stream",
  2334. )
  2335. @router.delete("/{archive_id}/f3d")
  2336. async def delete_f3d(
  2337. archive_id: int,
  2338. db: AsyncSession = Depends(get_db),
  2339. ):
  2340. """Delete the Fusion 360 design file from an archive."""
  2341. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2342. archive = result.scalar_one_or_none()
  2343. if not archive:
  2344. raise HTTPException(404, "Archive not found")
  2345. if not archive.f3d_path:
  2346. raise HTTPException(404, "No F3D file attached to this archive")
  2347. # Delete the file
  2348. f3d_path = settings.base_dir / archive.f3d_path
  2349. if f3d_path.exists():
  2350. f3d_path.unlink()
  2351. # Clear the path in database
  2352. archive.f3d_path = None
  2353. await db.commit()
  2354. return {"status": "deleted"}