traceforge-pcb 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. traceforge/__init__.py +3 -0
  2. traceforge/__main__.py +3 -0
  3. traceforge/acp_server.py +570 -0
  4. traceforge/agent.py +680 -0
  5. traceforge/altium/__init__.py +6 -0
  6. traceforge/altium/cfb.py +70 -0
  7. traceforge/altium/cli.py +60 -0
  8. traceforge/altium/model.py +163 -0
  9. traceforge/altium/outputs.py +24 -0
  10. traceforge/altium/pcb.py +301 -0
  11. traceforge/altium/project.py +328 -0
  12. traceforge/altium/schematic.py +400 -0
  13. traceforge/altium/tools.py +166 -0
  14. traceforge/approval.py +219 -0
  15. traceforge/attachments.py +346 -0
  16. traceforge/background.py +253 -0
  17. traceforge/bench/__init__.py +5 -0
  18. traceforge/bench/adapters.py +337 -0
  19. traceforge/bench/checks.py +410 -0
  20. traceforge/bench/cli.py +121 -0
  21. traceforge/bench/design.py +439 -0
  22. traceforge/bench/kicad.py +99 -0
  23. traceforge/bench/partscheck.py +159 -0
  24. traceforge/bench/review.py +100 -0
  25. traceforge/bench/runner.py +226 -0
  26. traceforge/bench/score.py +204 -0
  27. traceforge/bench/tasks.py +102 -0
  28. traceforge/chat.py +1185 -0
  29. traceforge/checks.py +328 -0
  30. traceforge/checks_sides.py +118 -0
  31. traceforge/cli.py +2224 -0
  32. traceforge/clipboard.py +107 -0
  33. traceforge/config.py +299 -0
  34. traceforge/context.py +276 -0
  35. traceforge/design/__init__.py +1 -0
  36. traceforge/design/constraints.py +397 -0
  37. traceforge/design/generate.py +1789 -0
  38. traceforge/design/outline.py +905 -0
  39. traceforge/design/schematic_layout.py +932 -0
  40. traceforge/design/schematic_lint.py +329 -0
  41. traceforge/design/schematic_route.py +207 -0
  42. traceforge/design/sheets.py +854 -0
  43. traceforge/design/sides.py +328 -0
  44. traceforge/design/spec.py +462 -0
  45. traceforge/design/specsheet.py +2351 -0
  46. traceforge/design/specsheet_render.py +183 -0
  47. traceforge/desktop/__init__.py +109 -0
  48. traceforge/desktop/keys.py +90 -0
  49. traceforge/desktop/project.py +443 -0
  50. traceforge/desktop/review.py +20 -0
  51. traceforge/desktop/server.py +1277 -0
  52. traceforge/desktop/static/app.css +223 -0
  53. traceforge/desktop/static/app.js +683 -0
  54. traceforge/desktop/static/highlight.js +77 -0
  55. traceforge/desktop/static/index.html +89 -0
  56. traceforge/desktop/static/md.js +90 -0
  57. traceforge/desktop/static/viewer.js +213 -0
  58. traceforge/desktop/symbols.py +212 -0
  59. traceforge/desktop/update.py +65 -0
  60. traceforge/diagnostics.py +67 -0
  61. traceforge/errata.py +219 -0
  62. traceforge/fab.py +108 -0
  63. traceforge/fab_layers.py +44 -0
  64. traceforge/features/__init__.py +6 -0
  65. traceforge/features/candidates.py +117 -0
  66. traceforge/features/cli.py +200 -0
  67. traceforge/features/package.py +433 -0
  68. traceforge/features/revdiff.py +224 -0
  69. traceforge/features/sarif.py +145 -0
  70. traceforge/features/viewer.py +265 -0
  71. traceforge/firmware/__init__.py +3 -0
  72. traceforge/firmware/cli.py +174 -0
  73. traceforge/firmware/drivers.py +372 -0
  74. traceforge/firmware/drivers_data.py +256 -0
  75. traceforge/firmware/mcus.py +177 -0
  76. traceforge/firmware/netlist.py +55 -0
  77. traceforge/firmware/pinmap.py +296 -0
  78. traceforge/firmware/scaffold.py +466 -0
  79. traceforge/firmware/toolchain.py +262 -0
  80. traceforge/hooks.py +237 -0
  81. traceforge/kicad/__init__.py +0 -0
  82. traceforge/kicad/cli.py +519 -0
  83. traceforge/kicad/diffpair.py +174 -0
  84. traceforge/kicad/edgegeom.py +191 -0
  85. traceforge/kicad/edit.py +405 -0
  86. traceforge/kicad/escape.py +1410 -0
  87. traceforge/kicad/formats.py +1073 -0
  88. traceforge/kicad/impedance.py +320 -0
  89. traceforge/kicad/install.py +75 -0
  90. traceforge/kicad/libraries.py +490 -0
  91. traceforge/kicad/models3d.py +942 -0
  92. traceforge/kicad/outputs.py +81 -0
  93. traceforge/kicad/pcb.py +787 -0
  94. traceforge/kicad/planes.py +1242 -0
  95. traceforge/kicad/project.py +136 -0
  96. traceforge/kicad/route.py +2698 -0
  97. traceforge/kicad/routegeom.py +164 -0
  98. traceforge/kicad/schematic.py +268 -0
  99. traceforge/kicad/sides.py +34 -0
  100. traceforge/kicad/stackup.py +424 -0
  101. traceforge/kicad_plugin/__init__.py +12 -0
  102. traceforge/kicad_plugin/actions.py +92 -0
  103. traceforge/kicad_plugin/cli.py +66 -0
  104. traceforge/kicad_plugin/client.py +86 -0
  105. traceforge/kicad_plugin/context.py +257 -0
  106. traceforge/kicad_plugin/discovery.py +81 -0
  107. traceforge/kicad_plugin/install.py +203 -0
  108. traceforge/kicad_plugin/overlay.py +60 -0
  109. traceforge/kicad_plugin/payload/action_plugin.py +65 -0
  110. traceforge/kicad_plugin/payload/ipc_main.py +42 -0
  111. traceforge/kicad_plugin/payload/plugin.json +90 -0
  112. traceforge/kicad_plugin/payload/requirements.txt +1 -0
  113. traceforge/kicad_plugin/views.py +202 -0
  114. traceforge/langchain.py +57 -0
  115. traceforge/local.py +580 -0
  116. traceforge/mcp_server.py +304 -0
  117. traceforge/models.py +310 -0
  118. traceforge/next_steps.py +110 -0
  119. traceforge/parts/__init__.py +52 -0
  120. traceforge/parts/alternates.py +488 -0
  121. traceforge/parts/bom.py +423 -0
  122. traceforge/parts/brief.py +705 -0
  123. traceforge/parts/catalog.py +297 -0
  124. traceforge/parts/cli_sourcing.py +156 -0
  125. traceforge/parts/data/duty_rates.yaml +37 -0
  126. traceforge/parts/data/hs_codes.yaml +103 -0
  127. traceforge/parts/datasheet.py +278 -0
  128. traceforge/parts/fx.py +100 -0
  129. traceforge/parts/model.py +185 -0
  130. traceforge/parts/net.py +187 -0
  131. traceforge/parts/offers.py +46 -0
  132. traceforge/parts/packages.py +397 -0
  133. traceforge/parts/pinout.py +714 -0
  134. traceforge/parts/providers/__init__.py +17 -0
  135. traceforge/parts/providers/base.py +100 -0
  136. traceforge/parts/providers/jlc.py +364 -0
  137. traceforge/parts/providers/keyed.py +661 -0
  138. traceforge/parts/report.py +508 -0
  139. traceforge/parts/supply.py +330 -0
  140. traceforge/parts/verify.py +455 -0
  141. traceforge/parts/web.py +575 -0
  142. traceforge/plans.py +70 -0
  143. traceforge/preferences.py +127 -0
  144. traceforge/prices.py +130 -0
  145. traceforge/prices.yaml +28 -0
  146. traceforge/prompts/__init__.py +54 -0
  147. traceforge/prompts/system.md +103 -0
  148. traceforge/providers.py +764 -0
  149. traceforge/remote/__init__.py +33 -0
  150. traceforge/remote/client.py +422 -0
  151. traceforge/remote/oidc.py +240 -0
  152. traceforge/remote/orgs.py +510 -0
  153. traceforge/remote/server.py +690 -0
  154. traceforge/remote/store.py +100 -0
  155. traceforge/review_changes.py +187 -0
  156. traceforge/routing.py +99 -0
  157. traceforge/runtime.py +435 -0
  158. traceforge/sessions.py +324 -0
  159. traceforge/sexpr.py +279 -0
  160. traceforge/sim/__init__.py +17 -0
  161. traceforge/sim/acmath.py +234 -0
  162. traceforge/sim/circuit.py +499 -0
  163. traceforge/sim/cli.py +162 -0
  164. traceforge/sim/engine.py +172 -0
  165. traceforge/sim/ltspice.py +175 -0
  166. traceforge/sim/measure.py +123 -0
  167. traceforge/sim/models.py +76 -0
  168. traceforge/sim/project.py +218 -0
  169. traceforge/sim/rawfile.py +123 -0
  170. traceforge/sim/results.py +298 -0
  171. traceforge/sim/tune.py +172 -0
  172. traceforge/skill_commands.py +165 -0
  173. traceforge/skill_library/circuit-simulation/SKILL.md +30 -0
  174. traceforge/skill_library/compliance-review/SKILL.md +51 -0
  175. traceforge/skill_library/design-review/SKILL.md +47 -0
  176. traceforge/skill_library/errata-hunt/SKILL.md +30 -0
  177. traceforge/skill_library/firmware/SKILL.md +26 -0
  178. traceforge/skill_library/power-budget/SKILL.md +27 -0
  179. traceforge/skill_library/release-package/SKILL.md +29 -0
  180. traceforge/skill_library/sourcing-brief/SKILL.md +24 -0
  181. traceforge/skill_library/thermal-review/SKILL.md +15 -0
  182. traceforge/skills.py +131 -0
  183. traceforge/thermal.py +557 -0
  184. traceforge/tools/__init__.py +48 -0
  185. traceforge/tools/agent_tools.py +213 -0
  186. traceforge/tools/base.py +303 -0
  187. traceforge/tools/batch.py +155 -0
  188. traceforge/tools/connections.py +245 -0
  189. traceforge/tools/files.py +777 -0
  190. traceforge/tools/firmware_tools.py +218 -0
  191. traceforge/tools/kicad_tools.py +1072 -0
  192. traceforge/tools/models3d_tools.py +141 -0
  193. traceforge/tools/parts_tools.py +473 -0
  194. traceforge/tools/processes.py +246 -0
  195. traceforge/tools/review_tools.py +178 -0
  196. traceforge/tools/sim_tools.py +230 -0
  197. traceforge/tui.py +620 -0
  198. traceforge/updates.py +124 -0
  199. traceforge/validate/__init__.py +77 -0
  200. traceforge/validate/builtins.py +1091 -0
  201. traceforge/validate/circuits.py +1240 -0
  202. traceforge/validate/config.py +410 -0
  203. traceforge/validate/default.yaml +113 -0
  204. traceforge/validate/design.py +191 -0
  205. traceforge/validate/explain.py +112 -0
  206. traceforge/validate/grounding.py +169 -0
  207. traceforge/validate/ipc2221.py +350 -0
  208. traceforge/validate/multilayer.py +805 -0
  209. traceforge/validate/netmodel.py +261 -0
  210. traceforge/validate/partcheck.py +472 -0
  211. traceforge/validate/report.py +280 -0
  212. traceforge/validate/review.py +322 -0
  213. traceforge/validate/runner.py +662 -0
  214. traceforge/workspace.py +171 -0
  215. traceforge_pcb-1.0.0.dist-info/METADATA +463 -0
  216. traceforge_pcb-1.0.0.dist-info/RECORD +219 -0
  217. traceforge_pcb-1.0.0.dist-info/WHEEL +4 -0
  218. traceforge_pcb-1.0.0.dist-info/entry_points.txt +2 -0
  219. traceforge_pcb-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,297 @@
