archives.py 105 KB

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