Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
4018 lines (3464 loc) · 152 KB
/
Copy pathapp.py
File metadata and controls
4018 lines (3464 loc) · 152 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, flash, abort
import os
import time
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, timedelta
import psycopg2
from dotenv import load_dotenv
import hashlib, secrets
import requests as http_requests
import random
# Chat system imports
from flask_socketio import SocketIO, emit, join_room, leave_room, disconnect as ws_disconnect
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity, get_jwt
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import jwt as pyjwt
from chat_crypto import (
generate_conversation_key,
encrypt_key, decrypt_key,
encrypt_message, decrypt_message,
)
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
app = Flask(__name__)
app.secret_key = os.getenv("FLASK_SECRET_KEY", "quickstock_premium_secret_2026")
# JWT Configuration
app.config["JWT_SECRET_KEY"] = os.getenv("JWT_SECRET_KEY", "change-me-in-production")
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=8)
jwt_manager = JWTManager(app)
# Rate Limiter
limiter = Limiter(key_func=get_remote_address, app=app,
default_limits=["200 per minute"])
# Flask-SocketIO
socketio = SocketIO(
app,
async_mode="eventlet",
cors_allowed_origins="*",
ping_timeout=60,
ping_interval=25,
max_http_buffer_size=1_000_000,
)
def get_db_connection():
return psycopg2.connect(DATABASE_URL)
def hash_password(password: str) -> str:
return hashlib.sha256(password.encode()).hexdigest()
# User Credentials with Roles
USERS = {
"admin": {"password": hash_password("quickstock2026"), "role": "admin"},
"shop_shrey": {"password": hash_password("shrey2026"), "role": "shop"}
}
def generate_otp() -> str:
return str(random.randint(100000, 999999))
def send_otp_fast2sms(phone: str, otp: str) -> bool:
"""Send OTP via Fast2SMS free DLT route."""
api_key = os.getenv('FAST2SMS_API_KEY')
if not api_key:
print("FAST2SMS_API_KEY not found in .env")
return False
url = "https://www.fast2sms.com/dev/bulkV2"
payload = {
"route": "q",
"message": f"Your QuickStock OTP is {otp}. Valid for 10 minutes. Do not share.",
"language": "english",
"flash": 0,
"numbers": phone,
}
headers = {"authorization": api_key, "Content-Type": "application/json"}
try:
resp = http_requests.post(url, json=payload, headers=headers, timeout=8)
data = resp.json()
return data.get("return") == True
except Exception as e:
print(f"OTP send failed: {e}")
return False
def save_otp_to_db(phone: str, otp: str, purpose: str = 'login'):
conn = get_db_connection()
cur = conn.cursor()
expires = datetime.utcnow() + timedelta(minutes=10)
cur.execute("""
INSERT INTO otp_log (phone, otp_code, purpose, expires_at)
VALUES (%s, %s, %s, %s)
""", (phone, otp, purpose, expires))
conn.commit()
cur.close(); conn.close()
def verify_otp_from_db(phone: str, otp: str) -> bool:
conn = get_db_connection()
cur = conn.cursor()
cur.execute("""
SELECT id FROM otp_log
WHERE phone = %s AND otp_code = %s
AND used = FALSE AND expires_at > NOW()
ORDER BY created_at DESC LIMIT 1
""", (phone, otp))
row = cur.fetchone()
if row:
cur.execute("UPDATE otp_log SET used = TRUE WHERE id = %s", (row[0],))
conn.commit()
cur.close(); conn.close()
return row is not None
def get_nearby_shops(shop_id: int, radius_km: float = 2.0) -> list:
"""Find all shops within radius_km of the given shop."""
conn = get_db_connection()
cur = conn.cursor()
cur.execute("""
SELECT s2.id, s2.shop_name, s2.owner_name,
ROUND(ST_Distance(
s1.geom::geography,
s2.geom::geography
) / 1000.0, 2) AS distance_km,
s2.latitude, s2.longitude
FROM shops s1
JOIN shops s2 ON s1.id != s2.id
WHERE s1.id = %s
AND s2.geom IS NOT NULL
AND ST_DWithin(
s1.geom::geography,
s2.geom::geography,
%s * 1000 -- convert km to metres
)
ORDER BY distance_km
""", (shop_id, radius_km))
rows = cur.fetchall()
cur.close(); conn.close()
return [{'id': r[0], 'shop_name': r[1], 'owner': r[2], 'distance_km': r[3], 'latitude': r[4], 'longitude': r[5]} for r in rows]
def get_product_sales_trend(shop_id: int, days: int = 30) -> list:
"""Daily sales totals for the past N days."""
conn = get_db_connection()
cur = conn.cursor()
cur.execute("""
SELECT DATE(b.created_at) AS sale_date,
SUM(b.total) AS daily_total,
COUNT(b.id) AS bill_count
FROM bills b
WHERE b.shop_id = %s
AND b.created_at >= NOW() - INTERVAL '1 day' * %s
GROUP BY sale_date
ORDER BY sale_date
""", (shop_id, days))
rows = cur.fetchall()
cur.close(); conn.close()
return [{'date': str(r[0]), 'total': float(r[1]), 'bills': r[2]} for r in rows]
def get_top_selling_products(shop_id: int, limit: int = 10) -> list:
"""Top products by revenue for the current month."""
conn = get_db_connection()
cur = conn.cursor()
cur.execute("""
SELECT bi.product_name,
SUM(bi.quantity) AS total_qty,
SUM(bi.line_total) AS total_revenue
FROM bill_items bi
JOIN bills b ON bi.bill_id = b.id
WHERE b.shop_id = %s
AND DATE_TRUNC('month', b.created_at) = DATE_TRUNC('month', NOW())
GROUP BY bi.product_name
ORDER BY total_revenue DESC
LIMIT %s
""", (shop_id, limit))
rows = cur.fetchall()
cur.close(); conn.close()
return [{'product': r[0], 'qty': float(r[1]), 'revenue': float(r[2])} for r in rows]
WHATSAPP_API_URL = "https://graph.facebook.com/v19.0/{phone_id}/messages"
def send_whatsapp_message(to_number: str, message: str) -> bool:
"""Send a free-form WhatsApp message (only works within 24hr window)."""
phone_id = os.getenv('WHATSAPP_PHONE_ID')
token = os.getenv('WHATSAPP_TOKEN')
if not phone_id or not token:
print("WhatsApp credentials missing in .env")
return False
url = WHATSAPP_API_URL.format(phone_id=phone_id)
payload = {
"messaging_product": "whatsapp",
"to": to_number,
"type": "text",
"text": {"body": message}
}
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
try:
resp = http_requests.post(url, json=payload, headers=headers, timeout=10)
return resp.status_code == 200
except Exception as e:
print(f"WhatsApp send failed: {e}")
return False
def send_whatsapp_template(to_number: str, template_name: str, params: list) -> bool:
"""Send an approved WhatsApp template message (works anytime)."""
phone_id = os.getenv('WHATSAPP_PHONE_ID')
token = os.getenv('WHATSAPP_TOKEN')
if not phone_id or not token:
print("WhatsApp credentials missing in .env")
return False
url = WHATSAPP_API_URL.format(phone_id=phone_id)
components = [{
"type": "body",
"parameters": [{"type": "text", "text": p} for p in params]
}]
payload = {
"messaging_product": "whatsapp",
"to": to_number,
"type": "template",
"template": {
"name": template_name,
"language": {"code": "en"},
"components": components
}
}
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
try:
resp = http_requests.post(url, json=payload, headers=headers, timeout=10)
return resp.status_code == 200
except Exception as e:
print(f"WhatsApp template send failed: {e}")
return False
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':
abort(403)
return f(*args, **kwargs)
return decorated_function
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
data = request.form
username = data.get('username', '').strip()
password = data.get('password', '').strip()
shop_name = data.get('shop_name', '').strip()
phone = data.get('phone', '').strip()
address = data.get('address', '').strip()
city = data.get('city', '').strip()
pin_code = data.get('pin_code', '').strip()
lat = data.get('latitude') or None
lng = data.get('longitude') or None
if not all([username, password, shop_name, phone]):
return render_template('register_template.html', error='All fields required')
try:
conn = get_db_connection()
cur = conn.cursor()
cur.execute("""
INSERT INTO shops
(username, password_hash, shop_name, phone, address, city, pin_code, latitude, longitude)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (username, hash_password(password), shop_name, phone,
address, city, pin_code, lat, lng))
conn.commit()
cur.close(); conn.close()
return redirect(url_for('login'))
except Exception as e:
return render_template('register_template.html', error=f'Username or phone already exists.')
return render_template('register_template.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username', '').strip()
password = request.form.get('password', '').strip()
conn = get_db_connection()
cur = conn.cursor()
cur.execute(
"SELECT id, username, password_hash, role, shop_name FROM shops WHERE username = %s",
(username,)
)
row = cur.fetchone()
cur.close(); conn.close()
if row and row[2] == hash_password(password):
session['user'] = row[1]
session['user_id'] = row[0]
session['role'] = row[3]
session['shop'] = row[4]
if row[3] == 'admin':
return redirect(url_for('admin_panel'))
return redirect(url_for('dashboard'))
else:
flash('Invalid credentials')
return render_template('login_template.html')
@app.route('/login/otp/send', methods=['POST'])
def send_login_otp():
phone = request.form.get('phone', '').strip()
conn = get_db_connection()
cur = conn.cursor()
cur.execute("SELECT id, username, role, shop_name FROM shops WHERE phone = %s", (phone,))
shop = cur.fetchone()
cur.close(); conn.close()
if not shop:
flash('Phone number not registered.')
return redirect(url_for('login'))
otp = generate_otp()
save_otp_to_db(phone, otp, 'login')
success = send_otp_fast2sms(phone, otp)
if not success:
flash('Could not send OTP. Try password login.')
return redirect(url_for('login'))
session['otp_phone'] = phone
return render_template('otp_verify_template.html', phone=phone)
@app.route('/login/otp/verify', methods=['POST'])
def verify_login_otp():
phone = session.get('otp_phone')
otp_code = request.form.get('otp', '').strip()
if not phone or not verify_otp_from_db(phone, otp_code):
flash('Invalid or expired OTP.')
return render_template('otp_verify_template.html', phone=phone, error=True)
conn = get_db_connection()
cur = conn.cursor()
cur.execute("SELECT id, username, role, shop_name FROM shops WHERE phone = %s", (phone,))
row = cur.fetchone()
cur.close(); conn.close()
session['user'] = row[1]
session['user_id'] = row[0]
session['role'] = row[2]
session['shop'] = row[3]
session.pop('otp_phone', None)
return redirect(url_for('dashboard'))
@app.route('/logout')
def logout():
from flask import session, redirect, url_for
session.clear()
return redirect(url_for('login'))
@app.route('/')
@login_required
def dashboard():
if session.get('role') == 'wholesaler':
return render_template('wholesaler_dashboard_template.html')
return render_template('dashboard_template.html')
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()
# Get current threshold if not provided
if new_threshold is None:
cur.execute("SELECT threshold FROM products WHERE name = %s", (product_name,))
row = cur.fetchone()
current_threshold = float(row[0]) if row and row[0] is not None else 0.0
else:
current_threshold = new_threshold
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()
# --- Low-Stock Detection (Return True if low) ---
is_low = new_stock <= current_threshold
cur.close()
conn.close()
return is_low
except Exception as e:
print(f"Error updating product DB: {e}")
return False
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}")
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
# Removed duplicate app = Flask(__name__)
# Create uploads directory if it doesn't exist
os.makedirs('./test_audio_files', exist_ok=True)
# Pending confirmations from voice input
pending_confirmations = []
# Live bill cart — accumulates confirmed items for billing
live_bill_cart = {
"items": [], # [{product, qty, unit, price}]
"discount": 0,
"payment_mode": "cash"
}
# --- Global State & Caches ---
pending_confirmations = []
android_client_connected = False
# User-specific stats cache: {user_id: {"timestamp": float, "data": dict}}
_dashboard_stats_cache = {}
_stats_cache_duration = 15.0 # seconds
# Global status of Android Client
# android_client_connected is already defined above in Global State & Caches section
# 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"
}
# Products are now fetched from DB dynamically using get_all_products_db()
# The global 'products' dict is removed. Functions should call get_all_products_db()
# or query the database directly.
# 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:
current_products = get_all_products_db()
# lazy import local helper (defined below)
text = auto_correct_asr(text, product_names=list(current_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, inventory=None):
"""Finds a product by name matching."""
product_name = product_name.strip()
print(f"[DEBUG] find_product input: '{product_name}'")
current_products = inventory if inventory is not None else get_all_products_db()
# Exact match
if product_name in current_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 current_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:
mapped_name = hindi_to_english[product_name]
print(f"[DEBUG] find_product mapped '{product_name}' -> '{mapped_name}'")
return mapped_name
# Check the global English-to-Hindi mapping
name_lower = product_name.lower()
for hi, en in product_name_english.items():
if en.lower() == name_lower:
print(f"[DEBUG] find_product mapped English '{product_name}' -> Hindi '{hi}'")
return hi
# Fuzzy fallback (difflib) for Devanagari names
if len(product_name) >= 3:
candidates = list(current_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, inventory=None):
"""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."""
inventory = inventory if inventory is not None else get_all_products_db()
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