Repository navigation
Expand file tree
/
Copy pathapp_backup.py
More file actions
2401 lines (2055 loc) · 94.8 KB
/
Copy pathapp_backup.py
File metadata and controls
2401 lines (2055 loc) · 94.8 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 requests
from flask import Flask, request, jsonify, send_file, render_template, session, redirect, url_for
import os
import re
import json
import csv
import speech_recognition as sr
import difflib
from difflib import SequenceMatcher
import urllib.parse
from datetime import datetime, date
import psycopg2
from dotenv import load_dotenv
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
try:
from indicnlp.normalize.indic_normalize import IndicNormalizerFactory
_has_indicnlp_normalizer = True
except Exception:
_has_indicnlp_normalizer = False
try:
from indic_transliteration.sanscript import transliterate, Devanagari, ITRANS
_has_indic = True
except Exception:
_has_indic = False
# Sumy imports are made lazy inside summarize_text to avoid optional deps at startup
# Optional: spaCy for basic NER (install model with `python -m spacy download en_core_web_sm`)
try:
import spacy
_spacy_available = True
except Exception:
spacy = None
_spacy_available = False
# Lazy-loaded spaCy model cache
_spacy_nlp = None
def get_spacy_nlp():
"""Return a loaded spaCy nlp object for 'en_core_web_sm'.
If model not found, attempt to download it. If download or load fails, return None."""
global _spacy_nlp
if not _spacy_available:
return None
if _spacy_nlp is not None:
return _spacy_nlp
try:
# First try to load
_spacy_nlp = spacy.load('en_core_web_sm')
return _spacy_nlp
except Exception as e:
print(f"WARNING: spaCy model load failed: {e}")
# Attempt to download the model if possible
try:
from spacy.cli import download as spacy_download
print("INFO: Attempting to download 'en_core_web_sm' model...")
spacy_download('en_core_web_sm')
_spacy_nlp = spacy.load('en_core_web_sm')
return _spacy_nlp
except Exception as e2:
print(f"WARNING: Could not download/load spaCy model: {e2}")
_spacy_nlp = None
return None
app = Flask(__name__)
app.secret_key = os.getenv("FLASK_SECRET_KEY", "quickstock_premium_secret_2026")
def get_db_connection():
return psycopg2.connect(DATABASE_URL)
def get_all_products_db():
try:
conn = get_db_connection()
cur = conn.cursor()
cur.execute("SELECT name, current_stock, threshold, unit, base_unit, price FROM products")
rows = cur.fetchall()
cur.close()
conn.close()
products_dict = {}
for r in rows:
name = r[0]
products_dict[name] = {
"name": name,
"current_stock": float(r[1]) if r[1] is not None else 0.0,
"threshold": float(r[2]) if r[2] is not None else 0.0,
"unit": r[3] or "unit",
"base_unit": r[4] or "unit",
"price": float(r[5]) if r[5] is not None else 0.0
}
return products_dict
except Exception as e:
print(f"Error fetching products from DB: {e}")
return {}
def update_product_stock_in_db(product_name, new_stock, new_threshold=None, new_price=None):
try:
conn = get_db_connection()
cur = conn.cursor()
updates = ["current_stock = %s"]
params = [new_stock]
if new_threshold is not None:
updates.append("threshold = %s")
params.append(new_threshold)
if new_price is not None:
updates.append("price = %s")
params.append(new_price)
params.append(product_name)
query = f"UPDATE products SET {', '.join(updates)} WHERE name = %s"
cur.execute(query, tuple(params))
conn.commit()
cur.close()
conn.close()
except Exception as e:
print(f"Error updating product DB: {e}")
def create_product_in_db(product_name, stock, threshold, unit, base_unit, price):
try:
conn = get_db_connection()
cur = conn.cursor()
cur.execute("""
INSERT INTO products (name, current_stock, threshold, unit, base_unit, price)
VALUES (%s, %s, %s, %s, %s, %s)
ON CONFLICT (name) DO NOTHING
""", (product_name, stock, threshold, unit, base_unit, price))
conn.commit()
cur.close()
conn.close()
except Exception as e:
print(f"Error creating product DB: {e}")
def log_transaction_in_db(action, product_name, quantity, unit, old_stock=None, new_stock=None):
try:
conn = get_db_connection()
cur = conn.cursor()
cur.execute("""
INSERT INTO transactions (product_name, quantity, transaction_type, unit, old_stock, new_stock)
VALUES (%s, %s, %s, %s, %s, %s)
""", (product_name, quantity, action, unit, old_stock, new_stock))
conn.commit()
cur.close()
conn.close()
except Exception as e:
print(f"Error logging transaction DB: {e}")
def load_transactions_from_db(limit=None):
"""Load transaction history from DB"""
try:
conn = get_db_connection()
cur = conn.cursor()
query = "SELECT id, product_name, quantity, transaction_type, unit, timestamp, old_stock, new_stock FROM transactions ORDER BY timestamp DESC"
if limit:
query += f" LIMIT {limit}"
cur.execute(query)
rows = cur.fetchall()
cur.close()
conn.close()
transactions = []
for r in rows:
transactions.append({
'id': r[0],
'product': r[1],
'quantity': r[2],
'action': r[3],
'unit': r[4],
'timestamp': r[5].strftime('%Y-%m-%d %H:%M:%S'),
'old_stock': r[6],
'new_stock': r[7]
})
return transactions
except Exception as e:
print(f"Error fetching transactions from DB: {e}")
return []
# User Credentials with Roles
USERS = {
"admin": {"password": "quickstock2026", "role": "admin"},
"shop_shrey": {"password": "shrey2026", "role": "shop"}
}
def login_required(f):
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user' not in session:
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
from functools import wraps
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user' not in session:
return redirect(url_for('login'))
if session.get('role') != 'admin':
from flask import abort
abort(403)
return f(*args, **kwargs)
return decorated_function
@app.route('/login', methods=['GET', 'POST'])
def login():
from flask import redirect, url_for, session, render_template, flash
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
user_data = USERS.get(username)
if user_data and user_data['password'] == password:
session['user'] = username
session['role'] = user_data['role']
# Redirect based on role
if user_data['role'] == 'admin':
return redirect(url_for('admin_panel'))
return redirect(url_for('home'))
else:
flash('Invalid credentials')
return render_template('login_template.html')
@app.route('/logout')
def logout():
from flask import session, redirect, url_for
session.clear()
return redirect(url_for('login'))
# Create uploads directory if it doesn't exist
os.makedirs('./test_audio_files', exist_ok=True)
# CSV file path for storing completed transactions
TRANSACTIONS_CSV = os.path.join(os.path.dirname(__file__), 'transactions_history.csv')
# Transaction log to track all inventory changes
transaction_log = []
# Pending confirmations from voice input
pending_confirmations = []
# Global status of Android Client
android_client_connected = False
# Hindi to English product name mapping
product_name_english = {
"पारले जी": "Parle-G",
"लेस": "Lays",
"डाबर हनी": "Dabur Honey",
"टाटा नमक": "Tata Salt",
"कोक": "Coke",
"साबुन": "Soap",
"आटा": "Wheat Flour",
"चावल": "Rice",
"दाल": "Lentils",
"चीनी": "Sugar",
"तेल": "Oil",
"दूध": "Milk",
"चाय": "Tea"
}
# Hindi to English unit name mapping
unit_name_english = {
"पैकेट": "Packet",
"बोतल": "Bottle",
"पीस": "Piece",
"किलो": "Kg",
"ग्राम": "Gram",
"लीटर": "Liter",
"मिलीलीटर": "ml"
}
# Enhanced database with measurement units and base units
# Enhanced database with measurement units and base units
products = {
"पारले जी": {"current_stock": 100, "threshold": 20, "unit": "पैकेट", "base_unit": "पैकेट", "price": 10},
"लेस": {"current_stock": 50, "threshold": 15, "unit": "पैकेट", "base_unit": "पैकेट", "price": 20},
"डाबर हनी": {"current_stock": 30, "threshold": 10, "unit": "बोतल", "base_unit": "बोतल", "price": 150},
"टाटा नमक": {"current_stock": 80, "threshold": 25, "unit": "पैकेट", "base_unit": "पैकेट", "price": 25},
"कोक": {"current_stock": 40, "threshold": 12, "unit": "बोतल", "base_unit": "बोतल", "price": 40},
"साबुन": {"current_stock": 25, "threshold": 8, "unit": "पीस", "base_unit": "पीस", "price": 35},
"आटा": {"current_stock": 100, "threshold": 25, "unit": "किलो", "base_unit": "किलो", "price": 45},
"चावल": {"current_stock": 150, "threshold": 30, "unit": "किलो", "base_unit": "किलो", "price": 60},
"दाल": {"current_stock": 80, "threshold": 20, "unit": "किलो", "base_unit": "किलो", "price": 120},
"चीनी": {"current_stock": 60, "threshold": 15, "unit": "किलो", "base_unit": "किलो", "price": 42},
"तेल": {"current_stock": 50, "threshold": 12, "unit": "लीटर", "base_unit": "लीटर", "price": 180},
"दूध": {"current_stock": 40, "threshold": 10, "unit": "लीटर", "base_unit": "लीटर", "price": 66},
"चाय": {"current_stock": 5, "threshold": 2, "unit": "किलो", "base_unit": "किलो", "price": 450},
}
# Measurement unit conversions (to base units)
unit_conversions = {
# English
'kg': 1, 'kilo': 1, 'kilogram': 1,
'grams': 0.001, 'gram': 0.001, 'g': 0.001, 'gm': 0.001,
'liters': 1, 'liter': 1, 'l': 1,
'ml': 0.001, 'milliliter': 0.001,
'packets': 1, 'packet': 1, 'pkt': 1,
'bottles': 1, 'bottle': 1,
'pieces': 1, 'piece': 1, 'pcs': 1,
# Devanagari
'किलो': 1,
'ग्राम': 0.001,
'ग्रा': 0.001,
'लीटर': 1,
'मिलीलीटर': 0.001,
'पैकेट': 1,
'बोतल': 1,
'पीस': 1,
}
# Text preprocessing functions
def preprocess_text(text):
"""Preprocess the input text for better NLU understanding."""
if not text:
return ""
print(f"Original text: '{text}'")
# Normalize Hindi text using Indic NLP normalizer (reduces spelling/diacritic variants)
try:
if _has_indicnlp_normalizer and re.search(r"[\u0900-\u097F]", text):
_normalizer = getattr(preprocess_text, "_indic_normalizer", None)
if _normalizer is None:
factory = IndicNormalizerFactory()
preprocess_text._indic_normalizer = factory.get_normalizer("hi")
_normalizer = preprocess_text._indic_normalizer
text = _normalizer.normalize(text)
print(f"[DEBUG] After IndicNLP normalize: '{text}'")
except Exception as _e:
print(f"[DEBUG] IndicNLP normalize skipped: {_e}")
# --- Normalize Hindi numerals and number words to ASCII digits ---
try:
# Map Devanagari digits to ASCII
devanagari_digits = str.maketrans('०१२३४५६७८९', '0123456789')
text = text.translate(devanagari_digits)
# Base Hindi number words to digits
hindi_number_words = {
'शून्य': '0', 'एक': '1', 'दो': '2', 'तीन': '3', 'चार': '4',
'पाँच': '5', 'पांच': '5', 'छह': '6', 'सात': '7', 'आठ': '8', 'नौ': '9',
'दस': '10', 'ग्यारह': '11', 'बारह': '12', 'तेरह': '13', 'चौदह': '14',
'पंद्रह': '15', 'पन्द्रह': '15', 'सोलह': '16', 'सत्रह': '17', 'अठारह': '18', 'उन्नीस': '19',
'बीस': '20', 'इक्कीस': '21', 'बाइस': '22', 'तेईस': '23', 'चौबीस': '24', 'पच्चीस': '25',
'छब्बीस': '26', 'सत्ताईस': '27', 'अट्ठाईस': '28', 'उनतीस': '29', 'उन्तीस': '29',
'तीस': '30', 'इकतीस': '31', 'इकत्तीस': '31', 'बत्तीς': '32', 'तैंतीस': '33', 'चौंतीस': '34', 'पैंतीस': '35',
'छत्तीस': '36', 'सैंतीस': '37', 'अड़तीस': '38', 'अडतीस': '38', 'उनतालीस': '39',
'चालीस': '40', 'इकतालीस': '41', 'बयालीस': '42', 'तैंतालीस': '43', 'चवालीस': '44', 'पैंतालीस': '45',
'छयालिस': '46', 'सैंतालीस': '47', 'अड़तालीस': '48', 'अड़तालीस': '48', 'उनचास': '49',
'पचास': '50', 'इक्याबन': '51', 'बावन': '52', 'त्रिपन': '53', 'चौवन': '54', 'पचपन': '55',
'छप्पन': '56', 'सत्तावन': '57', 'अठावन': '58', 'उनसठ': '59',
'साठ': '60', 'इकसठ': '61', 'बासठ': '62', 'तिरसठ': '63', 'चौंसठ': '64', 'पैंसठ': '65',
'छियासठ': '66', 'सड़सठ': '67', 'सड़सठ': '67', 'अड़सठ': '68', 'अड़सठ': '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'
}
# Compositional Hindi number parser for short phrases (e.g., "दो सौ बीस")
units = {
'शून्य':0,'एक':1,'दो':2,'तीन':3,'चार':4,'पांच':5,'पाँच':5,'छह':6,'सात':7,'आठ':8,'नौ':9,
'दस':10,'ग्यारह':11,'बारह':12,'तेरह':13,'चौदह':14,'पंद्रह':15,'पन्द्रह':15,'सोलह':16,'सत्रह':17,'अठारह':18,'उन्नीस':19
}
tens = {
'बीस':20,'तीस':30,'चालीस':40,'पचास':50,'साठ':60,'सत्तर':70,'अस्सी':80,'नब्बे':90
}
scales = {'सौ':100,'हज़ार':1000,'हजार':1000}
def parse_hindi_number_tokens(tok_seq):
total = 0
current = 0
matched_any = False
for tok in tok_seq:
if tok in hindi_number_words:
# Direct mapped composite word
current += int(hindi_number_words[tok])
matched_any = True
elif tok in units:
current += units[tok]
matched_any = True
elif tok in tens:
current += tens[tok]
matched_any = True
elif tok in scales:
if current == 0:
current = 1
current *= scales[tok]
total += current
current = 0
matched_any = True
else:
return None
return total + current if matched_any else None
# Token scan: replace sequences of number words with digits
tokens = text.split()
i = 0
out_tokens = []
while i < len(tokens):
parsed = None
parsed_len = 0
# try up to 4-word spans
for span in (4,3,2,1):
if i+span <= len(tokens):
val = parse_hindi_number_tokens(tokens[i:i+span])
if val is not None:
parsed = str(val)
parsed_len = span
break
if parsed is not None:
out_tokens.append(parsed)
i += parsed_len
else:
# single-word direct mapping fallback
w = tokens[i]
out_tokens.append(hindi_number_words.get(w, w))
i += 1
text = ' '.join(out_tokens)
print(f"[DEBUG] After Hindi number normalization: '{text}'")
except Exception as _e:
print(f"[DEBUG] Number normalization skipped: {_e}")
# Convert to lowercase
text = text.lower().strip()
# Remove extra whitespace
text = ' '.join(text.split())
print(f"[DEBUG] After trim/lower: '{text}'")
# Common Hinglish corrections and normalization
corrections = {
'beech': 'beche', 'bich': 'beche', 'bikgayi': 'bik gayi', 'bikgaya': 'bik gaya',
'aagaya': 'aa gaya', 'aagaye': 'aa gaye', 'aaya': 'aa gaya', 'aaye': 'aa gaye',
'daldo': 'daal do', 'addkardo': 'add kar do', 'stockcheck': 'stock check',
'kitnabacha': 'kitna bacha', 'kitnebacha': 'kitna bacha',
'bechi': 'beche', 'bechai': 'beche', 'bech': 'beche',
'kilo': 'kg', 'kilogram': 'kg', 'grams': 'g', 'gram': 'g',
'liters': 'l', 'liter': 'l', 'milliliter': 'ml',
}
# Apply corrections
words = text.split()
corrected_words = []
for word in words:
if word in corrections:
corrected_words.append(corrections[word])
else:
corrected_words.append(word)
text = ' '.join(corrected_words)
print(f"[DEBUG] After Hinglish corrections: '{text}'")
# Automatic ASR correction (fuzzy + cache + optional LLM)
try:
# lazy import local helper (defined below)
text = auto_correct_asr(text, product_names=list(products.keys()))
print(f"[DEBUG] After ASR auto-correct: '{text}'")
except Exception as e:
print(f"ASR auto-correct failed: {e}")
# Remove common filler words
filler_words = ['please', 'ji', 'hey', 'hello', 'okay', 'ok', 'toh', 'to', 'the', 'a', 'of']
words = text.split()
words = [word for word in words if word not in filler_words]
text = ' '.join(words)
print(f"Preprocessed text: '{text}'")
return text
# Enhanced helper function for product name matching (no fuzzy)
def find_product(product_name):
"""Finds a product by fuzzy name matching."""
product_name = product_name.strip()
print(f"[DEBUG] find_product input: '{product_name}'")
# Exact match
if product_name in products:
print(f"[DEBUG] find_product exact match: '{product_name}'")
return product_name
# Partial match (only for sufficiently long tokens)
if len(product_name) >= 3:
for known_product in products.keys():
if product_name in known_product or known_product in product_name:
print(f"[DEBUG] find_product partial matched '{product_name}' -> '{known_product}'")
return known_product
# Common Hindi product name mappings
hindi_to_english = {
'आटा': 'आटा',
'मैदा': 'आटा',
'चावल': 'चावल',
'राइस': 'चावल',
'दाल': 'दाल',
'नमक': 'टाटा नमक',
'टाटा नमक': 'टाटा नमक',
'शहद': 'डाबर हनी',
'हनी': 'डाबर हनी',
'चीनी': 'चीनी',
'शक्कर': 'चीनी',
'तेल': 'तेल',
'ऑयल': 'तेल',
'दूध': 'दूध',
'मिल्क': 'दूध',
'चाय': 'चाय',
'टी': 'चाय',
'पारले जी': 'पारले जी',
'लेज़': 'लेज़',
'कोक': 'कोक',
'साबुन': 'साबुन',
}
if product_name in hindi_to_english:
print(f"[DEBUG] find_product mapped '{product_name}' -> '{hindi_to_english[product_name]}'")
return hindi_to_english[product_name]
# Fuzzy fallback (difflib) for Devanagari names
if len(product_name) >= 3:
candidates = list(products.keys())
matches = difflib.get_close_matches(product_name, candidates, n=1, cutoff=0.75)
if matches:
print(f"[DEBUG] find_product fuzzy matched '{product_name}' -> '{matches[0]}'")
return matches[0]
return None
def parse_multiple_products_by_numbers(text):
"""Parse multiple products using number positions as delimiters.
Examples: '2 lays 3 parle g' or 'lays 2 parle g 3'
Returns list of (quantity, product_key, unit) tuples."""
print(f"[DEBUG] parse_multiple_products_by_numbers input: '{text}'")
# Find all numbers (digits) and their positions in the text
number_pattern = r'\d+(?:\.\d+)?'
numbers = []
for match in re.finditer(number_pattern, text):
numbers.append({
'value': float(match.group()),
'start': match.start(),
'end': match.end(),
'text': match.group()
})
# Also check for Hindi number words that might not have been converted
hindi_numbers = {
'एक': 1, 'दो': 2, 'तीन': 3, 'चार': 4, 'पाँच': 5, 'पांच': 5,
'छह': 6, 'सात': 7, 'आठ': 8, 'नौ': 9, 'दस': 10
}
tokens_temp = text.split()
for idx, token in enumerate(tokens_temp):
if token in hindi_numbers:
# Calculate approximate position
pos = sum(len(t) + 1 for t in tokens_temp[:idx])
numbers.append({
'value': float(hindi_numbers[token]),
'start': pos,
'end': pos + len(token),
'text': token
})
print(f"[DEBUG] Found Hindi number word '{token}' = {hindi_numbers[token]}")
# Sort by position
numbers.sort(key=lambda x: x['start'])
print(f"[DEBUG] Found {len(numbers)} numbers: {[n['text'] for n in numbers]}")
print(f"[DEBUG] Full text being parsed: '{text}'")
tokens = text.split()
print(f"[DEBUG] Tokens: {tokens}")
if len(numbers) < 2:
# Less than 2 numbers, not a multi-product command
print(f"[DEBUG] ⚠️ Only {len(numbers)} number(s) found, not multi-product - will try conjunction-based")
return None
results = []
tokens = text.split()
used_products = set() # Track which products have been used to avoid duplicates
used_token_indices = set() # Track which token positions have been used
# Track occurrence count for each unique number text
occurrence_tracker = {}
# Strategy: Each number represents a quantity for a product
# Look for product names near each number
for i, num_info in enumerate(numbers):
quantity = num_info['value']
# Extract text around this number
# Get tokens before and after the number
num_token_idx = None
num_text = num_info['text']
# Track which occurrence of this specific number text we're looking for
if num_text not in occurrence_tracker:
occurrence_tracker[num_text] = 0
occurrence_tracker[num_text] += 1
target_occurrence = occurrence_tracker[num_text]
# Find the target_occurrence-th occurrence of this number (could be digit or Hindi word)
current_occurrence = 0
for idx, token in enumerate(tokens):
if idx in used_token_indices:
continue # Skip already used positions
if num_text in token or token == num_text:
current_occurrence += 1
if current_occurrence == target_occurrence:
num_token_idx = idx
used_token_indices.add(idx)
print(f"[DEBUG] Found number '{num_text}' (occurrence {target_occurrence}) at token index {idx}")
break
if num_token_idx is None:
print(f"[DEBUG] Could not find token index for number '{num_text}' (occurrence {target_occurrence})")
continue
# Look for product name after the number (most common: "2 lays")
product_text = None
unit = None
# Define keywords to skip
keywords = ['बेचा', 'बेचे', 'बिक', 'दिया', 'आ', 'गया', 'गए', 'आया', 'जोड़', 'डाल', 'मिला', 'और', 'and', 'aur']
# Check tokens after the number
for offset in range(1, min(5, len(tokens) - num_token_idx)):
candidate = tokens[num_token_idx + offset]
# Check if it's a unit
if candidate.lower() in unit_conversions:
unit = candidate.lower()
print(f"[DEBUG] Found unit '{unit}' after number at offset {offset}")
# Product might be after the unit: "2 kg aata"
if num_token_idx + offset + 1 < len(tokens):
next_token = tokens[num_token_idx + offset + 1]
# Check if next token is not a number
if not re.match(r'^\d+(?:\.\d+)?$', next_token):
product_text = next_token
print(f"[DEBUG] Found product '{product_text}' after unit")
# Check for multi-word product names (but stop at next number)
if num_token_idx + offset + 2 < len(tokens):
next_next = tokens[num_token_idx + offset + 2]
if not re.match(r'^\d+(?:\.\d+)?$', next_next) and next_next.lower() not in keywords:
product_text += " " + next_next
print(f"[DEBUG] Extended product name to '{product_text}'")
break
continue
# Check if it's a number (next product's quantity)
if re.match(r'^\d+(?:\.\d+)?$', candidate):
break
# Check if it's a keyword (skip)
if candidate.lower() in keywords:
continue
# This is likely the product name
product_text = candidate
# Check for multi-word product names
if num_token_idx + offset + 1 < len(tokens):
next_token = tokens[num_token_idx + offset + 1]
# If next token is not a number and not a keyword, it's part of product name
if not re.match(r'^\d+(?:\.\d+)?$', next_token) and next_token.lower() not in keywords:
product_text += " " + next_token
break
# If no product found after number, check before (less common: "lays 2")
if not product_text and num_token_idx > 0:
for offset in range(1, min(3, num_token_idx + 1)):
candidate = tokens[num_token_idx - offset]
# Check if it's a unit
if candidate.lower() in unit_conversions:
unit = candidate.lower()
continue
# Check if it's a number
if re.match(r'^\d+(?:\.\d+)?$', candidate):
break
# Check if it's a keyword (keywords already defined above)
if candidate.lower() in keywords:
continue
product_text = candidate
# Check for multi-word product names before
if num_token_idx - offset - 1 >= 0:
prev_token = tokens[num_token_idx - offset - 1]
if not re.match(r'^\d+(?:\.\d+)?$', prev_token) and prev_token.lower() not in keywords:
product_text = prev_token + " " + product_text
break
if product_text:
product_key = find_product(product_text)
if product_key:
# Check if this product has already been used
if product_key in used_products:
print(f"[DEBUG] Product '{product_key}' already used, skipping duplicate")
continue
# Use detected unit or product's default unit
if not unit:
unit = products[product_key]['unit']
results.append((quantity, product_key, unit))
used_products.add(product_key)
print(f"[DEBUG] Extracted: qty={quantity}, product={product_key}, unit={unit}")
else:
print(f"[DEBUG] Product '{product_text}' not found in inventory")
return results if len(results) >= 2 else None
def parse_multiple_products_by_conjunctions(text):
"""Parse multiple products by splitting on conjunctions (FALLBACK METHOD).
Examples: '2 lays और 3 parle g'
Returns list of (quantity, product_key, unit) tuples."""
print(f"[DEBUG] parse_multiple_products_by_conjunctions input: '{text}'")
# Split by common separators: 'and', 'aur', 'और', 'तथा', 'व', ',', 'or', 'evam'
# Pattern allows optional spaces around separators
separators = r'\s*(?:and|aur|और|तथा|व|evam|एवं|or|,)\s*'
segments = re.split(separators, text, flags=re.IGNORECASE)
print(f"[DEBUG] Split into segments: {segments}")
results = []
for segment in segments:
segment = segment.strip()
if not segment:
continue
qty, prod, unit = parse_quantity_and_unit(segment)
if qty and prod:
results.append((qty, prod, unit))
print(f"[DEBUG] Parsed segment '{segment}' -> qty={qty}, product={prod}, unit={unit}")
return results if results else None
def parse_multiple_products(text):
"""Parse multiple products from text using multiple strategies.
Primary: Number-based detection ('2 lays 3 parle g')
Fallback: Conjunction-based splitting ('2 lays और 3 parle g')
Returns list of (quantity, product_key, unit) tuples."""
print(f"[DEBUG] ========== MULTI-PRODUCT PARSING ==========")
print(f"[DEBUG] Input text: '{text}'")
# Strategy 1: Number-based detection (PRIMARY)
print(f"[DEBUG] Trying Strategy 1: Number-based detection...")
results = parse_multiple_products_by_numbers(text)
if results and len(results) >= 2:
print(f"[DEBUG] ✅ Number-based parsing succeeded with {len(results)} products")
print(f"[DEBUG] Results: {results}")
return results
else:
print(f"[DEBUG] ❌ Number-based parsing returned: {results}")
# Strategy 2: Conjunction-based splitting (FALLBACK)
print(f"[DEBUG] Trying Strategy 2: Conjunction-based splitting...")
results = parse_multiple_products_by_conjunctions(text)
if results and len(results) >= 2:
print(f"[DEBUG] ✅ Conjunction-based parsing succeeded with {len(results)} products")
print(f"[DEBUG] Results: {results}")
return results
else:
print(f"[DEBUG] ❌ Conjunction-based parsing returned: {results}")
print(f"[DEBUG] ❌ Both multi-product parsing strategies failed")
print(f"[DEBUG] ==========================================")
return None
def parse_quantity_and_unit(text):
"""Parse quantity and unit from text, converting to base units."""
print(f"[DEBUG] parse_quantity_and_unit input: '{text}'")
# First, handle 'quantity + unit' only (no product specified)
unit_pattern = r'^(\d+(?:\.\d+)?)\s*(kg|kilo|kilogram|gram|g|gm|liters?|liter|l|ml|milliliter|packets?|packet|pkt|bottles?|bottle|pieces?|piece|pcs|किलो|ग्राम|ग्रा|लीटर|मिलीलीटर|पैकेट|बोतल|पीस)\s*$'
m_unit_only = re.search(unit_pattern, text)
if m_unit_only:
try:
qty = float(m_unit_only.group(1))
unit = m_unit_only.group(2).lower()
print(f"[DEBUG] Detected quantity+unit only: qty={qty}, unit='{unit}', no product")
return qty, None, unit
except Exception as _e:
print(f"[DEBUG] Unit-only parse failed: {_e}")
# Check if text contains conjunctions - if so, it might be a multi-product command
# that failed to parse, so return None to avoid incorrect parsing
conjunctions = ['और', 'aur', 'and', 'तथा', 'व', 'evam', 'एवं', 'or', ',']
if any(conj in text.lower() for conj in conjunctions):
print(f"[DEBUG] Text contains conjunctions, might be multi-product. Skipping single-product parse.")
# Still try to parse, but be more careful
# Patterns for different quantity formats
patterns = [
r'(\d+(?:\.\d+)?)\s*(kg|kilo|kilogram|gram|g|gm|liters?|liter|l|ml|milliliter|packets?|packet|pkt|bottles?|bottle|pieces?|piece|pcs|किलो|ग्राम|ग्रा|लीटर|मिलीलीटर|पैकेट|बोतल|पीस)\s+(\w+(?:\s+\w+)*)', # "2 kg आटा"
r'(\d+(?:\.\d+)?)\s+(\w+(?:\s+\w+)*)', # "2 आटा" (default unit)
r'(\w+(?:\s+\w+)*)\s+(\d+(?:\.\d+)?)\s*(kg|kilo|kilogram|gram|g|gm|liters?|liter|l|ml|milliliter|packets?|packet|pkt|bottles?|bottle|pieces?|piece|pcs|किलो|ग्राम|ग्रा|लीटर|मिलीलीटर|पैकेट|बोतल|पीस)', # "आटा 2 किलो"
]
for pattern in patterns:
print(f"[DEBUG] Trying pattern: {pattern}")
match = re.search(pattern, text)
if match:
print(f"[DEBUG] Regex matched groups: {match.groups()}")
if len(match.groups()) == 3:
# Validate that group(1) is actually a number
try:
quantity = float(match.group(1))
except ValueError:
# Group 1 is not a number, skip this pattern
print(f"[DEBUG] Group 1 '{match.group(1)}' is not a number, trying next pattern")
continue
unit = match.group(2).lower()
product_text = match.group(3)
else:
# Validate that group(1) is actually a number
try:
quantity = float(match.group(1))
except ValueError:
# Group 1 is not a number, skip this pattern
print(f"[DEBUG] Group 1 '{match.group(1)}' is not a number, trying next pattern")
continue
product_text = match.group(2)
unit = None # Will use product's default unit
# If the second group is actually a unit, treat as unit-only input
if product_text in unit_conversions:
print(f"[DEBUG] Second group is a unit ('{product_text}'); no product provided")
return quantity, None, product_text
product_key = find_product(product_text)
if product_key:
# If unit is specified, convert to product's base unit
if unit and unit in unit_conversions:
base_quantity = quantity * unit_conversions[unit]
actual_quantity = base_quantity / unit_conversions[products[product_key]['base_unit']]
print(f"[DEBUG] Parsed quantity={quantity}, unit='{unit}', product='{product_key}', actual_quantity={actual_quantity}")
return actual_quantity, product_key, unit
else:
# Use product's default unit
print(f"[DEBUG] Parsed quantity={quantity}, default unit for product='{product_key}'")
return quantity, product_key, products[product_key]['unit']
# Fallback: simple number and product detection
words = text.split()
print(f"[DEBUG] Fallback parsing tokens: {words}")
quantity = None
product_key = None
unit = None
for i, word in enumerate(words):
# Check if word is a number
if word.replace('.', '').isdigit():
quantity = float(word)
# Look for product in surrounding words
for j in range(max(0, i-2), min(len(words), i+3)):
potential_product = find_product(words[j])
if potential_product:
product_key = potential_product
unit = products[product_key]['unit']
break
break
return quantity, product_key, unit
def transcribe_audio_sr(filepath):
"""Transcribe audio using SpeechRecognition."""
recognizer = sr.Recognizer()
try:
with sr.AudioFile(filepath) as source:
print("Listening to audio...")
audio = recognizer.record(source)
text = recognizer.recognize_google(audio, language="en-IN")
return text
except sr.UnknownValueError:
print("Could not understand audio")
return ""
# --- ASR auto-correction helpers ---
_ASR_CACHE_PATH = os.path.join(os.path.dirname(__file__), "asr_corrections_cache.json")
_ASR_LOG_PATH = os.path.join(os.path.dirname(__file__), "asr_corrections_log.jsonl")
_ASR_REVIEW_PATH = os.path.join(os.path.dirname(__file__), "asr_corrections_review.json")
def load_asr_cache():
if os.path.exists(_ASR_CACHE_PATH):
try:
with open(_ASR_CACHE_PATH, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
return {}
def save_asr_cache(cache):
try:
with open(_ASR_CACHE_PATH, "w", encoding="utf-8") as f:
json.dump(cache, f, ensure_ascii=False, indent=2)
except Exception:
pass
def append_asr_log(fragment, chosen, source="auto", confidence=1.0):
rec = {
"fragment": fragment,
"chosen": chosen,
"source": source,
"confidence": float(confidence),
"timestamp": datetime.utcnow().isoformat()
}
try:
with open(_ASR_LOG_PATH, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
except Exception:
pass
def auto_correct_asr(text, product_names=None, openai_api_key=None, llm_timeout_seconds=8,
fuzzy_cutoff=0.78, top_n_grams=3):
"""Auto-correct likely ASR mishearings against product_names.
Uses a small persistent cache to remember mappings. Optional LLM path omitted by default.
"""
if product_names is None:
product_names = []
cache = load_asr_cache()
words = text.split()
corrected_words = []
i = 0
N = len(words)
while i < N:
matched = False
for n in range(min(top_n_grams, N - i), 0, -1):
fragment = " ".join(words[i:i+n]).lower()
# cached?
if fragment in cache:
corrected = cache[fragment]
corrected_words.extend(corrected.split())
i += n
matched = True
break
# Fuzzy match against product names (difflib)
close = difflib.get_close_matches(fragment, product_names, n=1, cutoff=fuzzy_cutoff)
if close:
candidate = close[0]
cache[fragment] = candidate
# compute rough confidence by sequence matcher
conf = SequenceMatcher(None, fragment, candidate).ratio()
append_asr_log(fragment, candidate, source="auto", confidence=conf)
corrected_words.extend(candidate.split())
i += n
matched = True
break
# Secondary best-score scan
best = None
best_score = 0.0
for p in product_names:
score = SequenceMatcher(None, fragment, p).ratio()
if score > best_score:
best_score = score
best = p
if best and best_score >= fuzzy_cutoff:
cache[fragment] = best
append_asr_log(fragment, best, source="auto", confidence=best_score)
corrected_words.extend(best.split())
i += n
matched = True
break
if not matched:
token = words[i].lower()
# optional LLM path — omitted by default for privacy/cost
if openai_api_key and token.isalpha():