archives.py 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399
  1. import io
  2. import logging
  3. import zipfile
  4. from pathlib import Path
  5. from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
  6. from fastapi.responses import FileResponse, Response
  7. from sqlalchemy import func, select
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from backend.app.core.config import settings
  10. from backend.app.core.database import get_db
  11. from backend.app.models.archive import PrintArchive
  12. from backend.app.models.filament import Filament
  13. from backend.app.schemas.archive import ArchiveResponse, ArchiveStats, ArchiveUpdate, ReprintRequest
  14. from backend.app.services.archive import ArchiveService
  15. logger = logging.getLogger(__name__)
  16. router = APIRouter(prefix="/archives", tags=["archives"])
  17. def compute_time_accuracy(archive: PrintArchive) -> dict:
  18. """Compute actual print time and accuracy for an archive.
  19. Returns dict with actual_time_seconds and time_accuracy.
  20. time_accuracy = (estimated / actual) * 100
  21. - 100% = perfect estimate
  22. - >100% = print was faster than estimated
  23. - <100% = print took longer than estimated
  24. """
  25. result = {"actual_time_seconds": None, "time_accuracy": None}
  26. if archive.started_at and archive.completed_at and archive.status == "completed":
  27. actual_seconds = int((archive.completed_at - archive.started_at).total_seconds())
  28. if actual_seconds > 0:
  29. result["actual_time_seconds"] = actual_seconds
  30. if archive.print_time_seconds and archive.print_time_seconds > 0:
  31. # Calculate accuracy as percentage
  32. accuracy = (archive.print_time_seconds / actual_seconds) * 100
  33. # Sanity check: skip unreasonable values (e.g., manually changed status)
  34. # Valid range: 5% to 500% (print took 20x longer to 5x faster than estimated)
  35. if 5 <= accuracy <= 500:
  36. result["time_accuracy"] = round(accuracy, 1)
  37. return result
  38. def archive_to_response(
  39. archive: PrintArchive,
  40. duplicates: list[dict] | None = None,
  41. duplicate_count: int = 0,
  42. ) -> dict:
  43. """Convert archive model to response dict with computed fields."""
  44. data = {
  45. "id": archive.id,
  46. "printer_id": archive.printer_id,
  47. "project_id": archive.project_id,
  48. "project_name": archive.project.name if archive.project else None,
  49. "filename": archive.filename,
  50. "file_path": archive.file_path,
  51. "file_size": archive.file_size,
  52. "content_hash": archive.content_hash,
  53. "thumbnail_path": archive.thumbnail_path,
  54. "timelapse_path": archive.timelapse_path,
  55. "source_3mf_path": archive.source_3mf_path,
  56. "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. try:
  1203. import qrcode
  1204. from PIL import Image as PILImage
  1205. except ImportError:
  1206. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  1207. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1208. archive = result.scalar_one_or_none()
  1209. if not archive:
  1210. raise HTTPException(404, "Archive not found")
  1211. # Build URL to archive download
  1212. base_url = str(request.base_url).rstrip("/")
  1213. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  1214. # Generate QR code
  1215. qr = qrcode.QRCode(
  1216. version=1,
  1217. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1218. box_size=10,
  1219. border=2,
  1220. )
  1221. qr.add_data(archive_url)
  1222. qr.make(fit=True)
  1223. img = qr.make_image(fill_color="black", back_color="white")
  1224. # Convert to PIL Image for resizing
  1225. pil_img = img.get_image()
  1226. # Resize if needed
  1227. if size != 200:
  1228. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  1229. # Convert to bytes
  1230. buffer = io.BytesIO()
  1231. pil_img.save(buffer, format="PNG")
  1232. buffer.seek(0)
  1233. return Response(
  1234. content=buffer.getvalue(),
  1235. media_type="image/png",
  1236. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1237. )
  1238. @router.get("/{archive_id}/capabilities")
  1239. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  1240. """Check what viewing capabilities are available for this 3MF file."""
  1241. import json
  1242. import xml.etree.ElementTree as ET
  1243. service = ArchiveService(db)
  1244. archive = await service.get_archive(archive_id)
  1245. if not archive:
  1246. raise HTTPException(404, "Archive not found")
  1247. file_path = settings.base_dir / archive.file_path
  1248. if not file_path.exists():
  1249. raise HTTPException(404, "File not found")
  1250. has_model = False
  1251. has_gcode = False
  1252. has_source = False
  1253. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1254. filament_colors: list[str] = []
  1255. # Check if source 3MF exists - this is where actual mesh data typically lives
  1256. source_path = None
  1257. if archive.source_3mf_path:
  1258. source_path = settings.base_dir / archive.source_3mf_path
  1259. if source_path.exists():
  1260. has_source = True
  1261. # Helper function to check for mesh data and extract colors from a 3MF file
  1262. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  1263. """Extract mesh presence, colors, and build volume from a 3MF file."""
  1264. found_mesh = False
  1265. colors: list[str] = []
  1266. volume = {"x": 256, "y": 256, "z": 256}
  1267. try:
  1268. with zipfile.ZipFile(zf_path, "r") as zf:
  1269. names = zf.namelist()
  1270. # Check for 3D model - look for actual mesh data
  1271. for name in names:
  1272. if name.endswith(".model"):
  1273. try:
  1274. content = zf.read(name).decode("utf-8")
  1275. if "<vertex" in content or "<mesh" in content:
  1276. found_mesh = True
  1277. break
  1278. except Exception:
  1279. pass
  1280. # Extract filament colors from project_settings.config
  1281. if "Metadata/project_settings.config" in names:
  1282. try:
  1283. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1284. config_data = json.loads(config_content)
  1285. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1286. printable_area = config_data.get("printable_area", [])
  1287. if printable_area and len(printable_area) >= 3:
  1288. max_x = 0
  1289. max_y = 0
  1290. for coord in printable_area:
  1291. if "x" in coord:
  1292. parts = coord.split("x")
  1293. if len(parts) == 2:
  1294. try:
  1295. x, y = int(parts[0]), int(parts[1])
  1296. max_x = max(max_x, x)
  1297. max_y = max(max_y, y)
  1298. except ValueError:
  1299. pass
  1300. if max_x > 0 and max_y > 0:
  1301. volume["x"] = max_x
  1302. volume["y"] = max_y
  1303. # Parse printable_height
  1304. printable_height = config_data.get("printable_height")
  1305. if printable_height:
  1306. try:
  1307. volume["z"] = int(printable_height)
  1308. except (ValueError, TypeError):
  1309. pass
  1310. # Extract filament colors
  1311. raw_colors = config_data.get("filament_colour", [])
  1312. if raw_colors:
  1313. for color in raw_colors:
  1314. if color and isinstance(color, str):
  1315. colors.append(color)
  1316. except Exception:
  1317. pass
  1318. except zipfile.BadZipFile:
  1319. pass
  1320. return found_mesh, colors, volume
  1321. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  1322. if has_source and source_path:
  1323. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  1324. if source_has_mesh:
  1325. has_model = True
  1326. if source_colors:
  1327. filament_colors = source_colors
  1328. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  1329. build_volume = source_volume
  1330. try:
  1331. with zipfile.ZipFile(file_path, "r") as zf:
  1332. names = zf.namelist()
  1333. # Check for G-code in the sliced file
  1334. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1335. # Check for 3D model in sliced file (fallback if no source)
  1336. if not has_model:
  1337. for name in names:
  1338. if name.endswith(".model"):
  1339. try:
  1340. content = zf.read(name).decode("utf-8")
  1341. if "<vertex" in content or "<mesh" in content:
  1342. has_model = True
  1343. break
  1344. except Exception:
  1345. pass
  1346. # Extract filament colors from slice_info.config (for gcode preview)
  1347. # These are the actual filaments used in the print, indexed by tool/extruder
  1348. slice_colors: list[str] = []
  1349. if "Metadata/slice_info.config" in names:
  1350. try:
  1351. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1352. root = ET.fromstring(slice_content)
  1353. filaments = root.findall(".//filament")
  1354. filament_map: dict[int, str] = {}
  1355. for f in filaments:
  1356. fid = f.get("id")
  1357. fcolor = f.get("color")
  1358. used_g = f.get("used_g", "0")
  1359. try:
  1360. used_amount = float(used_g)
  1361. except (ValueError, TypeError):
  1362. used_amount = 0
  1363. if fid is not None and fcolor:
  1364. try:
  1365. tool_id = int(fid) - 1
  1366. if tool_id >= 0 and used_amount > 0:
  1367. filament_map[tool_id] = fcolor
  1368. except ValueError:
  1369. pass
  1370. if filament_map:
  1371. max_tool = max(filament_map.keys())
  1372. for i in range(max_tool + 1):
  1373. slice_colors.append(filament_map.get(i, "#00AE42"))
  1374. except Exception:
  1375. pass
  1376. # Use slice_info colors if we don't have colors from source yet
  1377. if not filament_colors and slice_colors:
  1378. filament_colors = slice_colors
  1379. # Extract build volume from sliced file if not already set from source
  1380. if build_volume["x"] == 256 and build_volume["y"] == 256:
  1381. if "Metadata/project_settings.config" in names:
  1382. try:
  1383. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1384. config_data = json.loads(config_content)
  1385. printable_area = config_data.get("printable_area", [])
  1386. if printable_area and len(printable_area) >= 3:
  1387. max_x = 0
  1388. max_y = 0
  1389. for coord in printable_area:
  1390. if "x" in coord:
  1391. parts = coord.split("x")
  1392. if len(parts) == 2:
  1393. try:
  1394. x, y = int(parts[0]), int(parts[1])
  1395. max_x = max(max_x, x)
  1396. max_y = max(max_y, y)
  1397. except ValueError:
  1398. pass
  1399. if max_x > 0 and max_y > 0:
  1400. build_volume["x"] = max_x
  1401. build_volume["y"] = max_y
  1402. printable_height = config_data.get("printable_height")
  1403. if printable_height:
  1404. try:
  1405. build_volume["z"] = int(printable_height)
  1406. except (ValueError, TypeError):
  1407. pass
  1408. # Fallback colors from project_settings if still empty
  1409. if not filament_colors:
  1410. raw_colors = config_data.get("filament_colour", [])
  1411. if raw_colors:
  1412. for color in raw_colors:
  1413. if color and isinstance(color, str):
  1414. filament_colors.append(color)
  1415. except Exception:
  1416. pass
  1417. except zipfile.BadZipFile:
  1418. raise HTTPException(400, "Invalid 3MF file")
  1419. return {
  1420. "has_model": has_model,
  1421. "has_gcode": has_gcode,
  1422. "has_source": has_source,
  1423. "build_volume": build_volume,
  1424. "filament_colors": filament_colors,
  1425. }
  1426. @router.get("/{archive_id}/gcode")
  1427. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  1428. """Extract and return G-code from the 3MF file."""
  1429. service = ArchiveService(db)
  1430. archive = await service.get_archive(archive_id)
  1431. if not archive:
  1432. raise HTTPException(404, "Archive not found")
  1433. file_path = settings.base_dir / archive.file_path
  1434. if not file_path.exists():
  1435. raise HTTPException(404, "File not found")
  1436. try:
  1437. with zipfile.ZipFile(file_path, "r") as zf:
  1438. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1439. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1440. if not gcode_files:
  1441. raise HTTPException(
  1442. 404,
  1443. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1444. )
  1445. # Get the first plate's G-code (usually plate_1.gcode)
  1446. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1447. return Response(content=gcode_content, media_type="text/plain")
  1448. except zipfile.BadZipFile:
  1449. raise HTTPException(400, "Invalid 3MF file")
  1450. except HTTPException:
  1451. raise
  1452. except Exception as e:
  1453. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1454. @router.get("/{archive_id}/plate-preview")
  1455. async def get_plate_preview(archive_id: int, db: AsyncSession = Depends(get_db)):
  1456. """Get the plate preview image from the 3MF file.
  1457. Returns the slicer-generated plate thumbnail which shows the model
  1458. with correct colors and positioning.
  1459. """
  1460. service = ArchiveService(db)
  1461. archive = await service.get_archive(archive_id)
  1462. if not archive:
  1463. raise HTTPException(404, "Archive not found")
  1464. file_path = settings.base_dir / archive.file_path
  1465. if not file_path.exists():
  1466. raise HTTPException(404, "File not found")
  1467. try:
  1468. with zipfile.ZipFile(file_path, "r") as zf:
  1469. names = zf.namelist()
  1470. # Try to find plate preview images in order of preference
  1471. # First look for the specific plate being printed (check slice_info for plate index)
  1472. plate_num = 1
  1473. if "Metadata/slice_info.config" in names:
  1474. try:
  1475. import xml.etree.ElementTree as ET
  1476. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1477. root = ET.fromstring(slice_content)
  1478. plate_elem = root.find(".//plate/metadata[@key='index']")
  1479. if plate_elem is not None:
  1480. plate_num = int(plate_elem.get("value", "1"))
  1481. except Exception:
  1482. pass
  1483. # Try plate-specific image first, then fall back to plate_1
  1484. preview_paths = [
  1485. f"Metadata/plate_{plate_num}.png",
  1486. "Metadata/plate_1.png",
  1487. "Metadata/thumbnail.png",
  1488. ]
  1489. for preview_path in preview_paths:
  1490. if preview_path in names:
  1491. image_data = zf.read(preview_path)
  1492. return Response(content=image_data, media_type="image/png")
  1493. # If no plate image, try any PNG in Metadata
  1494. for name in names:
  1495. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  1496. image_data = zf.read(name)
  1497. return Response(content=image_data, media_type="image/png")
  1498. raise HTTPException(404, "No plate preview found in 3MF file")
  1499. except zipfile.BadZipFile:
  1500. raise HTTPException(400, "Invalid 3MF file")
  1501. except HTTPException:
  1502. raise
  1503. except Exception as e:
  1504. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  1505. @router.post("/upload")
  1506. async def upload_archive(
  1507. file: UploadFile = File(...),
  1508. printer_id: int | None = None,
  1509. db: AsyncSession = Depends(get_db),
  1510. ):
  1511. """Manually upload a 3MF file to archive."""
  1512. if not file.filename or not file.filename.endswith(".3mf"):
  1513. raise HTTPException(400, "File must be a .3mf file")
  1514. # Save uploaded file temporarily
  1515. temp_path = settings.archive_dir / "temp" / file.filename
  1516. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1517. try:
  1518. content = await file.read()
  1519. temp_path.write_bytes(content)
  1520. service = ArchiveService(db)
  1521. archive = await service.archive_print(
  1522. printer_id=printer_id,
  1523. source_file=temp_path,
  1524. )
  1525. if not archive:
  1526. raise HTTPException(400, "Failed to archive file")
  1527. return ArchiveResponse.model_validate(archive)
  1528. finally:
  1529. if temp_path.exists():
  1530. temp_path.unlink()
  1531. @router.post("/upload-bulk")
  1532. async def upload_archives_bulk(
  1533. files: list[UploadFile] = File(...),
  1534. printer_id: int | None = None,
  1535. db: AsyncSession = Depends(get_db),
  1536. ):
  1537. """Bulk upload multiple 3MF files to archive."""
  1538. results = []
  1539. errors = []
  1540. for file in files:
  1541. if not file.filename or not file.filename.endswith(".3mf"):
  1542. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1543. continue
  1544. temp_path = settings.archive_dir / "temp" / file.filename
  1545. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1546. try:
  1547. content = await file.read()
  1548. temp_path.write_bytes(content)
  1549. service = ArchiveService(db)
  1550. archive = await service.archive_print(
  1551. printer_id=printer_id,
  1552. source_file=temp_path,
  1553. )
  1554. if archive:
  1555. results.append(
  1556. {
  1557. "filename": file.filename,
  1558. "id": archive.id,
  1559. "status": "success",
  1560. }
  1561. )
  1562. else:
  1563. errors.append({"filename": file.filename, "error": "Failed to process"})
  1564. except Exception as e:
  1565. errors.append({"filename": file.filename, "error": str(e)})
  1566. finally:
  1567. if temp_path.exists():
  1568. temp_path.unlink()
  1569. return {
  1570. "uploaded": len(results),
  1571. "failed": len(errors),
  1572. "results": results,
  1573. "errors": errors,
  1574. }
  1575. @router.get("/{archive_id}/filament-requirements")
  1576. async def get_filament_requirements(
  1577. archive_id: int,
  1578. db: AsyncSession = Depends(get_db),
  1579. ):
  1580. """Get filament requirements from the archived 3MF file.
  1581. Returns the filaments used in this print with their slot IDs, types, colors,
  1582. and usage amounts. This can be compared with current AMS state before reprinting.
  1583. """
  1584. import xml.etree.ElementTree as ET
  1585. service = ArchiveService(db)
  1586. archive = await service.get_archive(archive_id)
  1587. if not archive:
  1588. raise HTTPException(404, "Archive not found")
  1589. file_path = settings.base_dir / archive.file_path
  1590. if not file_path.exists():
  1591. raise HTTPException(404, "Archive file not found")
  1592. filaments = []
  1593. try:
  1594. with zipfile.ZipFile(file_path, "r") as zf:
  1595. # Parse slice_info.config for filament requirements
  1596. if "Metadata/slice_info.config" in zf.namelist():
  1597. content = zf.read("Metadata/slice_info.config").decode()
  1598. root = ET.fromstring(content)
  1599. # Extract filament elements
  1600. # Format: <filament id="1" type="PLA" color="#FFFFFF" used_g="100" used_m="10" />
  1601. for filament_elem in root.findall(".//filament"):
  1602. filament_id = filament_elem.get("id")
  1603. filament_type = filament_elem.get("type", "")
  1604. filament_color = filament_elem.get("color", "")
  1605. used_g = filament_elem.get("used_g", "0")
  1606. used_m = filament_elem.get("used_m", "0")
  1607. # Only include filaments that are actually used
  1608. try:
  1609. used_grams = float(used_g)
  1610. except (ValueError, TypeError):
  1611. used_grams = 0
  1612. if used_grams > 0 and filament_id:
  1613. filaments.append(
  1614. {
  1615. "slot_id": int(filament_id),
  1616. "type": filament_type,
  1617. "color": filament_color,
  1618. "used_grams": round(used_grams, 1),
  1619. "used_meters": float(used_m) if used_m else 0,
  1620. }
  1621. )
  1622. # Sort by slot ID
  1623. filaments.sort(key=lambda x: x["slot_id"])
  1624. except Exception as e:
  1625. logger.warning(f"Failed to parse filament requirements from archive {archive_id}: {e}")
  1626. return {
  1627. "archive_id": archive_id,
  1628. "filename": archive.filename,
  1629. "filaments": filaments,
  1630. }
  1631. @router.post("/{archive_id}/reprint")
  1632. async def reprint_archive(
  1633. archive_id: int,
  1634. printer_id: int,
  1635. body: ReprintRequest | None = None,
  1636. db: AsyncSession = Depends(get_db),
  1637. ):
  1638. """Send an archived 3MF file to a printer and start printing."""
  1639. from backend.app.main import register_expected_print
  1640. from backend.app.models.printer import Printer
  1641. from backend.app.services.bambu_ftp import upload_file_async
  1642. from backend.app.services.printer_manager import printer_manager
  1643. # Use defaults if no body provided
  1644. if body is None:
  1645. body = ReprintRequest()
  1646. # Get archive
  1647. service = ArchiveService(db)
  1648. archive = await service.get_archive(archive_id)
  1649. if not archive:
  1650. raise HTTPException(404, "Archive not found")
  1651. # Get printer
  1652. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1653. printer = result.scalar_one_or_none()
  1654. if not printer:
  1655. raise HTTPException(404, "Printer not found")
  1656. # Check printer is connected
  1657. if not printer_manager.is_connected(printer_id):
  1658. raise HTTPException(400, "Printer is not connected")
  1659. # Get the sliced 3MF file path
  1660. file_path = settings.base_dir / archive.file_path
  1661. if not file_path.exists():
  1662. raise HTTPException(404, "Archive file not found")
  1663. # Upload file to printer via FTP
  1664. from backend.app.services.bambu_ftp import delete_file_async
  1665. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1666. # The printer might reject filenames with unusual extensions
  1667. base_name = archive.filename
  1668. if base_name.endswith(".gcode.3mf"):
  1669. base_name = base_name[:-10] # Remove .gcode.3mf
  1670. elif base_name.endswith(".3mf"):
  1671. base_name = base_name[:-4] # Remove .3mf
  1672. remote_filename = f"{base_name}.3mf"
  1673. remote_path = f"/{remote_filename}"
  1674. # Delete existing file if present (avoids 553 error)
  1675. await delete_file_async(
  1676. printer.ip_address,
  1677. printer.access_code,
  1678. remote_path,
  1679. )
  1680. uploaded = await upload_file_async(
  1681. printer.ip_address,
  1682. printer.access_code,
  1683. file_path,
  1684. remote_path,
  1685. )
  1686. if not uploaded:
  1687. raise HTTPException(500, "Failed to upload file to printer")
  1688. # Register this as an expected print so we don't create a duplicate archive
  1689. register_expected_print(printer_id, remote_filename, archive_id)
  1690. # Detect plate ID from 3MF file
  1691. plate_id = 1
  1692. try:
  1693. with zipfile.ZipFile(file_path, "r") as zf:
  1694. for name in zf.namelist():
  1695. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1696. # Extract plate number from "Metadata/plate_X.gcode"
  1697. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1698. plate_id = int(plate_str)
  1699. break
  1700. except Exception:
  1701. pass # Default to plate 1 if detection fails
  1702. logger.info(
  1703. f"Reprint archive {archive_id}: plate_id={plate_id}, "
  1704. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}, "
  1705. f"flow_cali={body.flow_cali}, vibration_cali={body.vibration_cali}, "
  1706. f"layer_inspect={body.layer_inspect}, timelapse={body.timelapse}"
  1707. )
  1708. # Start the print with options
  1709. started = printer_manager.start_print(
  1710. printer_id,
  1711. remote_filename,
  1712. plate_id,
  1713. ams_mapping=body.ams_mapping,
  1714. timelapse=body.timelapse,
  1715. bed_levelling=body.bed_levelling,
  1716. flow_cali=body.flow_cali,
  1717. vibration_cali=body.vibration_cali,
  1718. layer_inspect=body.layer_inspect,
  1719. use_ams=body.use_ams,
  1720. )
  1721. if not started:
  1722. raise HTTPException(500, "Failed to start print")
  1723. return {
  1724. "status": "printing",
  1725. "printer_id": printer_id,
  1726. "archive_id": archive_id,
  1727. "filename": archive.filename,
  1728. }
  1729. # =============================================================================
  1730. # Project Page API
  1731. # =============================================================================
  1732. @router.get("/{archive_id}/project-page")
  1733. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  1734. """Get the project page data from the 3MF file."""
  1735. from backend.app.schemas.archive import ProjectPageResponse
  1736. from backend.app.services.archive import ProjectPageParser
  1737. service = ArchiveService(db)
  1738. archive = await service.get_archive(archive_id)
  1739. if not archive:
  1740. raise HTTPException(404, "Archive not found")
  1741. file_path = settings.base_dir / archive.file_path
  1742. if not file_path.exists():
  1743. raise HTTPException(404, "Archive file not found")
  1744. parser = ProjectPageParser(file_path)
  1745. data = parser.parse(archive_id)
  1746. return ProjectPageResponse(**data)
  1747. @router.patch("/{archive_id}/project-page")
  1748. async def update_project_page(
  1749. archive_id: int,
  1750. update_data: dict,
  1751. db: AsyncSession = Depends(get_db),
  1752. ):
  1753. """Update project page metadata in the 3MF file."""
  1754. from backend.app.services.archive import ProjectPageParser
  1755. service = ArchiveService(db)
  1756. archive = await service.get_archive(archive_id)
  1757. if not archive:
  1758. raise HTTPException(404, "Archive not found")
  1759. file_path = settings.base_dir / archive.file_path
  1760. if not file_path.exists():
  1761. raise HTTPException(404, "Archive file not found")
  1762. parser = ProjectPageParser(file_path)
  1763. success = parser.update_metadata(update_data)
  1764. if not success:
  1765. raise HTTPException(500, "Failed to update project page")
  1766. # Return updated data
  1767. data = parser.parse(archive_id)
  1768. return data
  1769. @router.get("/{archive_id}/project-image/{image_path:path}")
  1770. async def get_project_image(
  1771. archive_id: int,
  1772. image_path: str,
  1773. db: AsyncSession = Depends(get_db),
  1774. ):
  1775. """Get an image from the 3MF project page."""
  1776. from backend.app.services.archive import ProjectPageParser
  1777. service = ArchiveService(db)
  1778. archive = await service.get_archive(archive_id)
  1779. if not archive:
  1780. raise HTTPException(404, "Archive not found")
  1781. file_path = settings.base_dir / archive.file_path
  1782. if not file_path.exists():
  1783. raise HTTPException(404, "Archive file not found")
  1784. parser = ProjectPageParser(file_path)
  1785. result = parser.get_image(image_path)
  1786. if not result:
  1787. raise HTTPException(404, "Image not found in 3MF file")
  1788. image_data, content_type = result
  1789. return Response(
  1790. content=image_data,
  1791. media_type=content_type,
  1792. headers={"Cache-Control": "max-age=3600"},
  1793. )
  1794. # =============================================================================
  1795. # Source 3MF API (Original Project Files)
  1796. # =============================================================================
  1797. @router.post("/{archive_id}/source")
  1798. async def upload_source_3mf(
  1799. archive_id: int,
  1800. file: UploadFile = File(...),
  1801. db: AsyncSession = Depends(get_db),
  1802. ):
  1803. """Upload the original source 3MF project file for an archive."""
  1804. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1805. archive = result.scalar_one_or_none()
  1806. if not archive:
  1807. raise HTTPException(404, "Archive not found")
  1808. if not file.filename or not file.filename.endswith(".3mf"):
  1809. raise HTTPException(400, "File must be a .3mf file")
  1810. # Get archive directory and create source subdirectory
  1811. file_path = settings.base_dir / archive.file_path
  1812. archive_dir = file_path.parent
  1813. source_dir = archive_dir / "source"
  1814. source_dir.mkdir(exist_ok=True)
  1815. # Delete old source file if exists
  1816. if archive.source_3mf_path:
  1817. old_source_path = settings.base_dir / archive.source_3mf_path
  1818. if old_source_path.exists():
  1819. old_source_path.unlink()
  1820. # Save the source 3MF file - preserve original filename
  1821. source_filename = file.filename
  1822. source_path = source_dir / source_filename
  1823. content = await file.read()
  1824. source_path.write_bytes(content)
  1825. # Update archive with source path (relative to base_dir)
  1826. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  1827. await db.commit()
  1828. await db.refresh(archive)
  1829. return {
  1830. "status": "uploaded",
  1831. "source_3mf_path": archive.source_3mf_path,
  1832. "filename": source_filename,
  1833. }
  1834. @router.get("/{archive_id}/source")
  1835. async def download_source_3mf(
  1836. archive_id: int,
  1837. db: AsyncSession = Depends(get_db),
  1838. ):
  1839. """Download the source 3MF project file."""
  1840. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1841. archive = result.scalar_one_or_none()
  1842. if not archive:
  1843. raise HTTPException(404, "Archive not found")
  1844. if not archive.source_3mf_path:
  1845. raise HTTPException(404, "No source 3MF attached to this archive")
  1846. source_path = settings.base_dir / archive.source_3mf_path
  1847. if not source_path.exists():
  1848. raise HTTPException(404, "Source 3MF file not found on disk")
  1849. # Use the actual filename from the path
  1850. filename = source_path.name
  1851. return FileResponse(
  1852. path=source_path,
  1853. filename=filename,
  1854. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1855. )
  1856. @router.get("/{archive_id}/source/{filename}")
  1857. async def download_source_3mf_for_slicer(
  1858. archive_id: int,
  1859. filename: str,
  1860. db: AsyncSession = Depends(get_db),
  1861. ):
  1862. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  1863. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1864. archive = result.scalar_one_or_none()
  1865. if not archive:
  1866. raise HTTPException(404, "Archive not found")
  1867. if not archive.source_3mf_path:
  1868. raise HTTPException(404, "No source 3MF attached to this archive")
  1869. source_path = settings.base_dir / archive.source_3mf_path
  1870. if not source_path.exists():
  1871. raise HTTPException(404, "Source 3MF file not found on disk")
  1872. return FileResponse(
  1873. path=source_path,
  1874. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  1875. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1876. )
  1877. @router.post("/upload-source")
  1878. async def upload_source_3mf_by_name(
  1879. file: UploadFile = File(...),
  1880. print_name: str = Query(None, description="Match archive by print name"),
  1881. db: AsyncSession = Depends(get_db),
  1882. ):
  1883. """Upload source 3MF and match to archive by print name.
  1884. This endpoint is designed for slicer post-processing scripts.
  1885. It finds the most recent archive matching the print name and attaches the source.
  1886. """
  1887. if not file.filename or not file.filename.endswith(".3mf"):
  1888. raise HTTPException(400, "File must be a .3mf file")
  1889. # Derive print name from filename if not provided
  1890. if not print_name:
  1891. # Remove .3mf extension and common suffixes
  1892. print_name = file.filename.rsplit(".3mf", 1)[0]
  1893. # Remove _source suffix if present
  1894. if print_name.endswith("_source"):
  1895. print_name = print_name[:-7]
  1896. # Find matching archive - try exact match first, then fuzzy
  1897. result = await db.execute(
  1898. select(PrintArchive)
  1899. .where(PrintArchive.print_name == print_name)
  1900. .order_by(PrintArchive.created_at.desc())
  1901. .limit(1)
  1902. )
  1903. archive = result.scalar_one_or_none()
  1904. if not archive:
  1905. # Try matching filename without .gcode.3mf
  1906. result = await db.execute(
  1907. select(PrintArchive)
  1908. .where(PrintArchive.filename.like(f"{print_name}%"))
  1909. .order_by(PrintArchive.created_at.desc())
  1910. .limit(1)
  1911. )
  1912. archive = result.scalar_one_or_none()
  1913. if not archive:
  1914. # Try case-insensitive partial match on print_name
  1915. result = await db.execute(
  1916. select(PrintArchive)
  1917. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  1918. .order_by(PrintArchive.created_at.desc())
  1919. .limit(1)
  1920. )
  1921. archive = result.scalar_one_or_none()
  1922. if not archive:
  1923. raise HTTPException(404, f"No archive found matching '{print_name}'")
  1924. # Get archive directory and create source subdirectory
  1925. file_path = settings.base_dir / archive.file_path
  1926. archive_dir = file_path.parent
  1927. source_dir = archive_dir / "source"
  1928. source_dir.mkdir(exist_ok=True)
  1929. # Delete old source file if exists
  1930. if archive.source_3mf_path:
  1931. old_source_path = settings.base_dir / archive.source_3mf_path
  1932. if old_source_path.exists():
  1933. old_source_path.unlink()
  1934. # Save the source 3MF file - preserve original filename
  1935. source_filename = file.filename
  1936. source_path = source_dir / source_filename
  1937. content = await file.read()
  1938. source_path.write_bytes(content)
  1939. # Update archive with source path
  1940. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  1941. await db.commit()
  1942. await db.refresh(archive)
  1943. return {
  1944. "status": "uploaded",
  1945. "archive_id": archive.id,
  1946. "archive_name": archive.print_name or archive.filename,
  1947. "source_3mf_path": archive.source_3mf_path,
  1948. "filename": source_filename,
  1949. }
  1950. @router.delete("/{archive_id}/source")
  1951. async def delete_source_3mf(
  1952. archive_id: int,
  1953. db: AsyncSession = Depends(get_db),
  1954. ):
  1955. """Delete the source 3MF project file from an archive."""
  1956. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1957. archive = result.scalar_one_or_none()
  1958. if not archive:
  1959. raise HTTPException(404, "Archive not found")
  1960. if not archive.source_3mf_path:
  1961. raise HTTPException(404, "No source 3MF attached to this archive")
  1962. # Delete the file
  1963. source_path = settings.base_dir / archive.source_3mf_path
  1964. if source_path.exists():
  1965. source_path.unlink()
  1966. # Clear the path in database
  1967. archive.source_3mf_path = None
  1968. await db.commit()
  1969. return {"status": "deleted"}