-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpantry_manager_sqlite.py
More file actions
1892 lines (1687 loc) · 73.5 KB
/
Copy pathpantry_manager_sqlite.py
File metadata and controls
1892 lines (1687 loc) · 73.5 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
import sqlite3
import logging
from datetime import date, datetime, timedelta
from typing import Any, Dict, List, Optional
from pantry_manager_abc import PantryManager
from scripts.short_id_utils import parse_short_id
from error_utils import safe_execute, validate_required_params
from constants import get_units_for_locale, is_infinite_ingredient
import i18n
logger = logging.getLogger(__name__)
class SQLitePantryManager(PantryManager):
"""SQLite implementation of the PantryManager interface."""
def __init__(self, connection_string: str = "pantry.db", **kwargs):
"""
Initialize the SQLite pantry manager.
Args:
connection_string: Path to the SQLite database file
**kwargs: Additional configuration options (ignored for SQLite)
"""
self.db_path = connection_string
try:
self._initialize_units()
except Exception:
# Defer database errors until actual operations
pass
def _get_connection(self):
"""Get a database connection. Should be used in a context manager."""
conn = sqlite3.connect(self.db_path)
conn.isolation_level = None # Enable autocommit mode
return conn
def _initialize_units(self) -> None:
"""Populate units table with defaults if empty."""
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS Units (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
base_unit TEXT NOT NULL,
size REAL NOT NULL
)
"""
)
cursor.execute("SELECT COUNT(*) FROM Units")
if cursor.fetchone()[0] == 0:
# Use locale-specific units (default to English for SQLite single-user mode)
locale = i18n.LANG
units = get_units_for_locale(locale)
cursor.executemany(
"INSERT INTO Units (name, base_unit, size) VALUES (?, ?, ?)",
[(u["name"], u["base_unit"], u["size"]) for u in units],
)
@safe_execute("list units", default_return=[])
def list_units(self) -> List[Dict[str, Any]]:
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute("SELECT name, base_unit, size FROM Units")
return [
{"name": name, "base_unit": base_unit, "size": size}
for name, base_unit, size in cursor.fetchall()
]
@safe_execute("set unit", default_return=False)
def set_unit(self, name: str, base_unit: str, size: float) -> bool:
validate_required_params(name=name, base_unit=base_unit, size=size)
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO Units (name, base_unit, size)
VALUES (?, ?, ?)
ON CONFLICT(name) DO UPDATE SET base_unit=excluded.base_unit, size=excluded.size
""",
(name, base_unit, size),
)
return True
@safe_execute("delete unit", default_return=False)
def delete_unit(self, name: str) -> bool:
"""Delete a custom measurement unit."""
validate_required_params(name=name)
with self._get_connection() as conn:
cursor = conn.cursor()
# Check if unit is used in transactions before deleting
cursor.execute(
"SELECT COUNT(*) FROM PantryTransactions WHERE unit = ?", (name,)
)
if cursor.fetchone()[0] > 0:
return False # Cannot delete unit that's being used
# Delete the unit
cursor.execute("DELETE FROM Units WHERE name = ?", (name,))
return cursor.rowcount > 0
@safe_execute("add ingredient", default_return=False)
def add_ingredient(self, name: str, default_unit: str) -> bool:
"""
Add a new ingredient to the database.
Args:
name: Name of the ingredient
default_unit: Default unit of measurement for this ingredient
Returns:
bool: True if successful, False otherwise
"""
validate_required_params(name=name, default_unit=default_unit)
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO Ingredients (name, default_unit)
VALUES (?, ?)
""",
(name, default_unit),
)
return True
@safe_execute("add preference", default_return=False)
def add_preference(
self, category: str, item: str, level: str, notes: str = None
) -> bool:
"""
Add a new food preference to the database.
Args:
category: Type of preference (dietary, allergy, dislike, like)
item: The specific preference item
level: Importance level (required, preferred, avoid)
notes: Optional notes about the preference
Returns:
bool: True if successful, False otherwise
"""
validate_required_params(category=category, item=item, level=level)
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO Preferences (category, item, level, notes, created_date)
VALUES (?, ?, ?, ?, datetime('now'))
""",
(category, item, level, notes),
)
return True
@safe_execute("update preference", default_return=False)
def update_preference(
self, preference_id: int, level: str, notes: str = None
) -> bool:
"""
Update an existing food preference.
Args:
preference_id: ID of the preference to update
level: New importance level (required/preferred/avoid)
notes: Optional new notes
Returns:
bool: True if successful, False otherwise
"""
validate_required_params(level=level)
if preference_id is None or preference_id <= 0:
raise ValueError("Valid preference_id is required")
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
UPDATE Preferences
SET level = ?, notes = ?
WHERE id = ?
""",
(level, notes, preference_id),
)
return cursor.rowcount > 0
@safe_execute("delete preference", default_return=False)
def delete_preference(self, preference_id: int) -> bool:
"""Delete a food preference by ID."""
if preference_id is None or preference_id <= 0:
raise ValueError("Valid preference_id is required")
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM Preferences WHERE id = ?", (preference_id,))
return cursor.rowcount > 0
@safe_execute("get preferences", default_return=[])
def get_preferences(self) -> List[Dict[str, Any]]:
"""Get all food preferences."""
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
SELECT id, category, item, level, notes, created_date
FROM Preferences
ORDER BY id
"""
)
columns = [col[0] for col in cursor.description]
return [dict(zip(columns, row)) for row in cursor.fetchall()]
@safe_execute("get ingredient ID", default_return=None)
def get_ingredient_id(self, name: str) -> Optional[int]:
"""Get the ID of an ingredient by name."""
validate_required_params(name=name)
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT id FROM Ingredients WHERE name = ?",
(name,),
)
result = cursor.fetchone()
return result[0] if result else None
def get_unit_id(self, name: str) -> Optional[int]:
"""Get the ID of a unit by name (case-insensitive)."""
validate_required_params(name=name)
with self._get_connection() as conn:
cursor = conn.cursor()
# Try exact match first
cursor.execute(
"SELECT id FROM Units WHERE name = ?",
(name,),
)
result = cursor.fetchone()
if result:
return result[0]
# Try case-insensitive match
cursor.execute(
"SELECT id FROM Units WHERE LOWER(name) = LOWER(?)",
(name,),
)
result = cursor.fetchone()
return result[0] if result else None
@safe_execute("add pantry item", default_return=False)
def add_item(
self, item_name: str, quantity: float, unit: str, notes: Optional[str] = None
) -> bool:
"""
Add a new item to the pantry or increase existing item quantity.
Args:
item_name: Name of the item to add
quantity: Amount to add
unit: Unit of measurement
notes: Optional notes about the transaction
Returns:
bool: True if successful, False otherwise
"""
validate_required_params(item_name=item_name, unit=unit)
if quantity <= 0:
raise ValueError("Quantity must be positive")
# Normalize the unit name to match database entries
normalized_unit = self._normalize_unit_name(unit)
with self._get_connection() as conn:
cursor = conn.cursor()
# Get or create the ingredient
ingredient_id = self.get_ingredient_id(item_name)
if ingredient_id is None:
self.add_ingredient(item_name, normalized_unit)
ingredient_id = self.get_ingredient_id(item_name)
cursor.execute(
"""
INSERT INTO PantryTransactions
(transaction_type, ingredient_id, quantity, unit, transaction_date, notes)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
"addition",
ingredient_id,
quantity,
normalized_unit,
datetime.now().isoformat(),
notes,
),
)
return True
def remove_item(
self, item_name: str, quantity: float, unit: str, notes: Optional[str] = None
) -> bool:
"""
Remove a quantity of an item from the pantry.
Args:
item_name: Name of the item to remove
quantity: Amount to remove
unit: Unit of measurement
notes: Optional notes about the transaction
Returns:
bool: True if successful, False otherwise
"""
try:
# Normalize the unit name to match database entries
normalized_unit = self._normalize_unit_name(unit)
# First check if we have enough of the item
current_quantity = self.get_item_quantity(item_name, unit)
if current_quantity < quantity:
print(
f"Not enough {item_name} in pantry. Current quantity: {current_quantity} {unit}"
)
return False
with self._get_connection() as conn:
cursor = conn.cursor()
ingredient_id = self.get_ingredient_id(item_name)
if ingredient_id is None:
print(f"Ingredient {item_name} not found in database")
return False
cursor.execute(
"""
INSERT INTO PantryTransactions
(transaction_type, ingredient_id, quantity, unit, transaction_date, notes)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
"removal",
ingredient_id,
quantity,
normalized_unit,
datetime.now().isoformat(),
notes,
),
)
return True
except Exception as e:
print(f"Error removing item: {e}")
return False
def get_item_quantity(self, item_name: str, unit: str) -> float:
"""
Get the current quantity of an item in the pantry.
Args:
item_name: Name of the item to check
unit: Unit of measurement
Returns:
float: Current quantity of the item (can be negative if more removals than additions)
"""
try:
# Normalize the unit name to match database entries
normalized_unit = self._normalize_unit_name(unit)
with self._get_connection() as conn:
cursor = conn.cursor()
ingredient_id = self.get_ingredient_id(item_name)
if ingredient_id is None:
return 0.0
cursor.execute(
"""
SELECT
SUM(CASE
WHEN transaction_type = 'addition' THEN quantity
ELSE -quantity
END) as net_quantity
FROM PantryTransactions
WHERE ingredient_id = ? AND unit = ?
""",
(ingredient_id, normalized_unit),
)
result = cursor.fetchone()[0]
return float(result) if result is not None else 0.0
except Exception as e:
print(f"Error getting item quantity: {e}")
return 0.0
def get_total_item_quantity(self, item_name: str, unit: str) -> float:
"""Get total quantity of an item across all units converted to the specified unit."""
try:
with self._get_connection() as conn:
cursor = conn.cursor()
ingredient_id = self.get_ingredient_id(item_name)
if ingredient_id is None:
return 0.0
# Normalize the unit name to match database entries
normalized_unit = self._normalize_unit_name(unit)
# First try exact match with normalized unit
cursor.execute(
"SELECT base_unit, size FROM Units WHERE name = ?",
(normalized_unit,),
)
target = cursor.fetchone()
# If no exact match, try common variations
if not target:
# Create mapping for common abbreviations and case variations
unit_mappings = {
# Volume abbreviations
"tsp": "Teaspoon",
"tbsp": "Tablespoon",
"cup": "Cup",
"ml": "Milliliter",
"l": "Liter",
"fl oz": "Fluid ounce",
"pt": "Pint",
"qt": "Quart",
"gal": "Gallon",
# Weight abbreviations
"g": "Gram",
"kg": "Kilogram",
"oz": "Ounce",
"lb": "Pound",
"lbs": "Pound",
# Count abbreviations
"pc": "Piece",
"pcs": "Piece",
"piece": "Piece",
"pieces": "Piece",
# Case variations (lowercase to proper case)
"teaspoon": "Teaspoon",
"tablespoon": "Tablespoon",
"milliliter": "Milliliter",
"liter": "Liter",
"gram": "Gram",
"kilogram": "Kilogram",
"ounce": "Ounce",
"pound": "Pound",
}
# Try mapped unit name
mapped_unit = unit_mappings.get(unit.lower())
if mapped_unit:
cursor.execute(
"SELECT base_unit, size FROM Units WHERE name = ?",
(mapped_unit,),
)
target = cursor.fetchone()
# If still no match, try case-insensitive search
if not target:
cursor.execute(
"SELECT base_unit, size FROM Units WHERE LOWER(name) = LOWER(?)",
(unit,),
)
target = cursor.fetchone()
# If still no match, try ingredient-specific conversions
if not target:
# Try ingredient-specific volume-to-weight conversions
conversion_result = self._try_ingredient_conversion(
item_name, unit, cursor
)
if conversion_result is not None:
return conversion_result
# Fall back to old behavior
return self.get_item_quantity(item_name, unit)
target_base, target_size = target
cursor.execute(
"""
SELECT t.unit, u.base_unit, u.size,
SUM(CASE WHEN t.transaction_type = 'addition' THEN t.quantity ELSE -t.quantity END)
AS net_quantity
FROM PantryTransactions t
JOIN Units u ON t.unit = u.name
WHERE t.ingredient_id = ?
GROUP BY t.unit, u.base_unit, u.size
""",
(ingredient_id,),
)
total_base = 0.0
for unit_name, base_unit, size, qty in cursor.fetchall():
if base_unit == target_base and qty:
total_base += float(qty) * float(size)
# If no matching base units found, try ingredient-specific conversion
if total_base == 0.0:
conversion_result = self._try_ingredient_conversion(
item_name, unit, cursor
)
if conversion_result is not None:
return conversion_result
return total_base / float(target_size)
except Exception as e:
print(f"Error getting total item quantity: {e}")
return 0.0
def _try_ingredient_conversion(
self, item_name: str, requested_unit: str, cursor
) -> float:
"""
Try ingredient-specific conversions between volume and weight.
Args:
item_name: Name of the ingredient
requested_unit: Unit being requested (e.g., 'Cup')
cursor: Database cursor
Returns:
float: Converted quantity, or None if no conversion possible
"""
try:
# Common ingredient conversions (volume to weight)
# These are approximate values for cooking purposes
ingredient_conversions = {
# Cheese (grated)
"parmesan cheese": {
("Cup", "Gram"): 100, # 1 cup grated parmesan ≈ 100g
("Tablespoon", "Gram"): 6, # 1 tbsp grated parmesan ≈ 6g
},
"cheddar cheese": {
("Cup", "Gram"): 110, # 1 cup grated cheddar ≈ 110g
("Tablespoon", "Gram"): 7,
},
"mozzarella cheese": {
("Cup", "Gram"): 100, # 1 cup shredded mozzarella ≈ 100g
},
# Flour and baking
"flour": {
("Cup", "Gram"): 120, # 1 cup all-purpose flour ≈ 120g
("Tablespoon", "Gram"): 8,
},
"sugar": {
("Cup", "Gram"): 200, # 1 cup granulated sugar ≈ 200g
("Tablespoon", "Gram"): 12,
},
"brown sugar": {
("Cup", "Gram"): 220, # 1 cup packed brown sugar ≈ 220g
("Tablespoon", "Gram"): 14,
},
"butter": {
("Cup", "Gram"): 227, # 1 cup butter ≈ 227g (2 sticks)
("Tablespoon", "Gram"): 14, # 1 tbsp butter ≈ 14g
},
# Common cooking ingredients
"rice": {
("Cup", "Gram"): 185, # 1 cup uncooked rice ≈ 185g
},
"pasta": {
("Cup", "Gram"): 100, # 1 cup dry pasta ≈ 100g
},
}
# Normalize ingredient name for matching
normalized_ingredient = item_name.lower().strip()
# Check if we have conversions for this ingredient
if normalized_ingredient not in ingredient_conversions:
return None
conversions = ingredient_conversions[normalized_ingredient]
# Find what units we have in the pantry for this ingredient
cursor.execute(
"SELECT id FROM Ingredients WHERE LOWER(name) = LOWER(?)", (item_name,)
)
ingredient_result = cursor.fetchone()
if not ingredient_result:
return None
ingredient_id = ingredient_result[0]
# Get pantry quantities grouped by unit
cursor.execute(
"""
SELECT t.unit,
SUM(CASE WHEN t.transaction_type = 'addition' THEN t.quantity ELSE -t.quantity END) AS net_quantity
FROM PantryTransactions t
WHERE t.ingredient_id = ?
GROUP BY t.unit
HAVING SUM(CASE WHEN t.transaction_type = 'addition' THEN t.quantity ELSE -t.quantity END) > 0
""",
(ingredient_id,),
)
total_in_requested_unit = 0.0
for pantry_unit, pantry_quantity in cursor.fetchall():
# Check if we can convert from pantry_unit to requested_unit
conversion_key = (requested_unit, pantry_unit)
reverse_conversion_key = (pantry_unit, requested_unit)
if conversion_key in conversions:
# Direct conversion: pantry_unit to requested_unit
conversion_factor = conversions[conversion_key]
converted_amount = float(pantry_quantity) / conversion_factor
total_in_requested_unit += converted_amount
elif reverse_conversion_key in conversions:
# Reverse conversion: requested_unit to pantry_unit
conversion_factor = conversions[reverse_conversion_key]
converted_amount = float(pantry_quantity) * conversion_factor
total_in_requested_unit += converted_amount
return total_in_requested_unit if total_in_requested_unit > 0 else None
except Exception as e:
print(f"Error in ingredient conversion: {e}")
return None
def _normalize_unit_name(self, unit: str) -> str:
"""Normalize unit name to match Units table entries."""
try:
with self._get_connection() as conn:
cursor = conn.cursor()
# First try exact match
cursor.execute("SELECT name FROM Units WHERE name = ?", (unit,))
if cursor.fetchone():
return unit
# Try common abbreviation mappings
unit_mappings = {
"tsp": "Teaspoon",
"tbsp": "Tablespoon",
"cup": "Cup",
"cups": "Cup",
"ml": "Milliliter",
"l": "Liter",
"fl oz": "Fluid ounce",
"pt": "Pint",
"qt": "Quart",
"gal": "Gallon",
"g": "Gram",
"kg": "Kilogram",
"oz": "Ounce",
"lb": "Pound",
"lbs": "Pound",
"pc": "Piece",
"pcs": "Piece",
"piece": "Piece",
"pieces": "Piece",
"teaspoon": "Teaspoon",
"tablespoon": "Tablespoon",
"tablespoons": "Tablespoon",
"milliliter": "Milliliter",
"liter": "Liter",
"gram": "Gram",
"kilogram": "Kilogram",
"ounce": "Ounce",
"pound": "Pound",
}
mapped_unit = unit_mappings.get(unit.lower())
if mapped_unit:
cursor.execute(
"SELECT name FROM Units WHERE name = ?", (mapped_unit,)
)
if cursor.fetchone():
return mapped_unit
# Try case-insensitive match
cursor.execute(
"SELECT name FROM Units WHERE LOWER(name) = LOWER(?)", (unit,)
)
result = cursor.fetchone()
if result:
return result[0]
# If no match found, return original unit (might need to be added to Units)
return unit
except Exception as e:
print(f"Error normalizing unit name: {e}")
return unit
def get_pantry_contents(self) -> Dict[str, Dict[str, float]]:
"""
Get the current contents of the pantry.
Returns:
Dict[str, Dict[str, float]]: Dictionary with item names as keys and their quantities by unit as values
"""
try:
with self._get_connection() as conn:
cursor = conn.cursor()
cursor.execute(
"""
SELECT
i.name,
t.unit,
SUM(CASE
WHEN t.transaction_type = 'addition' THEN t.quantity
ELSE -t.quantity
END) as net_quantity
FROM PantryTransactions t
JOIN Ingredients i ON t.ingredient_id = i.id
GROUP BY i.name, t.unit
HAVING net_quantity > 0
"""
)
results = cursor.fetchall()
contents = {}
for item_name, unit, quantity in results:
if item_name not in contents:
contents[item_name] = {}
contents[item_name][unit] = quantity
return contents
except Exception as e:
print(f"Error getting pantry contents: {e}")
return {}
def add_recipe(
self,
name: str,
instructions: str,
time_minutes: int,
ingredients: List[Dict[str, Any]],
servings: int = 4,
) -> tuple[bool, Optional[str]]:
"""
Add a new recipe to the database.
Args:
name: Name of the recipe
instructions: Cooking instructions
time_minutes: Time required to prepare the recipe
ingredients: List of dictionaries containing:
- name: ingredient name
- quantity: amount needed
- unit: unit of measurement
servings: Number of servings (default: 4)
Returns:
tuple[bool, Optional[str]]: (Success status, Recipe Short ID)
"""
# Validate servings
if not isinstance(servings, int) or servings < 1:
raise ValueError("Servings must be a positive integer")
if servings > 100:
raise ValueError("Servings must be 100 or less")
try:
with self._get_connection() as conn:
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute(
"""
INSERT INTO Recipes
(name, instructions, time_minutes, servings, created_date, last_modified)
VALUES (?, ?, ?, ?, ?, ?)
RETURNING id, short_id
""",
(name, instructions, time_minutes, servings, now, now),
)
recipe_id, short_id = cursor.fetchone()
# Add ingredients
for ingredient in ingredients:
ingredient_id = self.get_ingredient_id(ingredient["name"])
if ingredient_id is None:
# Create new ingredient if it doesn't exist
self.add_ingredient(ingredient["name"], ingredient["unit"])
ingredient_id = self.get_ingredient_id(ingredient["name"])
# Get unit_id for the unit name
unit_id = self.get_unit_id(ingredient["unit"])
if unit_id is None:
# Fallback: try to find a sensible default unit
available_units = self.list_units()
if available_units:
# Try to find Gram, Piece, or the first available unit
for preferred in ["Gram", "Piece", "Stuk"]:
fallback = next(
(
u
for u in available_units
if u["name"] == preferred
),
None,
)
if fallback:
unit_id = (
fallback["id"]
if "id" in fallback
else self.get_unit_id(fallback["name"])
)
warning_msg = f"⚠️ Warning: Unit '{ingredient['unit']}' not found, using '{fallback['name']}' instead"
print(warning_msg)
logger.warning(warning_msg)
break
# If still no match, use first available unit
if unit_id is None and available_units:
fallback_unit = available_units[0]["name"]
unit_id = self.get_unit_id(fallback_unit)
warning_msg = f"⚠️ Warning: Unit '{ingredient['unit']}' not found, using '{fallback_unit}' instead"
print(warning_msg)
logger.warning(warning_msg)
# If still no unit found, skip this ingredient
if unit_id is None:
warning_msg = f"⚠️ Warning: Skipping ingredient '{ingredient['name']}' - no valid units available"
print(warning_msg)
logger.warning(warning_msg)
continue
cursor.execute(
"""
INSERT INTO RecipeIngredients
(recipe_id, ingredient_id, quantity, unit_id)
VALUES (?, ?, ?, ?)
""",
(
recipe_id,
ingredient_id,
ingredient["quantity"],
unit_id,
),
)
return True, short_id
except Exception as e:
print(f"Error adding recipe: {e}")
return False, None
def get_recipe(self, recipe_name: str) -> Optional[Dict[str, Any]]:
"""
Get a recipe and its ingredients by name with fuzzy matching.
Args:
recipe_name: Name of the recipe to retrieve
Returns:
Optional[Dict[str, Any]]: Recipe details including ingredients, or None if not found
"""
if not recipe_name or not recipe_name.strip():
return None
search_term = recipe_name.strip()
try:
with self._get_connection() as conn:
cursor = conn.cursor()
# Strategy 1: Exact match
cursor.execute(
"""
SELECT
r.id, r.name, r.instructions, r.time_minutes, r.servings, r.rating,
r.created_date, r.last_modified, 1 as match_score
FROM Recipes r
WHERE r.name = ?
""",
(search_term,),
)
recipe = cursor.fetchone()
# Strategy 2: Case-insensitive exact match
if not recipe:
cursor.execute(
"""
SELECT
r.id, r.name, r.instructions, r.time_minutes, r.servings, r.rating,
r.created_date, r.last_modified, 2 as match_score
FROM Recipes r
WHERE LOWER(r.name) = LOWER(?)
""",
(search_term,),
)
recipe = cursor.fetchone()
# Strategy 3: Word-based matching - all words in search term appear in recipe name
if not recipe:
search_words = [
w.lower() for w in search_term.split() if len(w) > 2
]
if search_words:
word_conditions = " AND ".join(
["LOWER(r.name) LIKE ?" for _ in search_words]
)
word_params = [f"%{word}%" for word in search_words]
cursor.execute(
f"""
SELECT
r.id, r.name, r.instructions, r.time_minutes, r.servings, r.rating,
r.created_date, r.last_modified, 3 as match_score
FROM Recipes r
WHERE {word_conditions}
ORDER BY LENGTH(r.name) ASC
LIMIT 1
""",
word_params,
)
recipe = cursor.fetchone()
# Strategy 4: Any word in search term appears in recipe name (excluding common words)
if not recipe:
# Filter out very common words that would match too many recipes
common_words = {
"recipe",
"the",
"and",
"with",
"for",
"of",
"to",
"in",
"a",
"an",
}
search_words = [
w.lower()
for w in search_term.split()
if len(w) > 2 and w.lower() not in common_words
]
if search_words:
word_conditions = " OR ".join(
["LOWER(r.name) LIKE ?" for _ in search_words]
)
word_params = [f"%{word}%" for word in search_words]
cursor.execute(
f"""
SELECT
r.id, r.name, r.instructions, r.time_minutes, r.servings, r.rating,
r.created_date, r.last_modified, 4 as match_score
FROM Recipes r
WHERE {word_conditions}
ORDER BY LENGTH(r.name) ASC
LIMIT 1
""",
word_params,
)
recipe = cursor.fetchone()
# Strategy 5: Substring match (fallback) - more conservative
if not recipe:
# Split search term into words and require multiple words to match (filter common words)
common_words = {
"recipe",
"the",
"and",
"with",
"for",
"of",
"to",
"in",
"a",
"an",
}
search_words = [
w.strip()
for w in search_term.lower().split()
if len(w.strip()) > 2 and w.strip() not in common_words
]
if len(search_words) >= 2:
# For multi-word searches, require at least 2 words to match
# Rebuild word conditions and params for this strategy
word_conditions_s5 = []
word_params_s5 = []
for word in search_words:
word_conditions_s5.append("LOWER(r.name) LIKE ?")
word_params_s5.append(f"%{word}%")
# Require at least 80% of words to match (round up)
min_matches = max(2, int(len(search_words) * 0.8 + 0.5))
word_match_query = f"""
SELECT
r.id, r.name, r.instructions, r.time_minutes, r.rating,
r.created_date, r.last_modified, 5 as match_score,
({' + '.join(['CASE WHEN ' + cond + ' THEN 1 ELSE 0 END' for cond in word_conditions_s5])}) as word_matches
FROM Recipes r
WHERE ({' + '.join(['CASE WHEN ' + cond + ' THEN 1 ELSE 0 END' for cond in word_conditions_s5])}) >= ?
ORDER BY word_matches DESC, LENGTH(r.name) ASC
LIMIT 1
"""
cursor.execute(
word_match_query,
word_params_s5 + word_params_s5 + [min_matches],