1
+ """Combine part providers behind one cached lookup/search API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import time
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from dataclasses import dataclass, field
9
+
10
+ from traceforge.parts.model import PartInfo, is_lcsc_code, normalize_lcsc
11
+ from traceforge.parts.net import Cache, Net, Offline, ProviderError, default_net
12
+ from traceforge.parts.offers import ensure_offers
13
+ from traceforge.parts.packages import parse_catalog_package
14
+ from traceforge.parts.providers.base import NotSupported, PartProvider, SearchQuery, norm_mpn
15
+ from traceforge.parts.providers.jlc import JlcpcbProvider, JlcsearchProvider, LcscProvider
16
+ from traceforge.parts.providers.keyed import DigikeyProvider, MouserProvider, NexarProvider
17
+
18
+ PROVIDERS: dict[str, type[PartProvider]] = {
19
+ "jlcpcb": JlcpcbProvider,
20
+ "lcsc": LcscProvider,
21
+ "jlcsearch": JlcsearchProvider,
22
+ "nexar": NexarProvider,
23
+ "digikey": DigikeyProvider,
24
+ "mouser": MouserProvider,
25
+ }
26
+ DEFAULT_ORDER = ("jlcpcb", "lcsc", "jlcsearch", "nexar", "digikey", "mouser")
27
+
28
+
29
+ @dataclass
30
+ class Attempt:
31
+ provider: str
32
+ outcome: str # found | not_found | offline | error | cached | stale
33
+ detail: str = ""
34
+ fetched_at: float = 0.0 # when the answer came from the provider (epoch seconds)
35
+
36
+
37
+ @dataclass
38
+ class LookupReport:
39
+ query: str
40
+ part: PartInfo | None = None
41
+ attempts: list[Attempt] = field(default_factory=list)
42
+
43
+ @property
44
+ def answered(self) -> bool:
45
+ """At least one provider (or the cache) gave a definite answer."""
46
+ return any(a.outcome in {"found", "not_found", "cached", "stale"} for a in self.attempts)
47
+
48
+ @property
49
+ def offline(self) -> bool:
50
+ return not self.answered and any(a.outcome == "offline" for a in self.attempts)
51
+
52
+ def describe(self) -> str:
53
+ return ", ".join(
54
+ f"{a.provider}: {a.outcome}" + (f" ({a.detail})" if a.detail else "")
55
+ for a in self.attempts
56
+ )
57
+
58
+
59
+ def _enrich(part: PartInfo) -> PartInfo:
60
+ if part.pin_count is None:
61
+ facts = parse_catalog_package(
62
+ part.package, description=part.description, attributes=part.attributes
63
+ )
64
+ part.pin_count = facts.pins
65
+ if not part.mounting:
66
+ part.mounting = facts.mounting
67
+ if part.stock is None and part.stock_by_source:
68
+ part.stock = max(part.stock_by_source.values())
69
+ return part
70
+
71
+
72
+ class Catalog:
73
+ """Ordered providers + a disk cache.
74
+
75
+ ``TRACEFORGE_PART_PROVIDERS`` (comma separated) picks and orders providers;
76
+ keyed ones only run when their credentials are set.
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ providers: list[str] | None = None,
82
+ *,
83
+ net: Net | None = None,
84
+ cache: Cache | None = None,
85
+ ):
86
+ self.net = net or default_net()
87
+ self.cache = cache or Cache()
88
+ names = providers or [
89
+ n.strip()
90
+ for n in os.environ.get("TRACEFORGE_PART_PROVIDERS", ",".join(DEFAULT_ORDER)).split(",")
91
+ if n.strip()
92
+ ]
93
+ self.providers: list[PartProvider] = []
94
+ for name in names:
95
+ cls = PROVIDERS.get(name)
96
+ if cls is None:
97
+ continue
98
+ provider = cls(self.net)
99
+ if provider.configured():
100
+ self.providers.append(provider)
101
+
102
+ def provider_names(self) -> list[str]:
103
+ return [p.name for p in self.providers]
104
+
105
+ # ----------------------------------------------------------------- lookup
106
+
107
+ def _cached_call(self, provider: PartProvider, op: str, key: str, call, report: LookupReport):
108
+ """Run a provider call through the cache. Returns (found, value)."""
109
+ cache_key = f"{provider.name}:{op}:{key}"
110
+ hit = self.cache.get("lookup", cache_key)
111
+ if hit is not None:
112
+ when = self.cache.entry_time("lookup", cache_key)
113
+ report.attempts.append(Attempt(provider.name, "cached", fetched_at=when))
114
+ return True, hit[0]
115
+ try:
116
+ value = call()
117
+ except NotSupported:
118
+ return False, None
119
+ except Offline as exc:
120
+ stale = self.cache.get("lookup", cache_key, allow_stale=True)
121
+ if stale is not None:
122
+ when = self.cache.entry_time("lookup", cache_key)
123
+ report.attempts.append(
124
+ Attempt(provider.name, "stale", "network failed", fetched_at=when)
125
+ )
126
+ value = stale[0]
127
+ if isinstance(value, dict) and value.get("part"):
128
+ value["part"]["stale"] = True
129
+ return True, value
130
+ report.attempts.append(Attempt(provider.name, "offline", str(exc)[:120]))
131
+ return False, None
132
+ except (ProviderError, ValueError, KeyError, TypeError) as exc:
133
+ report.attempts.append(Attempt(provider.name, "error", str(exc)[:160]))
134
+ return False, None
135
+ stored = {"part": value.to_dict() if value else None}
136
+ self.cache.put("lookup", cache_key, stored)
137
+ report.attempts.append(
138
+ Attempt(provider.name, "found" if value else "not_found", fetched_at=time.time())
139
+ )
140
+ return True, stored
141
+
142
+ def lookup_report(self, code_or_mpn: str, *, all_sources: bool = False) -> LookupReport:
143
+ """Look a part up; ``all_sources`` asks every provider instead of stopping at two."""
144
+ query = (code_or_mpn or "").strip()
145
+ report = LookupReport(query)
146
+ if not query:
147
+ return report
148
+ if is_lcsc_code(query):
149
+ code = normalize_lcsc(query)
150
+ providers = [p for p in self.providers if p.codes]
151
+ # JLCPCB (assembly library, stock) and LCSC (package, lifecycle) complement each other.
152
+ primary = [p for p in providers if p.name in {"jlcpcb", "lcsc"}] or providers[:1]
153
+ if all_sources:
154
+ primary = providers
155
+ results = self._run(primary, "code", code, lambda p: p.lookup_code(code), report)
156
+ if not any(ok for ok, _ in results) or not any(v and v.get("part") for _, v in results):
157
+ rest = [p for p in providers if p not in primary]
158
+ if not any(ok for ok, _ in results):
159
+ results += self._run(rest, "code", code, lambda p: p.lookup_code(code), report)
160
+ parts = [
161
+ PartInfo.from_dict(v["part"]) for ok, v in results if ok and v and v.get("part")
162
+ ]
163
+ else:
164
+ providers = [p for p in self.providers if p.mpns or p.searches]
165
+ parts = []
166
+ for provider in providers:
167
+ ok, value = self._cached_call(
168
+ provider, "mpn", norm_mpn(query), lambda p=provider: p.lookup_mpn(query), report
169
+ )
170
+ if ok and value and value.get("part"):
171
+ parts.append(PartInfo.from_dict(value["part"]))
172
+ if len(parts) >= 2 and not all_sources:
173
+ break
174
+ for found in parts:
175
+ ensure_offers(found)
176
+ if parts:
177
+ merged = parts[0]
178
+ for other in parts[1:]:
179
+ if not merged.lcsc or not other.lcsc or merged.lcsc == other.lcsc:
180
+ merged.merge(other)
181
+ report.part = _enrich(merged)
182
+ return report
183
+
184
+ def _run(self, providers, op, key, fn, report):
185
+ if not providers:
186
+ return []
187
+ subreports = [LookupReport(key) for _ in providers]
188
+ with ThreadPoolExecutor(max_workers=len(providers)) as pool:
189
+ futures = [
190
+ pool.submit(self._cached_call, p, op, key, (lambda p=p: fn(p)), sub)
191
+ for p, sub in zip(providers, subreports)
192
+ ]
193
+ results = [future.result() for future in futures]
194
+ for sub in subreports:
195
+ report.attempts.extend(sub.attempts)
196
+ return results
197
+
198
+ def lookup(self, code_or_mpn: str) -> PartInfo | None:
199
+ """The part for an LCSC code or MPN; None if no catalogue knows it.
200
+
201
+ Raises :class:`Offline` when no provider could be asked and nothing is cached.
202
+ """
203
+ report = self.lookup_report(code_or_mpn)
204
+ if report.part is None and not report.answered and report.attempts:
205
+ raise Offline(f"could not verify {code_or_mpn!r}: {report.describe()}")
206
+ return report.part
207
+
208
+ def lookup_many(self, queries: list[str], workers: int = 8) -> dict[str, LookupReport]:
209
+ unique = list(dict.fromkeys(q.strip() for q in queries if q and q.strip()))
210
+ if not unique:
211
+ return {}
212
+ with ThreadPoolExecutor(max_workers=min(workers, len(unique))) as pool:
213
+ reports = list(pool.map(self.lookup_report, unique))
214
+ return dict(zip(unique, reports))
215
+
216
+ # ----------------------------------------------------------------- search
217
+
218
+ def search(
219
+ self,
220
+ query: str,
221
+ *,
222
+ package: str | None = None,
223
+ basic_only: bool = False,
224
+ in_stock: bool = True,
225
+ limit: int = 10,
226
+ ) -> list[PartInfo]:
227
+ """Search every searching provider; basic and in-stock parts first."""
228
+ request = SearchQuery(query, package, basic_only, in_stock, max(1, min(limit, 50)))
229
+ if is_lcsc_code(query.strip()):
230
+ part = self.lookup(query)
231
+ return [part] if part else []
232
+ results: list[PartInfo] = []
233
+ errors: list[str] = []
234
+ answered = False
235
+ key = f"{query}|{package}|{basic_only}|{in_stock}|{request.limit}"
236
+ for provider in [p for p in self.providers if p.searches]:
237
+ cache_key = f"{provider.name}:search:{key}"
238
+ hit = self.cache.get("search", cache_key)
239
+ if hit is not None:
240
+ found = [PartInfo.from_dict(d) for d in hit[0]]
241
+ else:
242
+ try:
243
+ found = provider.search(request)
244
+ except NotSupported:
245
+ continue
246
+ except Offline as exc:
247
+ stale = self.cache.get("search", cache_key, allow_stale=True)
248
+ if stale is None:
249
+ errors.append(f"{provider.name}: {exc}")
250
+ continue
251
+ found = [PartInfo.from_dict({**d, "stale": True}) for d in stale[0]]
252
+ except (ProviderError, ValueError, KeyError, TypeError) as exc:
253
+ errors.append(f"{provider.name}: {exc}")
254
+ continue
255
+ self.cache.put("search", cache_key, [p.to_dict() for p in found])
256
+ answered = True
257
+ results.extend(found)
258
+ if len({p.lcsc or p.mpn for p in results}) >= request.limit * 2:
259
+ break
260
+ if not answered and errors:
261
+ raise Offline("; ".join(errors))
262
+ merged: dict[str, PartInfo] = {}
263
+ for part in results:
264
+ ensure_offers(part)
265
+ key_ = part.lcsc or f"{part.manufacturer}:{part.mpn}"
266
+ if key_ in merged:
267
+ merged[key_].merge(part)
268
+ else:
269
+ merged[key_] = part
270
+ parts = [_enrich(p) for p in merged.values()]
271
+ if package:
272
+ wanted = package.lower().replace(" ", "")
273
+ parts = [p for p in parts if wanted in p.package.lower().replace(" ", "")] or [
274
+ p for p in parts if wanted in (p.description + p.mpn).lower().replace(" ", "")
275
+ ]
276
+ if basic_only:
277
+ parts = [p for p in parts if p.library_type in {"basic", "preferred", ""}]
278
+ if in_stock:
279
+ parts = [p for p in parts if p.stock is None or p.stock > 0]
280
+ rank = {"basic": 0, "preferred": 1}
281
+ parts.sort(key=lambda p: (rank.get(p.library_type, 2), -(p.stock or 0)))
282
+ return parts[: request.limit]
283
+
284
+
285
+ _default: Catalog | None = None
286
+
287
+
288
+ def default_catalog() -> Catalog:
289
+ global _default
290
+ if _default is None:
291
+ _default = Catalog()
292
+ return _default
293
+
294
+
295
+ def set_default_catalog(catalog: Catalog | None) -> None:
296
+ global _default
297
+ _default = catalog
@@ -0,0 +1,156 @@
1
+ """``traceforge parts bom|brief|alternates``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from rich.console import Console
10
+
11
+ from traceforge.parts.net import Offline
12
+
13
+ console = Console()
14
+ err = Console(stderr=True)
15
+
16
+ COMMANDS = ("bom", "brief", "alternates")
17
+
18
+
19
+ def _qtys(text: str | None) -> tuple[int, ...]:
20
+ try:
21
+ values = tuple(sorted({int(x) for x in (text or "1,10,100,1000").split(",") if x.strip()}))
22
+ except ValueError:
23
+ raise SystemExit(
24
+ "error: --qty takes comma separated whole numbers, e.g. 1,10,100,1000"
25
+ ) from None
26
+ if not values or min(values) < 1:
27
+ raise SystemExit("error: quantities must be positive")
28
+ return values
29
+
30
+
31
+ def _tables(args) -> dict[str, Any]:
32
+ from traceforge.parts.brief import load_yaml
33
+
34
+ return {
35
+ "hs_table": load_yaml(args.hs_table, "hs_codes.yaml") if args.hs_table else None,
36
+ "duty_table": load_yaml(args.duty_table, "duty_rates.yaml") if args.duty_table else None,
37
+ }
38
+
39
+
40
+ def run(args) -> int:
41
+ action, rest = args.query[0], args.query[1:]
42
+ if not rest:
43
+ err.print(f"[red]error:[/] parts {action} needs an argument (a part number or a BOM path)")
44
+ return 2
45
+ try:
46
+ return {"bom": _bom, "brief": _brief, "alternates": _alternates}[action](args, rest)
47
+ except Offline as exc:
48
+ err.print(f"[red]not verified: offline[/] ({exc})")
49
+ return 1
50
+ except (ValueError, OSError) as exc:
51
+ err.print(f"[red]error:[/] {exc}")
52
+ return 1
53
+
54
+
55
+ def _write(path: Path, text: str) -> None:
56
+ path.parent.mkdir(parents=True, exist_ok=True)
57
+ path.write_text(text, encoding="utf-8", newline="")
58
+ console.print(f"wrote {path}")
59
+
60
+
61
+ def _bom(args, rest: list[str]) -> int:
62
+ from traceforge.parts.bom import export_bom, export_cpl, load_bom, rollup
63
+ from traceforge.parts.fx import load_rates
64
+ from traceforge.parts.supply import source_many
65
+
66
+ items = load_bom(rest[0])
67
+ qtys = _qtys(args.qty)
68
+ fx = load_rates()
69
+ sourcings = source_many(
70
+ [i.query for i in items if i.query],
71
+ qtys=tuple(sorted({q * max(i.qty, 1) for q in qtys for i in items})),
72
+ currency=args.currency,
73
+ fx=fx,
74
+ )
75
+ roll = rollup(items, sourcings, qtys, args.currency.upper())
76
+ fmt = args.format
77
+ if args.out:
78
+ out = Path(args.out)
79
+ for name, kind in (
80
+ ("jlcpcb", "jlcpcb"),
81
+ ("pcbway", "pcbway"),
82
+ ("generic", "generic"),
83
+ ("excel", "excel"),
84
+ ):
85
+ if fmt in {"all", name}:
86
+ _write(out / f"bom_{name}.csv", export_bom(items, kind, sourcings, qtys[0]))
87
+ if fmt in {"all", "rollup"}:
88
+ _write(out / "rollup.md", roll.to_markdown() + f"\n\n{fx.describe()}\n")
89
+ _write(out / "rollup.json", json.dumps(roll.to_dict(), indent=1))
90
+ if args.board:
91
+ _write(out / "cpl_jlcpcb.csv", export_cpl(args.board, items))
92
+ return 0
93
+ if fmt in {"jlcpcb", "pcbway", "generic", "excel"}:
94
+ print(export_bom(items, fmt, sourcings, qtys[0]), end="")
95
+ return 0
96
+ if args.json:
97
+ print(json.dumps(roll.to_dict(), indent=1))
98
+ return 0
99
+ console.print(
100
+ f"[bold]{len(items)} BOM lines[/], prices in {args.currency.upper()} ({fx.describe()})\n"
101
+ )
102
+ print(roll.to_markdown())
103
+ return 0
104
+
105
+
106
+ def _brief(args, rest: list[str]) -> int:
107
+ from traceforge.parts.bom import load_bom, rollup
108
+ from traceforge.parts.brief import build_bom_brief, build_brief
109
+
110
+ tables = _tables(args)
111
+ common = {
112
+ "country": args.country or "",
113
+ "currency": args.currency,
114
+ "qty": args.target_qty,
115
+ "freight_usd": args.freight,
116
+ "insurance_pct": args.insurance,
117
+ **tables,
118
+ }
119
+ target = Path(rest[0])
120
+ if target.exists():
121
+ from traceforge.parts.fx import load_rates
122
+ from traceforge.parts.supply import source_many
123
+
124
+ items = load_bom(target)
125
+ fx = load_rates()
126
+ briefs = {}
127
+ for item in items:
128
+ if item.query:
129
+ briefs[item.query] = build_brief(item.query, fx=fx, with_alternates=False, **common)
130
+ sourcings = {k: b.sourcing for k, b in briefs.items()}
131
+ roll = rollup(items, sourcings, _qtys(args.qty_boards), args.currency.upper())
132
+ text = build_bom_brief(items, sourcings, roll.to_markdown(), briefs)
133
+ text += "\n\n---\n\n" + "\n\n---\n\n".join(b.to_markdown() for b in briefs.values())
134
+ data = {"bom": roll.to_dict(), "parts": [b.to_dict() for b in briefs.values()]}
135
+ _ = source_many # sourcing already done per brief
136
+ else:
137
+ brief = build_brief(rest[0], **common)
138
+ text, data = brief.to_markdown(), brief.to_dict()
139
+ if args.out:
140
+ base = Path(args.out)
141
+ md = base if base.suffix == ".md" else base.with_suffix(".md")
142
+ _write(md, text + "\n")
143
+ _write(md.with_suffix(".json"), json.dumps(data, indent=1, default=str))
144
+ return 0
145
+ print(json.dumps(data, indent=1, default=str) if args.json else text)
146
+ return 0
147
+
148
+
149
+ def _alternates(args, rest: list[str]) -> int:
150
+ from traceforge.parts.alternates import find_alternates
151
+
152
+ result = find_alternates(rest[0], limit=args.limit)
153
+ print(
154
+ json.dumps(result.to_dict(), indent=1, default=str) if args.json else result.to_markdown()
155
+ )
156
+ return 0 if result.original else 1
@@ -0,0 +1,37 @@
1
+ # Duty and tax table for the landed-cost estimate. EDITABLE DATA, NOT AUTHORITY.
2
+ #
3
+ # Entered 2026-11-04 from the author's recollection of the tariffs; NOT checked against the
4
+ # live notifications. Every rate carries `verified: false` until someone confirms it against the
5
+ # official source and changes the flag and date. Rates change with budgets and notifications;
6
+ # confirm with the customs broker before quoting a landed cost to anyone.
7
+ #
8
+ # Sources to check against:
9
+ # India - Customs Tariff Act 1975, First Schedule (CBIC: https://www.cbic.gov.in/ ->
10
+ # Customs -> Customs Tariff), effective BCD and exemption notifications, and the
11
+ # Social Welfare Surcharge; IGST per the IGST Act 2017 and CBIC rate notification
12
+ # No. 1/2017-Integrated Tax (Rate), 18% being the usual rate for chapter 85 goods.
13
+ # Other countries are intentionally absent: with no row, the brief shows the goods cost and
14
+ # says "no duty data for <country>"; it never guesses a rate.
15
+ #
16
+ # Format. `duty` maps an HS prefix (digits only, longest prefix wins) to a rate in percent of
17
+ # the customs value (CIF = goods + freight + insurance). `taxes` are applied in order after
18
+ # duty; `of` lists the amounts they are charged on: cif, duty, or the name of an earlier tax.
19
+ destinations:
20
+ IN:
21
+ name: India
22
+ currency: INR
23
+ as_of: "2026-11-04"
24
+ verified: false
25
+ duty_label: BCD
26
+ taxes:
27
+ - {name: SWS, pct: 10, of: [duty], note: "Social Welfare Surcharge, 10% of BCD (nil where BCD is nil or exempted)"}
28
+ - {name: IGST, pct: 18, of: [cif, duty, SWS], note: "Integrated GST on import; creditable to a GST-registered business, so a cash-flow cost rather than a final cost"}
29
+ duty:
30
+ # prefix: percent. Example values; see the header.
31
+ "8542": {pct: 0, note: "Integrated circuits: nil under the Information Technology Agreement lines"}
32
+ "8541": {pct: 0, note: "Diodes, transistors, LEDs, crystals: shown as nil, check LEDs (8541.41) and crystals (8541.60)"}
33
+ "8532": {pct: 10, note: "Capacitors"}
34
+ "8533": {pct: 10, note: "Resistors"}
35
+ "8504": {pct: 10, note: "Inductors"}
36
+ "8536": {pct: 10, note: "Connectors, switches, fuses"}
37
+ "8543": {pct: 10, note: "Modules"}
@@ -0,0 +1,103 @@
1
+ # HS classification guide for common electronic components.
2
+ #
3
+ # A GUIDE ONLY. Classification depends on the exact article and the importing country's
4
+ # tariff; the customs broker (or a binding ruling) decides. Subheadings are the 6-digit
5
+ # HS 2022 level (the World Customs Organization nomenclature), written from the author's
6
+ # working knowledge of HS 2022 chapters 85; they were not cross-checked line by line against
7
+ # the WCO publication. Countries extend these to 8-10 digits.
8
+ #
9
+ # Matching: a rule matches when `any` of its words appears in the part's category,
10
+ # description or MPN text (lower case) and none of `not` does. The first matching rule wins,
11
+ # so put specific rules before general ones. Edit freely; `--hs-table FILE` loads your own.
12
+ rules:
13
+ # Order matters: passives, discretes and connectors are tested before integrated circuits, because
14
+ # words such as 'usb' or 'chip' also appear in their descriptions.
15
+ - hs: "8541.41"
16
+ name: Light-emitting diodes (LED)
17
+ any: [led, light emitting diode, light-emitting]
18
+ why: 8541.41 is "light-emitting diodes (LED)" (HS 2022; earlier editions used 8541.40).
19
+ - hs: "8541.10"
20
+ name: Diodes (other than photosensitive or LED)
21
+ any: [diode, schottky, zener, rectifier, tvs, esd protection]
22
+ why: 8541.10 is "diodes, other than photodiodes or light-emitting diodes". TVS and ESD arrays are sometimes classed elsewhere.
23
+ - hs: "8541.21"
24
+ name: Transistors with a dissipation rate under 1 W
25
+ any: [transistor, mosfet, bjt, jfet]
26
+ not: [driver]
27
+ why: 8541.21 is transistors (other than photo-transistors) with a dissipation rate below 1 W; 8541.29 for 1 W or more. Check the part's power dissipation.
28
+ - hs: "8541.60"
29
+ name: Mounted piezoelectric crystals (crystals and resonators)
30
+ any: [crystal, resonator, oscillator crystal, xtal]
31
+ not: [oscillator ic, "mems"]
32
+ why: 8541.60 is "mounted piezo-electric crystals". Packaged oscillators with active circuitry are usually 8541.60 or 8543.70; confirm.
33
+ - hs: "8532.24"
34
+ name: Fixed capacitors - ceramic dielectric, multilayer (MLCC)
35
+ any: [mlcc, multilayer ceramic, ceramic capacitor, "x7r", "x5r", "c0g", "np0"]
36
+ why: 8532.24 is "ceramic dielectric, multilayer" fixed capacitors.
37
+ - hs: "8532.22"
38
+ name: Fixed capacitors - aluminium electrolytic
39
+ any: [aluminum electrolytic, aluminium electrolytic, electrolytic capacitor]
40
+ why: 8532.22 is aluminium electrolytic capacitors.
41
+ - hs: "8532.21"
42
+ name: Fixed capacitors - tantalum
43
+ any: [tantalum]
44
+ why: 8532.21 is tantalum fixed capacitors.
45
+ - hs: "8532.29"
46
+ name: Fixed capacitors - other
47
+ any: [capacitor]
48
+ why: Other fixed capacitors (film, polymer, supercapacitor classes vary); 8532.29 as the residual.
49
+ - hs: "8533.21"
50
+ name: Fixed resistors, power handling capacity not exceeding 20 W
51
+ any: [resistor, chip resistor, thick film, thin film]
52
+ not: [potentiometer, trimmer, variable, thermistor, varistor]
53
+ why: 8533.21 is fixed resistors of 20 W or less (chip resistors fall here).
54
+ - hs: "8533.40"
55
+ name: Variable resistors, potentiometers and trimmers
56
+ any: [potentiometer, trimmer, variable resistor, rheostat]
57
+ why: 8533.40 is other variable resistors including rheostats and potentiometers.
58
+ - hs: "8504.50"
59
+ name: Inductors (other)
60
+ any: [inductor, choke, ferrite bead, power inductor, coil]
61
+ why: 8504.50 is "other inductors". Ferrite beads are classified inconsistently (8504.50 or 8505.90); confirm.
62
+ - hs: "8536.10"
63
+ name: Fuses (voltage not exceeding 1000 V)
64
+ any: [fuse, polyfuse, pptc, resettable fuse]
65
+ why: 8536.10 is fuses for a voltage not exceeding 1000 V. Resettable PTC devices are sometimes put under 8533.40 or 9033; confirm.
66
+ - hs: "8536.50"
67
+ name: Switches (voltage not exceeding 1000 V)
68
+ any: [switch, tactile, pushbutton, dip switch]
69
+ why: 8536.50 is other switches for a voltage not exceeding 1000 V.
70
+ - hs: "8536.69"
71
+ name: Plugs and sockets (connectors) for voltage not exceeding 1000 V
72
+ any: [connector, receptacle, socket, header, usb-c, usb type-c, plug, jack, terminal block]
73
+ why: 8536.69 is plugs and sockets; 8536.90 covers other connection apparatus (terminal blocks, board-to-board in some tariffs).
74
+ - hs: "8543.70"
75
+ name: Electrical machines and apparatus having individual functions (modules)
76
+ any: [module, development board, dev board]
77
+ why: Finished modules with their own function are usually 8543.70 or 8517.62 (wireless); the function decides.
78
+ - hs: "8542.31"
79
+ name: Integrated circuits - processors and controllers (MCU, MPU, DSP, FPGA, SoC)
80
+ any: [microcontroller, mcu, "mpu", processor, fpga, dsp, "soc", cortex, risc, "arm "]
81
+ why: >
82
+ Heading 8542 covers electronic integrated circuits; 8542.31 is "processors and controllers,
83
+ whether or not combined with memories, converters, logic circuits, amplifiers, clocks".
84
+ A microcontroller is a controller with on-chip memory.
85
+ - hs: "8542.32"
86
+ name: Integrated circuits - memories
87
+ any: [eeprom, flash memory, "sram", "dram", "nor flash", "nand", "fram", "memory ic", "memories"]
88
+ not: [microcontroller, mcu]
89
+ why: 8542.32 is "memories" (flash, EEPROM, SRAM, DRAM) as standalone integrated circuits.
90
+ - hs: "8542.33"
91
+ name: Integrated circuits - amplifiers
92
+ any: [op amp, "opamp", operational amplifier, amplifier ic, comparator, instrumentation amplifier]
93
+ why: 8542.33 is "amplifiers" (op-amps, comparators, audio/RF amplifier ICs are usually placed here).
94
+ - hs: "8542.39"
95
+ name: Integrated circuits - other (regulators, drivers, interface, power management, ADC/DAC)
96
+ any: [regulator, ldo, "dc-dc", converter, driver, transceiver, "interface ic", "adc", "dac", power management, level shifter, supervisor, "rtc", gate driver, "integrated circuit"]
97
+ why: >
98
+ Remaining monolithic and hybrid integrated circuits fall in 8542.39. Some customs
99
+ authorities put voltage regulators in 8542.39 and others in 8504 (power supplies); confirm.
100
+ fallback:
101
+ hs: ""
102
+ name: Not classified by this table
103
+ why: No rule matched; ask the broker or look the part up in the destination country's tariff.