-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2039 lines (1683 loc) · 65 KB
/
app.py
File metadata and controls
2039 lines (1683 loc) · 65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# app.py
from __future__ import annotations
import os
import re
import secrets
import time
import ipaddress
from datetime import datetime, timedelta, timezone
import uuid
from pathlib import Path
import csv
import io
import json
from typing import Any, Dict, List, Optional
from urllib.parse import urlparse
import qrcode
from io import BytesIO
import base64
import httpx
from fastapi import FastAPI, Form, Request, Query
from fastapi.responses import HTMLResponse, FileResponse, RedirectResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi import HTTPException
from passlib.hash import pbkdf2_sha256
from jinja2 import Environment, FileSystemLoader, select_autoescape
from markupsafe import Markup
from db import get_conn, init_db, \
list_containers, list_categories, list_subcategories, list_packages, \
ensure_container, ensure_category, ensure_subcategory, ensure_package, \
get_container_full_map, set_container_full, fetch_statistics
from models import PartRequest, PartData, ImageResult, ImageDownloadRequest, DatasheetResult
try:
from openai import OpenAI
except Exception: # pragma: no cover - optional dependency
OpenAI = None # type: ignore[assignment]
try:
from tavily import TavilyClient
except Exception: # pragma: no cover - optional dependency
TavilyClient = None # type: ignore[assignment]
APP_TITLE = "Electronics Inventory"
APP_VERSION = "3.4"
BASE_URL = os.environ.get("INVENTORY_BASE_URL", "http://127.0.0.1:8001").rstrip("/")
print(f"[startup] BASE_URL = {BASE_URL}")
SESSION_COOKIE_NAME = "inventory_session"
SESSION_TTL_SECONDS = 24 * 60 * 60
STATIC_DIR = Path(__file__).with_name("static")
# --- AI Auto-Fill (optional feature) ---
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "").strip()
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "").strip()
def _ai_enabled() -> bool:
return bool(OPENAI_API_KEY and TAVILY_API_KEY and OpenAI and TavilyClient)
def _get_openai_client() -> Optional[OpenAI]:
if not _ai_enabled():
return None
return OpenAI(api_key=OPENAI_API_KEY)
def _get_tavily_client() -> Optional[TavilyClient]:
if not _ai_enabled():
return None
return TavilyClient(api_key=TAVILY_API_KEY)
def _env_truthy(name: str) -> bool:
return os.environ.get(name, "").strip().lower() in ("1", "true", "yes", "y", "on")
def _debug_auth(msg: str) -> None:
if _env_truthy("INVENTORY_DEBUG_AUTH"):
print(f"[auth] {msg}")
def _client_ip_from_headers(request: Request) -> str:
"""Best-effort client IP extraction.
Uses standard proxy headers when present. This is important for the
home-network auto-login feature when running behind a reverse proxy.
"""
xff = (request.headers.get("x-forwarded-for") or "").strip()
if xff:
# First IP is the original client.
ip = xff.split(",", 1)[0].strip()
if ip:
return ip
forwarded = (request.headers.get("forwarded") or "").strip()
if forwarded:
# Very small parser for RFC 7239: Forwarded: for=1.2.3.4;proto=https
m = re.search(r"(?:^|[;,\s])for=(?P<val>\"[^\"]+\"|\[[^\]]+\]|[^;\s,]+)", forwarded, re.IGNORECASE)
if m:
val = m.group("val").strip().strip('"')
if val.startswith("[") and "]" in val:
val = val[1:val.find("]")]
if val:
return val
return request.client.host if request.client else ""
def _auth_disabled() -> bool:
# Intended for fully-local setups only. Do NOT use on internet-exposed deployments.
return _env_truthy("INVENTORY_DISABLE_AUTH")
def _trusted_home_ips() -> set:
"""Return set of IPs/networks from INVENTORY_HOME_IPS env var.
Comma-separated list of IPs or CIDR ranges that should be treated as "home network".
Example: INVENTORY_HOME_IPS="80.123.70.54,203.0.113.0/24"
"""
raw = os.environ.get("INVENTORY_HOME_IPS", "").strip()
if not raw:
return set()
return {ip.strip() for ip in raw.split(",") if ip.strip()}
def _is_home_network(client_ip: str) -> bool:
"""
Check if the client IP address is from a home/private network.
This allows skipping password authentication when accessing from your local network,
without needing to set environment variables.
Returns True for:
- 127.0.0.0/8 (localhost, e.g., 127.0.0.1)
- 10.0.0.0/8 (Class A private network)
- 172.16.0.0/12 (Class B private network, 172.16-172.31)
- 192.168.0.0/16 (Class C private network)
- ::1 (IPv6 localhost)
- fe80::/10 (IPv6 link-local addresses)
- Any IP listed in INVENTORY_HOME_IPS env var
"""
raw = (client_ip or "").strip()
if not raw:
return False
# Be defensive: sometimes values can be comma-separated (e.g. from X-Forwarded-For).
raw = raw.split(",", 1)[0].strip()
# Strip IPv6 zone index (e.g. fe80::1%en0)
raw = raw.split("%", 1)[0].strip()
# Strip brackets and optional port (e.g. [::1]:1234)
if raw.startswith("["):
end = raw.find("]")
if end != -1:
raw = raw[1:end]
# Strip port from IPv4 (e.g. 192.168.1.10:54321)
if ":" in raw and raw.count(":") == 1 and "." in raw:
host, maybe_port = raw.rsplit(":", 1)
if maybe_port.isdigit():
raw = host
# Check against explicit whitelist first (supports public IPs behind reverse proxy)
trusted = _trusted_home_ips()
if raw in trusted:
_debug_auth(f"IP {raw} matches INVENTORY_HOME_IPS whitelist")
return True
# Check if IP falls within any CIDR range in the whitelist
try:
ip_obj = ipaddress.ip_address(raw)
for entry in trusted:
if "/" in entry:
try:
if ip_obj in ipaddress.ip_network(entry, strict=False):
_debug_auth(f"IP {raw} matches CIDR {entry} in INVENTORY_HOME_IPS")
return True
except ValueError:
pass
except ValueError:
return False
return bool(ip_obj.is_loopback or ip_obj.is_private or ip_obj.is_link_local)
def _normalize_pass_hash(auth_pass_hash: str) -> str:
"""Normalize legacy/mis-copied pbkdf2 hashes into passlib format.
Accepts variants seen in shell/env contexts where '$' is lost or replaced.
Example legacy value: '-sha256.<salt>.<checksum>'
"""
raw = (auth_pass_hash or "").strip()
if raw == "" or raw.startswith("$"):
return raw
# Common legacy formats where '$' got replaced with '.'
m = re.fullmatch(r"(?:pbkdf2)?-?sha256\.(\d+)\.([A-Za-z0-9./]+)\.([A-Za-z0-9./]+)", raw)
if m:
rounds, salt, chk = m.group(1), m.group(2), m.group(3)
return f"$pbkdf2-sha256${rounds}${salt}${chk}"
# Legacy format missing rounds: '-sha256.<salt>.<checksum>'
m = re.fullmatch(r"-?sha256\.([A-Za-z0-9./]+)\.([A-Za-z0-9./]+)", raw)
if m:
salt, chk = m.group(1), m.group(2)
rounds = getattr(pbkdf2_sha256, "default_rounds", 29000)
return f"$pbkdf2-sha256${rounds}${salt}${chk}"
return raw
ALLOWED_EDIT_FIELDS = {
"category",
"subcategory",
"description",
"package",
"container_id",
"quantity",
"notes",
"image_url",
"datasheet_url",
"pinout_url",
}
def _parse_stock_levels(text: str) -> tuple[int | None, int | None]:
"""Parse stock levels input.
Supported:
- "" (empty) -> disable thresholds (NULL, NULL)
- "5" -> (5, 5) (green when >=5, red when <5)
- "10:5" -> (10, 5) (green >=10, yellow >=5 and <10, red <5)
"""
raw = (text or "").strip()
if raw == "":
return None, None
if ":" not in raw:
v = int(raw)
v = max(v, 0)
return v, v
left, right = [p.strip() for p in raw.split(":", 1)]
if left == "" or right == "":
raise ValueError("Use the format hi:lo (e.g. 10:5)")
hi = max(int(left), 0)
lo = max(int(right), 0)
if hi < lo:
raise ValueError("Expected hi >= lo (e.g. 10:5)")
return hi, lo
def _available_label_presets() -> List[str]:
static_dir = Path(__file__).with_name("static")
presets: List[str] = []
for css_file in static_dir.glob("avery_*.css"):
name = css_file.stem
if not name.startswith("avery_"):
continue
preset = name[len("avery_"):]
if preset and re.fullmatch(r"[A-Za-z0-9_-]+", preset):
presets.append(preset)
return sorted(set(presets))
def _label_preset_metadata() -> dict:
"""Read metadata from preset CSS files.
Expects a comment like: /* Meta: columns=2, rows=8, label_size=105x57mm */
"""
static_dir = Path(__file__).with_name("static")
metadata = {}
for css_file in static_dir.glob("avery_*.css"):
name = css_file.stem
if not name.startswith("avery_"):
continue
preset = name[len("avery_"):]
if not (preset and re.fullmatch(r"[A-Za-z0-9_-]+", preset)):
continue
try:
content = css_file.read_text()
match = re.search(r'/\*\s*Meta:\s*(.+?)\s*\*/', content)
if match:
meta_str = match.group(1)
meta = {}
for part in meta_str.split(","):
if "=" in part:
k, v = part.strip().split("=", 1)
meta[k.strip()] = v.strip()
metadata[preset] = meta
except Exception:
pass
return metadata
def _normalize_static_media_path(field: str, value: str) -> str:
"""Normalize user-entered media references.
Allows entering just a filename for the per-part image/pinout fields.
Examples:
- image_url: "LM358_board.jpg" -> "/static/images/LM358_board.jpg"
- pinout_url: "LM358_pinout.png" -> "/static/pinouts/LM358_pinout.png"
If an extension is omitted and there is exactly one matching file by stem
in the target folder, it will be used.
Absolute paths (starting with '/') and URLs are preserved.
"""
raw = (value or "").strip()
if raw == "":
return ""
# Leave full URLs or absolute paths untouched
lowered = raw.lower()
if "://" in raw or lowered.startswith("data:") or lowered.startswith("mailto:"):
return raw
if raw.startswith("/"):
return raw
# Normalize a few common relative patterns into /static/…
for prefix in ("static/", "static\\"):
if raw.startswith(prefix):
return "/" + raw.replace("\\", "/")
for prefix in ("images/", "images\\", "pinouts/", "pinouts\\"):
if raw.startswith(prefix):
return "/static/" + raw.replace("\\", "/")
# Only treat plain filenames (no path separators) as candidates.
if "/" in raw or "\\" in raw or ".." in raw:
return raw
subdir = None
if field == "image_url":
subdir = "images"
elif field == "pinout_url":
subdir = "pinouts"
if subdir is None:
return raw
folder = STATIC_DIR / subdir
if not folder.exists() or not folder.is_dir():
return f"/static/{subdir}/{raw}"
# 1) Exact match
if (folder / raw).exists():
return f"/static/{subdir}/{raw}"
# 2) Case-insensitive match
try:
entries = [p for p in folder.iterdir() if p.is_file()]
except Exception:
entries = []
ci = [p for p in entries if p.name.lower() == raw.lower()]
if len(ci) == 1:
return f"/static/{subdir}/{ci[0].name}"
# 3) Stem match when extension omitted
if "." not in raw:
stem_matches = [p for p in entries if p.stem.lower() == raw.lower()]
if len(stem_matches) == 1:
return f"/static/{subdir}/{stem_matches[0].name}"
# Default: assume it belongs in that folder
return f"/static/{subdir}/{raw}"
def _auth_config() -> tuple[str, str]:
# Read at request-time so runtime env changes (service env, docker env, etc.) are respected.
return (
os.environ.get("INVENTORY_USER", ""),
os.environ.get("INVENTORY_PASS_HASH", ""),
)
def _now_ts() -> int:
return int(time.time())
def _cleanup_expired_sessions(now_ts: int) -> None:
with get_conn() as conn:
conn.execute("DELETE FROM sessions WHERE expires_at <= ?", (now_ts,))
def _get_valid_session(token: str) -> Optional[Dict[str, Any]]:
if not token:
return None
now_ts = _now_ts()
with get_conn() as conn:
conn.execute("DELETE FROM sessions WHERE expires_at <= ?", (now_ts,))
row = conn.execute(
"SELECT token, username, expires_at FROM sessions WHERE token = ? AND expires_at > ?",
(token, now_ts),
).fetchone()
return dict(row) if row is not None else None
def _create_session(username: str) -> tuple[str, int]:
token = secrets.token_urlsafe(32)
now_ts = _now_ts()
expires_ts = now_ts + SESSION_TTL_SECONDS
with get_conn() as conn:
conn.execute(
"INSERT INTO sessions(token, username, created_at, expires_at) VALUES (?, ?, ?, ?)",
(token, username, now_ts, expires_ts),
)
return token, expires_ts
def _delete_session(token: str) -> None:
if not token:
return
with get_conn() as conn:
conn.execute("DELETE FROM sessions WHERE token = ?", (token,))
app = FastAPI()
@app.middleware("http")
async def session_auth_middleware(request: Request, call_next):
# Skip all authentication if globally disabled via environment variable
if _auth_disabled():
request.state.user = "local"
return await call_next(request)
# Check if the request is coming from the home network
# If so, automatically authenticate without requiring password
client_host = _client_ip_from_headers(request)
_debug_auth(f"middleware path={request.url.path} client_ip={client_host or '<none>'}")
if client_host and _is_home_network(client_host):
_debug_auth("home network detected -> allow without session")
request.state.user = "home_network_user"
return await call_next(request)
path = request.url.path
# Allow unauthenticated access to login page, static files, and favicon
if path == "/login" or path == "/favicon.ico" or path.startswith("/static/"):
return await call_next(request)
token = request.cookies.get(SESSION_COOKIE_NAME, "")
session = _get_valid_session(token)
if session is not None:
request.state.user = session.get("username")
return await call_next(request)
accept = request.headers.get("accept", "")
wants_html = ("text/html" in accept) or ("*/*" in accept) or (accept.strip() == "")
if wants_html:
return RedirectResponse(url="/login", status_code=303)
return HTMLResponse("Unauthorized", status_code=401)
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Environment(
loader=FileSystemLoader("templates"),
autoescape=select_autoescape(["html", "xml"]),
)
templates.globals["app_title"] = APP_TITLE
templates.globals["app_version"] = APP_VERSION
templates.globals["get_container_full_map"] = get_container_full_map
# Register tojson filter for Jinja2 templates (used by statistics page)
# Markup() prevents Jinja2 autoescape from escaping quotes in JSON output
templates.filters["tojson"] = lambda v: Markup(json.dumps(v))
def render(template_name: str, **context: Any) -> HTMLResponse:
tpl = templates.get_template(template_name)
return HTMLResponse(tpl.render(**context))
def render_with_status(template_name: str, status_code: int, **context: Any) -> HTMLResponse:
tpl = templates.get_template(template_name)
return HTMLResponse(tpl.render(**context), status_code=status_code)
@app.on_event("startup")
def _startup() -> None:
init_db()
@app.get("/login", response_class=HTMLResponse)
def login_get(request: Request) -> HTMLResponse:
# If authentication is globally disabled, redirect to main page
if _auth_disabled():
return RedirectResponse(url="/", status_code=303)
# If accessing from home network, automatically redirect to main page
# No password required when on local network
client_host = _client_ip_from_headers(request)
_debug_auth(f"GET /login client_ip={client_host or '<none>'}")
if client_host and _is_home_network(client_host):
_debug_auth("home network detected -> redirect to /")
return RedirectResponse(url="/", status_code=303)
return render("login.html", request=request, title=f"{APP_TITLE} – Login", error="")
@app.post("/login")
def login_post(
request: Request,
username: str = Form(""),
password: str = Form(""),
):
# If authentication is globally disabled, redirect to main page
if _auth_disabled():
return RedirectResponse(url="/", status_code=303)
# If accessing from home network, automatically authenticate
# without checking credentials
client_host = _client_ip_from_headers(request)
_debug_auth(f"POST /login client_ip={client_host or '<none>'}")
if client_host and _is_home_network(client_host):
_debug_auth("home network detected -> redirect to /")
return RedirectResponse(url="/", status_code=303)
auth_user, auth_pass_hash = _auth_config()
if not auth_user or not auth_pass_hash:
return render_with_status(
"login.html",
500,
request=request,
title=f"{APP_TITLE} – Login",
error="Auth not configured on server (set INVENTORY_USER and INVENTORY_PASS_HASH)",
)
user_ok = secrets.compare_digest((username or ""), auth_user)
# Try pbkdf2 hash verification first; fall back to plaintext comparison for dev setups
norm_hash = _normalize_pass_hash(auth_pass_hash)
if norm_hash.startswith("$pbkdf2-sha256$"):
try:
pass_ok = pbkdf2_sha256.verify((password or ""), norm_hash)
except ValueError:
pass_ok = False
else:
# Plaintext fallback (for local dev only – not recommended for production)
_debug_auth("INVENTORY_PASS_HASH is not a pbkdf2 hash; using plaintext comparison")
pass_ok = secrets.compare_digest((password or ""), auth_pass_hash)
if not (user_ok and pass_ok):
return render(
"login.html",
request=request,
title=f"{APP_TITLE} – Login",
error="Invalid username or password",
)
token, expires_ts = _create_session(username=auth_user)
resp = RedirectResponse(url="/", status_code=303)
expires_dt = datetime.fromtimestamp(expires_ts, tz=timezone.utc)
resp.set_cookie(
key=SESSION_COOKIE_NAME,
value=token,
max_age=SESSION_TTL_SECONDS,
expires=expires_dt,
httponly=True,
secure=True,
samesite="lax",
path="/",
)
return resp
@app.get("/logout")
def logout(request: Request):
if _auth_disabled():
return RedirectResponse(url="/", status_code=303)
token = request.cookies.get(SESSION_COOKIE_NAME, "")
_delete_session(token)
resp = RedirectResponse(url="/login", status_code=303)
resp.delete_cookie(key=SESSION_COOKIE_NAME, path="/")
return resp
@app.get("/favicon.ico")
async def favicon():
return FileResponse("static/favicon.ico")
def fetch_parts(
q: str = "",
category: str = "",
subcategory: str = "",
container_id: str = "",
limit: int = 500,
) -> List[Dict[str, Any]]:
sql = (
"SELECT *, "
"datetime(created_at, 'localtime') AS created_at_local, "
"datetime(updated_at, 'localtime') AS updated_at_local "
"FROM parts WHERE 1=1"
)
params: List[Any] = []
if q.strip():
sql += " AND (description LIKE ? OR notes LIKE ? OR subcategory LIKE ? OR package LIKE ? OR container_id LIKE ?)"
pat = f"%{q.strip()}%"
params += [pat, pat, pat, pat, pat]
if category.strip():
sql += " AND category = ?"
params.append(category.strip())
if subcategory.strip():
sql += " AND subcategory = ?"
params.append(subcategory.strip())
if container_id.strip():
sql += " AND container_id = ?"
params.append(container_id.strip())
sql += " ORDER BY updated_at DESC, id DESC LIMIT ?"
params.append(limit)
with get_conn() as conn:
rows = conn.execute(sql, params).fetchall()
return [dict(r) for r in rows]
# --- AI Auto-Fill endpoints (optional feature) ---
EXISTING_CATEGORIES = ["IC", "Module", "Passive", "Semiconductors", "Connectors", "Electromechanical"]
EXISTING_SUBCATS = ["OpAmp", "Logic", "Arduino", "Step-down (buck)", "N-channel", "Timers / Oscillators", "MOSFET"]
# Trusted electronics domains for Tavily search (first pass)
ELECTRONICS_DOMAINS = [
"digikey.com",
"mouser.com",
"reichelt.de",
"conrad.com",
"farnell.com",
"newark.com",
"lcsc.com",
"alldatasheet.com",
"datasheetcatalog.com",
"ti.com",
"onsemi.com",
"st.com",
"infineon.com",
"nxp.com",
"microchip.com",
"analog.com",
"vishay.com",
"tme.eu",
"electronics.semaf.at",
"berrybase.at",
"dfrobot.com",
"seeedstudio.com",
"adafruit.com",
"sparkfun.com",
"pololu.com",
"rohm.com",
"maxim-ic.com",
"monolithicpower.com",
"pimoroni.com",
"botland.store",
]
@app.post("/api/fill-part", response_model=PartData)
async def fill_part_agent(request: PartRequest) -> PartData:
if not _ai_enabled():
raise HTTPException(status_code=503, detail="AI Auto-Fill is disabled")
tavily = _get_tavily_client()
client = _get_openai_client()
if not tavily or not client:
raise HTTPException(status_code=503, detail="AI Auto-Fill is disabled")
# 1. TAVILY SEARCH (Text) - first try trusted electronics domains
search_query = f"{request.query} datasheet specifications"
results = []
try:
response = tavily.search(
query=search_query,
search_depth="basic",
max_results=5,
include_domains=ELECTRONICS_DOMAINS,
)
results = response.get("results", [])
except Exception:
results = []
# Fallback: if fewer than 2 results, retry without domain restriction
if len(results) < 2:
try:
response = tavily.search(
query=search_query,
search_depth="basic",
max_results=5,
)
results = response.get("results", [])
except Exception:
results = []
search_context = "\n".join([f"- {r['content']}" for r in results]) if results else "Search failed."
# 2. ASK OPENAI
try:
prompt = f"""
Analyze the part: "{request.query}" based on the Search Context below.
Search Context: {search_context}
--- INSTRUCTIONS ---
1. DESCRIPTION:
- Format strictly as: "[Part Name] [Short Generic Type]"
- Example 1: "IRLZ44N MOSFET"
- Example 2: "SS34 Schottky"
- Example 3: "LM358 OpAmp"
- Keep it extremely short (max 3-4 words). Do NOT include specs here.
2. NOTES:
- Extract the MAIN electrical parameters.
- Format strictly as comma-separated key=value pairs: "Key=Value, Key=Value"
- Use standard engineering abbreviations.
- For MOSFETs require: VDss, Id, RdsOn (or Rds).
- For Diodes require: Vr (Voltage), If (Current).
- For Regulators/ICs require: Vin, Vout, Iout (or similar).
- Example output: "VDss=55V, Id=47A, RdsOn=22mOhm"
3. CATEGORY/SUBCATEGORY:
- MAP 'Category' strictly to: {json.dumps(EXISTING_CATEGORIES)}
- MAP 'Subcategory' strictly to: {json.dumps(EXISTING_SUBCATS)} (or 'General').
"""
completion = client.beta.chat.completions.parse(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a precise electronics inventory assistant."},
{"role": "user", "content": prompt},
],
response_format=PartData,
)
data = completion.choices[0].message.parsed
# Extract PDF link
for r in results:
if ".pdf" in r.get("url", ""):
data.datasheet_url = r["url"]
break
return data
except Exception as e:
raise HTTPException(status_code=500, detail=f"AI Error: {str(e)}")
@app.get("/api/search-images", response_model=List[ImageResult])
async def search_images(query: str, type: str = "part") -> List[ImageResult]:
if not _ai_enabled():
raise HTTPException(status_code=503, detail="AI Auto-Fill is disabled")
tavily = _get_tavily_client()
if not tavily:
raise HTTPException(status_code=503, detail="AI Auto-Fill is disabled")
suffix = " pinout diagram" if type == "pinout" else " electronic component"
try:
response = tavily.search(
query=query + suffix,
include_images=True,
include_answer=False,
max_results=18, # Fetch more for pagination
)
images = response.get("images", [])
clean_results: List[ImageResult] = []
for img_url in images:
if isinstance(img_url, str):
clean_results.append(ImageResult(title="Image", thumbnail=img_url, url=img_url, source="Web"))
elif isinstance(img_url, dict):
clean_results.append(
ImageResult(
title=img_url.get("description", "Image"),
thumbnail=img_url.get("url", ""),
url=img_url.get("url", ""),
source="Web",
)
)
return clean_results
except Exception:
return []
@app.get("/api/search-datasheet", response_model=List[DatasheetResult])
async def search_datasheet(query: str) -> List[DatasheetResult]:
"""Search for datasheets using Tavily, returning PDF links."""
if not _ai_enabled():
raise HTTPException(status_code=503, detail="AI Auto-Fill is disabled")
tavily = _get_tavily_client()
if not tavily:
raise HTTPException(status_code=503, detail="AI Auto-Fill is disabled")
try:
# Search for datasheets with PDF focus
response = tavily.search(
query=f"{query} datasheet PDF",
include_answer=False,
max_results=8,
include_domains=ELECTRONICS_DOMAINS,
)
results: List[DatasheetResult] = []
seen_urls = set()
for item in response.get("results", []):
url = item.get("url", "")
title = item.get("title", "Datasheet")
# Skip duplicates
if url in seen_urls:
continue
seen_urls.add(url)
# Extract domain for source
try:
from urllib.parse import urlparse
domain = urlparse(url).netloc.replace("www.", "")
except Exception:
domain = "Web"
results.append(DatasheetResult(
title=title[:100], # Truncate long titles
url=url,
source=domain
))
return results
except Exception:
return []
@app.post("/api/download-image")
async def download_image(req: ImageDownloadRequest) -> Dict[str, str]:
"""Download an image from URL and save it locally to /static/images or /static/pinouts."""
# Determine target folder
if req.type == "pinout":
target_dir = STATIC_DIR / "pinouts"
suffix = "_pinout"
else:
target_dir = STATIC_DIR / "images"
suffix = ""
# Sanitize part description for use as filename
# Remove special characters, replace spaces with underscores
safe_name = re.sub(r'[^\w\s-]', '', req.part_description.strip())
safe_name = re.sub(r'[\s]+', '_', safe_name)
if not safe_name:
safe_name = f"image_{secrets.token_hex(4)}"
# Try to determine file extension from URL
parsed = urlparse(req.url)
url_path = parsed.path.lower()
# Map common extensions
ext = ".jpg" # default
for extension in [".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"]:
if url_path.endswith(extension):
ext = extension
break
# Build final filename
filename = f"{safe_name}{suffix}{ext}"
filepath = target_dir / filename
# If file already exists, add a short random suffix
if filepath.exists():
filename = f"{safe_name}{suffix}_{secrets.token_hex(3)}{ext}"
filepath = target_dir / filename
try:
# Download the image with httpx (async-friendly)
async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client:
response = await client.get(req.url, headers={
"User-Agent": "Mozilla/5.0 (compatible; ElectronicsInventory/1.0)"
})
response.raise_for_status()
# Check content type to ensure it's an image
content_type = response.headers.get("content-type", "").lower()
if not any(t in content_type for t in ["image/", "application/octet-stream"]):
raise HTTPException(status_code=400, detail=f"URL did not return an image (got {content_type})")
# Optionally update extension based on content-type
if "png" in content_type:
ext = ".png"
elif "gif" in content_type:
ext = ".gif"
elif "webp" in content_type:
ext = ".webp"
elif "svg" in content_type:
ext = ".svg"
# Rebuild filename if content-type gave us a better extension
if not filename.endswith(ext):
filename = f"{safe_name}{suffix}{ext}"
filepath = target_dir / filename
if filepath.exists():
filename = f"{safe_name}{suffix}_{secrets.token_hex(3)}{ext}"
filepath = target_dir / filename
# Write the file
filepath.write_bytes(response.content)
# Return the local path (relative to static, for use in templates)
local_path = filename
return {"filename": local_path, "path": str(filepath)}
except httpx.HTTPStatusError as e:
raise HTTPException(status_code=502, detail=f"Failed to download image: HTTP {e.response.status_code}")
except httpx.RequestError as e:
raise HTTPException(status_code=502, detail=f"Failed to download image: {str(e)}")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to save image: {str(e)}")
def fetch_trash(
q: str = "",
category: str = "",
container_id: str = "",
limit: int = 500,
) -> List[Dict[str, Any]]:
sql = "SELECT *, datetime(deleted_at, 'unixepoch', 'localtime') AS deleted_at_human FROM parts_trash WHERE 1=1"
params: List[Any] = []
if q.strip():
sql += " AND (description LIKE ? OR notes LIKE ? OR subcategory LIKE ? OR package LIKE ? OR container_id LIKE ?)"
pat = f"%{q.strip()}%"
params += [pat, pat, pat, pat, pat]
if category.strip():
sql += " AND category = ?"
params.append(category.strip())
if container_id.strip():
sql += " AND container_id = ?"
params.append(container_id.strip())
sql += " ORDER BY deleted_at DESC, trash_id DESC LIMIT ?"
params.append(limit)
with get_conn() as conn:
rows = conn.execute(sql, params).fetchall()
return [dict(r) for r in rows]
def _trash_parts(where_sql: str, params: List[Any], deleted_by: str) -> str:
batch_id = secrets.token_urlsafe(12)
now_ts = _now_ts()
with get_conn() as conn:
conn.execute("BEGIN")
# Copy rows into trash
conn.execute(
f"""
INSERT INTO parts_trash(
uuid, original_id, batch_id, deleted_at, deleted_by,
category, subcategory, description, package, container_id, quantity, stock_ok_min, stock_warn_min, notes,
image_url, datasheet_url, pinout_url, pinout_image_url, created_at, updated_at
)
SELECT
uuid, id, ?, ?, ?,
category, subcategory, description, package, container_id, quantity, stock_ok_min, stock_warn_min, notes,
image_url, datasheet_url, pinout_url, pinout_image_url, created_at, updated_at
FROM parts
WHERE {where_sql}
""",
[batch_id, now_ts, deleted_by, *params],
)
# Delete from parts
conn.execute(
f"DELETE FROM parts WHERE {where_sql}",
params,