archives.py 86 KB

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