archives.py 105 KB

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