-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase_manager.py
More file actions
3527 lines (3031 loc) · 140 KB
/
Copy pathdatabase_manager.py
File metadata and controls
3527 lines (3031 loc) · 140 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
# -*- coding: utf-8 -*-
"""
Database Manager - a Windows 11 styled GUI
==========================================================================
Merges many files into a single Excel database. It is not limited to
contacts: the columns come from a "schema", so products, students or any
list of your own work just as well.
How it is used:
1) "New database" -> you pick the type, that is, the set of columns
"Open database" -> the columns are read from the file and numbering
continues from the last row
2) "Add contacts" -> you are asked who the file came from and that goes
into the "Source" column
3) Repeated rows are marked red. Which column identifies a duplicate is
part of the schema, and the marking is kept in Excel too.
Speaks three languages: Uzbek, Russian and English.
Run with: python database_manager.py
"""
import os
import re
import csv
import sys
import json
import copy
import ctypes
import shutil
import datetime
import traceback
import subprocess
import tkinter as tk
from tkinter import ttk, filedialog
from tkinter import font as tkfont
from openpyxl import Workbook, load_workbook
from openpyxl.styles import PatternFill, Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter
try:
import sv_ttk
HAS_SV = True
except ImportError:
HAS_SV = False
try: # lets files be dropped on the window
from tkinterdnd2 import TkinterDnD, DND_FILES
HAS_DND = True
except Exception:
HAS_DND = False
# ================================================================= translations
#
# Three strings per key: (Uzbek, Russian, English).
# When you add a string, fill in all three.
LANG_ORDER = ("uz", "ru", "en")
LANG_NAMES = {"uz": "O'zbekcha", "ru": "Русский", "en": "English"}
LANG_SHORT = {"uz": "UZ", "ru": "RU", "en": "EN"}
LANG = "uz" # current language (read from settings)
TR = {
# --- dastur nomi va logotip
"app_name": ("Baza Menejeri", "Менеджер баз", "Database Manager"),
"brand1": ("Baza Menejeri", "Менеджер баз", "Database Manager"),
# --- baza turlari (shablonlar)
"tpl_choose": ("Baza turini tanlang", "Выберите тип базы",
"Choose the database type"),
"tpl_contacts": ("Kontaktlar", "Контакты", "Contacts"),
"tpl_products": ("Mahsulotlar", "Товары", "Products"),
"tpl_students": ("Talabalar", "Студенты", "Students"),
"tpl_custom": ("O'z ustunlarim…", "Свои столбцы…", "My own columns…"),
"tpl_opened": ("Fayldan o'qilgan", "Прочитано из файла", "Read from file"),
# --- shablon ustunlari
"h_pname": ("Nomi", "Название", "Name"),
"h_code": ("Kod / Artikul", "Код / Артикул", "Code / SKU"),
"h_price": ("Narxi", "Цена", "Price"),
"h_qty": ("Soni", "Количество", "Quantity"),
"h_group": ("Guruh", "Группа", "Group"),
# --- ustunlarni o'zim tuzish
"sch_title": ("O'z ustunlarim", "Свои столбцы", "My own columns"),
"sch_head": ("Baza ustunlarini yozing", "Укажите столбцы базы",
"Define the database columns"),
"sch_body": ("Har bir ustunni alohida qatorga yozing.\n"
"Tartib raqami va manba ustuni pastdagi tugmachalar bilan "
"qo'shiladi.",
"Каждый столбец — с новой строки.\n"
"Номер по порядку и столбец источника добавляются "
"флажками ниже.",
"One column per line.\n"
"The row number and source columns are added with the "
"checkboxes below."),
"sch_key": ("Dublikat qaysi ustun bo'yicha topilsin?",
"По какому столбцу искать дубликаты?",
"Which column identifies duplicates?"),
"sch_no": ("Tartib raqami ustuni bo'lsin (№)",
"Добавить столбец с номером по порядку (№)",
"Add a row-number column (#)"),
"sch_src": ("Manba ustuni bo'lsin (fayl kimdan olingani)",
"Добавить столбец источника (от кого получен файл)",
"Add a source column (who the file came from)"),
"sch_none": ("— dublikat tekshirilmasin —", "— не искать дубликаты —",
"— do not check duplicates —"),
"sch_err": ("Ustun yozilmadi", "Столбцы не указаны", "No columns given"),
"sch_err_b": ("Kamida bitta ustun nomini yozing.",
"Укажите хотя бы один столбец.",
"Enter at least one column name."),
"sch_mode": ("Solishtirish usuli", "Способ сравнения", "Comparison method"),
"km_phone": ("telefon raqami sifatida", "как телефонный номер",
"as a phone number"),
"km_text": ("matn sifatida", "как текст", "as text"),
"km_number": ("raqam sifatida", "как число", "as a number"),
# --- yon panel bo'limlari
"sec_base": ("BAZA", "БАЗА", "DATABASE"),
"sec_contacts": ("KONTAKTLAR", "КОНТАКТЫ", "CONTACTS"),
"sec_output": ("CHIQARISH", "ЭКСПОРТ", "OUTPUT"),
# --- yon panel tugmalari
"nav_new": ("Yangi baza", "Новая база", "New database"),
"nav_open": ("Eski bazani ochish", "Открыть базу", "Open database"),
"nav_recent": ("Oxirgi fayllar", "Недавние файлы", "Recent files"),
"nav_add": ("Kontakt qo'shish", "Добавить контакты", "Add contacts"),
"nav_manual": ("Qo'lda qo'shish", "Добавить вручную", "Add manually"),
"nav_save": ("Saqlash", "Сохранить", "Save"),
"nav_saveas": ("Boshqa nom bilan", "Сохранить как", "Save as"),
"nav_excel": ("Excelda ochish", "Открыть в Excel", "Open in Excel"),
"nav_lang": ("Til", "Язык", "Language"),
"nav_dark": ("Tungi rejim", "Тёмная тема", "Dark mode"),
"nav_light": ("Kunduzgi rejim", "Светлая тема", "Light mode"),
# --- jadval sarlavhalari (Excelga ham shular yoziladi)
"h_no": ("№", "№", "#"),
"h_name": ("Ism Familiya", "Имя Фамилия", "Full Name"),
"h_phone": ("Telefon", "Телефон", "Phone"),
"h_id": ("ID", "ID", "ID"),
"h_source": ("Manba (kimdan olindi)", "Источник (от кого получено)",
"Source (from whom)"),
# --- ko'rsatkich kartalari
"card_total": ("Jami qator", "Всего строк", "Total rows"),
"card_dup": ("Dublikat", "Дубликаты", "Duplicates"),
"card_src": ("Manba raqam", "Источников", "Sources"),
"card_view": ("Ko'rinmoqda", "Показано", "Shown"),
# --- qidiruv va filtrlar
"search_ph": ("Ism, raqam yoki manba…", "Имя, номер или источник…",
"Name, number or source…"),
"only_dups": ("Faqat dublikatlar", "Только дубликаты", "Duplicates only"),
"last9": ("Oxirgi 9 raqam bo'yicha", "По последним 9 цифрам",
"Match last 9 digits"),
"btn_del_bar": (" O'chirish ", " Удалить ", " Delete "),
"btn_src_bar": (" Manbani o'zgartirish ", " Изменить источник ",
" Change source "),
# --- bo'sh holat
"empty_title": ("Baza hozircha bo'sh", "База пока пуста",
"The database is empty"),
"empty_text": (
"Chapdagi «Yangi baza» tugmasi bilan yangi ro'yxat boshlang\n"
"yoki «Eski bazani ochish» orqali mavjud Excel faylni yuklang.",
"Начните новый список кнопкой «Новая база» слева\n"
"или загрузите готовый файл через «Открыть базу».",
"Start a new list with “New database” on the left,\n"
"or load an existing file with “Open database”."),
# --- yuqori sarlavha va pastki qator
"new_base_label": ("Yangi baza", "Новая база", "New database"),
"not_saved": ("hali saqlanmagan", "ещё не сохранено", "not saved yet"),
"keys_hint": (
"Ctrl+S saqlash · Ctrl+Z ortga · Ctrl+C nusxa · "
"ikki marta bosib tahrirlash",
"Ctrl+S сохранить · Ctrl+Z отменить · Ctrl+C копировать · "
"двойной клик — правка",
"Ctrl+S save · Ctrl+Z undo · Ctrl+C copy · "
"double-click to edit"),
"hint_start": ("Boshlash uchun baza tanlang", "Выберите базу, чтобы начать",
"Choose a database to start"),
"hint_new": ("Yangi baza — raqamlash 1 dan boshlanadi",
"Новая база — нумерация начнётся с 1",
"New database — numbering starts at 1"),
"hint_next": ("Keyingi qator raqami: {n}", "Номер следующей строки: {n}",
"Next row number: {n}"),
"hint_added": ("Yangi qatorlar yashil rangda · "
"Ctrl+Z bilan ortga qaytarish mumkin",
"Новые строки выделены зелёным · Ctrl+Z отменит",
"New rows are green · Ctrl+Z undoes it"),
"hint_saved": ("Saqlandi: {path}", "Сохранено: {path}", "Saved: {path}"),
# --- umumiy tugmalar
"btn_ok": ("OK", "ОК", "OK"),
"btn_close": ("Yopish", "Закрыть", "Close"),
"btn_cancel": ("Bekor", "Отмена", "Cancel"),
"btn_save": ("Saqlash", "Сохранить", "Save"),
"btn_add": ("Qo'shish", "Добавить", "Add"),
"btn_delete": ("O'chirish", "Удалить", "Delete"),
"dlg_msg": ("Xabar", "Сообщение", "Message"),
"dlg_err": ("Xato", "Ошибка", "Error"),
# --- saqlanmagan o'zgarishlar
"unsaved_title": ("Saqlanmagan o'zgarishlar", "Несохранённые изменения",
"Unsaved changes"),
"unsaved_head": ("Bazada saqlanmagan o'zgarishlar bor",
"В базе есть несохранённые изменения",
"The database has unsaved changes"),
"unsaved_body": ("Davom etishdan oldin saqlaymizmi?",
"Сохранить перед продолжением?",
"Save before continuing?"),
"btn_dont_save": ("Saqlamasdan", "Не сохранять", "Don't save"),
# --- fayl tanlash oynalari
"fd_open": ("Eski Excel bazani tanlang", "Выберите файл базы",
"Choose an existing database"),
"fd_add": ("Kontaktlar faylini tanlang (bir nechta bo'lishi mumkin)",
"Выберите файлы контактов (можно несколько)",
"Choose contact files (multiple allowed)"),
"fd_save": ("Bazani saqlash", "Сохранить базу", "Save database"),
"ft_all": ("Barcha fayllar", "Все файлы", "All files"),
"ft_contacts": ("Kontakt fayllari", "Файлы контактов", "Contact files"),
"ft_text": ("Matnli fayl", "Текстовый файл", "Text file"),
"ft_vcard": ("Telefon eksporti (vCard)", "Экспорт с телефона (vCard)",
"Phone export (vCard)"),
"ft_xlsx": ("Excel fayl", "Файл Excel", "Excel file"),
# --- kutish oynasi
"busy_load": ("Yuklanmoqda: {name}", "Загрузка: {name}",
"Loading: {name}"),
"busy_read": ("O'qilmoqda ({n}/{total}): {name}",
"Чтение ({n}/{total}): {name}",
"Reading ({n}/{total}): {name}"),
# --- manba raqamini so'rash
"src_title": ("Manba raqami", "Номер источника", "Source number"),
"src_head": ("Bu kontaktlar kimning raqamidan olindi?",
"С чьего номера получены эти контакты?",
"Whose number did these contacts come from?"),
"src_body": (
"Fayl: {file}\nBu fayldagi kontaktlar: {n} ta\n\n"
"Yozgan raqamingiz shu fayldan keladigan {n} ta qatorning "
"oxirgi «Manba» ustuniga qo'yiladi.",
"Файл: {file}\nКонтактов в файле: {n}\n\n"
"Введённый номер будет записан в столбец «Источник» "
"для всех {n} строк из этого файла.",
"File: {file}\nContacts in this file: {n}\n\n"
"The number you enter goes into the “Source” column "
"for all {n} rows from this file."),
"srcempty_title": ("Manba bo'sh", "Источник не указан", "Source is empty"),
"srcempty_head": ("Manba raqami yozilmadi", "Номер источника не введён",
"No source number entered"),
"srcempty_body": (
"«Manba» ustuni bo'sh qoladi — keyin kimning kontakti ekanini "
"bilib bo'lmaydi.\nBaribir davom etamizmi?",
"Столбец «Источник» останется пустым — потом будет не понять, "
"чьи это контакты.\nВсё равно продолжить?",
"The “Source” column will stay empty — you won't know whose "
"contacts these are later.\nContinue anyway?"),
"btn_back": ("Orqaga qaytish", "Вернуться", "Go back"),
"btn_leave_empty": ("Bo'sh qoldirish", "Оставить пустым", "Leave empty"),
# --- dublikatlar
"dup_title": ("Dublikat raqamlar", "Дублирующиеся номера",
"Duplicate numbers"),
"dup_head": ("{n} ta takrorlangan raqam topildi", "Найдено дубликатов: {n}",
"{n} duplicate numbers found"),
"dup_body": (
"«{file}» faylidagi ba'zi raqamlar bazada allaqachon bor.\n\n"
"Qo'shish — hammasi qo'shiladi, dublikatlar qizil belgilanadi\n"
"Tashlab ketish — faqat yangi raqamlar qo'shiladi",
"Некоторые номера из файла «{file}» уже есть в базе.\n\n"
"Добавить — добавятся все, дубликаты выделятся красным\n"
"Пропустить — добавятся только новые номера",
"Some numbers in “{file}” are already in the database.\n\n"
"Add — everything is added, duplicates marked red\n"
"Skip — only new numbers are added"),
"btn_skip": ("Tashlab ketish", "Пропустить", "Skip"),
# --- xatolar
"err_read": ("Faylni o'qib bo'lmadi", "Не удалось прочитать файл",
"Could not read the file"),
"err_file_read": ("«{file}» o'qilmadi", "«{file}» не прочитан",
"“{file}” could not be read"),
"err_file_empty": ("«{file}» bo'sh", "«{file}» пуст", "“{file}” is empty"),
"err_file_empty_b": ("Faylda kontakt qatorlari topilmadi.",
"В файле не найдено строк с контактами.",
"No contact rows found in the file."),
"err_norow": ("Qator tanlanmagan", "Строка не выбрана", "No row selected"),
"err_norow_multi": ("Avval jadvaldan bir yoki bir nechta qatorni tanlang.",
"Сначала выберите одну или несколько строк в таблице.",
"Select one or more rows in the table first."),
"err_norow_one": ("Avval jadvaldan qatorni tanlang.",
"Сначала выберите строку в таблице.",
"Select a row in the table first."),
"err_norow_any": ("Avval jadvaldan qator(lar)ni tanlang.",
"Сначала выберите строку или строки.",
"Select row(s) in the table first."),
"err_empty_base": ("Baza bo'sh", "База пуста", "The database is empty"),
"err_empty_base_b": ("Saqlash uchun hech qanday qator yo'q.",
"Нечего сохранять — нет ни одной строки.",
"There are no rows to save."),
"err_busy": ("Fayl band", "Файл занят", "File is in use"),
"err_busy_b": ("Fayl Excelda ochiq bo'lsa kerak.\n"
"Excelni yoping va qaytadan saqlang.\n\n"
"Eski fayl o'zgarmadi.",
"Похоже, файл открыт в Excel.\n"
"Закройте Excel и сохраните ещё раз.\n\n"
"Старый файл не изменён.",
"The file is probably open in Excel.\n"
"Close Excel and save again.\n\n"
"The old file is unchanged."),
"err_save": ("Saqlab bo'lmadi", "Не удалось сохранить", "Could not save"),
"err_save_b": ("{err}\n\nEski fayl o'zgarmadi.",
"{err}\n\nСтарый файл не изменён.",
"{err}\n\nThe old file is unchanged."),
"err_notfound": ("Fayl topilmadi", "Файл не найден", "File not found"),
"err_notfound_b": ("Avval bazani saqlang.", "Сначала сохраните базу.",
"Save the database first."),
"err_open": ("Ochib bo'lmadi", "Не удалось открыть", "Could not open"),
"err_unexpected": ("Kutilmagan xato", "Непредвиденная ошибка",
"Unexpected error"),
"err_unexpected_b": ("{name}: {msg}\n\nBatafsil ma'lumot shu faylda:\n{log}",
"{name}: {msg}\n\nПодробности в файле:\n{log}",
"{name}: {msg}\n\nDetails are in this file:\n{log}"),
# --- tahrirlash
"edit_src_title": ("Manbani o'zgartirish", "Изменить источник",
"Change source"),
"edit_src_head": ("Tanlangan {n} ta qator uchun manba",
"Источник для выбранных строк ({n})",
"Source for {n} selected row(s)"),
"edit_src_body": ("Yangi qiymatni kiriting:", "Введите новое значение:",
"Enter the new value:"),
"edit_row_title": ("Qatorni tahrirlash", "Редактировать строку", "Edit row"),
"edit_row_head": ("{no}-qator", "Строка {no}", "Row {no}"),
"edit_row_body": ("Qiymatlarni o'zgartiring:", "Измените значения:",
"Change the values:"),
"add_title": ("Yangi kontakt", "Новый контакт", "New contact"),
"add_head": ("Yangi kontakt qo'shish", "Добавить новый контакт",
"Add a new contact"),
"add_body": ("Kamida ism yoki telefon to'ldirilishi kerak:",
"Нужно заполнить хотя бы имя или телефон:",
"At least a name or a phone is required:"),
"add_empty": ("Bo'sh kontakt", "Пустой контакт", "Empty contact"),
"add_empty_b": ("Hech bo'lmasa ism yoki telefon yozilishi kerak.",
"Нужно указать хотя бы имя или телефон.",
"You must enter at least a name or a phone."),
# --- o'chirish
"del_title": ("O'chirish", "Удаление", "Delete"),
"del_head": ("{n} ta qator o'chirilsinmi?", "Удалить строк: {n}?",
"Delete {n} row(s)?"),
"del_body": ("Xato bo'lsa Ctrl+Z bilan qaytarib olsangiz bo'ladi.",
"Если ошиблись — Ctrl+Z вернёт.",
"If it's a mistake, Ctrl+Z brings them back."),
# --- qisqa xabarlar
"t_loaded": ("{n} ta qator yuklandi", "Загружено строк: {n}",
"{n} rows loaded"),
"t_added": ("{n} ta qator qo'shildi", "Добавлено строк: {n}",
"{n} rows added"),
"t_skipped": (", {n} ta dublikat tashlandi", ", пропущено дубликатов: {n}",
", {n} duplicates skipped"),
"t_src_changed": ("{n} ta qatorning manbasi o'zgartirildi",
"Источник изменён у строк: {n}",
"Source changed for {n} row(s)"),
"t_row_updated": ("Qator yangilandi", "Строка обновлена", "Row updated"),
"t_contact_added": ("Kontakt qo'shildi", "Контакт добавлен",
"Contact added"),
"t_deleted": ("{n} ta qator o'chirildi", "Удалено строк: {n}",
"{n} rows deleted"),
"t_saved": ("{n} ta qator saqlandi", "Сохранено строк: {n}",
"{n} rows saved"),
"t_copied": ("{n} ta qator nusxa olindi", "Скопировано строк: {n}",
"{n} rows copied"),
"t_select_first": ("Avval qator tanlang", "Сначала выберите строку",
"Select a row first"),
"t_recent_empty": ("Oxirgi fayllar ro'yxati hozircha bo'sh",
"Список недавних файлов пуст",
"The recent files list is empty"),
"t_recent_cleared": ("Ro'yxat tozalandi", "Список очищен", "List cleared"),
"menu_clear": ("Ro'yxatni tozalash", "Очистить список", "Clear the list"),
# --- vositalar menyusi
"nav_tools": ("Vositalar", "Инструменты", "Tools"),
"tool_paste": ("Buferdan qo'yish (Ctrl+V)",
"Вставить из буфера (Ctrl+V)",
"Paste from clipboard (Ctrl+V)"),
"tool_normalize": ("Telefon formatini birxillashtirish",
"Привести телефоны к одному виду",
"Normalize phone format"),
"tool_problems": ("Faqat shubhali qatorlar",
"Только подозрительные строки",
"Suspicious rows only"),
"tool_csv": ("CSV ga eksport", "Экспорт в CSV", "Export to CSV"),
"tool_vcard": ("vCard ga eksport (telefon uchun)",
"Экспорт в vCard (для телефона)",
"Export to vCard (for phone)"),
# --- buferdan qo'yish
"clip_label": ("buferdan", "из буфера", "clipboard"),
"err_clip": ("Buferda kontakt yo'q", "В буфере нет контактов",
"No contacts in the clipboard"),
"err_clip_b": ("Exceldan yoki matndan qatorlarni nusxa oling "
"va qaytadan urinib ko'ring.",
"Скопируйте строки из Excel или из текста и повторите.",
"Copy rows from Excel or from text and try again."),
# --- manbani qayta ishlatish
"apply_all": ("Qolgan fayllarga ham shu raqam",
"Этот же номер для остальных файлов",
"Use this number for the remaining files"),
# --- telefon formati va shubhali qatorlar
"t_normalized": ("{n} ta raqam formati o'zgartirildi",
"Формат изменён у номеров: {n}",
"{n} phone numbers reformatted"),
"t_normalized_none": ("Hamma raqam allaqachon bir xil ko'rinishda",
"Все номера уже в едином виде",
"All numbers are already in the same format"),
"u_normalize": ("telefon formati birxillashtirildi",
"формат телефонов приведён к одному виду",
"phone format normalized"),
"t_problems": ("{n} ta shubhali qator", "Подозрительных строк: {n}",
"{n} suspicious rows"),
"t_no_problems": ("Shubhali qator topilmadi", "Подозрительных строк нет",
"No suspicious rows found"),
# --- eksport
"fd_csv": ("CSV ga saqlash", "Сохранить в CSV", "Save as CSV"),
"fd_vcard": ("vCard ga saqlash", "Сохранить в vCard", "Save as vCard"),
"ft_csv": ("CSV fayl", "Файл CSV", "CSV file"),
"ft_vcf": ("vCard fayl", "Файл vCard", "vCard file"),
"t_exported": ("{n} ta kontakt eksport qilindi",
"Экспортировано контактов: {n}", "{n} contacts exported"),
"busy_save": ("Saqlanmoqda: {name}", "Сохранение: {name}",
"Saving: {name}"),
# --- bo'sh ekrandagi oxirgi fayllar
"empty_recent": ("Oxirgi ochilganlar:", "Недавно открытые:",
"Recently opened:"),
# --- ortga qaytarish
"undo_word": ("Ortga qaytarildi", "Отменено", "Undone"),
"redo_word": ("Qaytadan bajarildi", "Возвращено", "Redone"),
"undo_empty": ("Ortga qaytariladigan amal yo'q", "Нечего отменять",
"Nothing to undo"),
"redo_empty": ("Qaytadan bajariladigan amal yo'q", "Нечего возвращать",
"Nothing to redo"),
"u_files": ("{n} ta fayl qo'shildi", "добавлено файлов: {n}",
"{n} files added"),
"u_src": ("{n} ta qatorning manbasi o'zgartirildi",
"изменён источник у {n} строк", "source changed for {n} rows"),
"u_row": ("{no}-qator tahrirlandi", "строка {no} изменена",
"row {no} edited"),
"u_manual": ("qo'lda kontakt qo'shildi", "контакт добавлен вручную",
"contact added manually"),
"u_del": ("{n} ta qator o'chirildi", "удалено строк: {n}",
"{n} rows deleted"),
}
def t(key, **kw):
"""Return the text in the current language, or the key if it is unknown."""
row = TR.get(key)
if row is None:
return key
try:
text = row[LANG_ORDER.index(LANG)]
except (ValueError, IndexError):
text = row[0]
return text.format(**kw) if kw else text
# ===================================================================== schema
#
# A schema describes the shape of a database. The application is not tied to
# contacts: the columns come from here, so any kind of list works.
#
# cols - the columns. Each one holds:
# key - internal name (stable, also written to the file)
# tkey - translation key (for the built-in templates)
# title - literal text (for user-defined columns)
# width - width in the table
# role — "no" | "name" | "phone" | "id" | "src" | ""
# key_col - column duplicates are matched on (None disables the check)
# key_mode — "phone" | "text" | "number"
SCHEMA_SHEET = "_schema" # hidden sheet the schema is stored in
def col(key, width, role="", tkey=None, title=None):
return {"key": key, "width": width, "role": role,
"tkey": tkey, "title": title}
TEMPLATES = {
"kontakt": {
"tkey": "tpl_contacts",
"cols": [col("no", 55, "no", "h_no"),
col("name", 270, "name", "h_name"),
col("phone", 190, "phone", "h_phone"),
col("id", 130, "id", "h_id"),
col("source", 220, "src", "h_source")],
"key_col": "phone", "key_mode": "phone",
},
"mahsulot": {
"tkey": "tpl_products",
"cols": [col("no", 55, "no", "h_no"),
col("name", 260, "name", "h_pname"),
col("code", 160, "id", "h_code"),
col("price", 110, "", "h_price"),
col("qty", 90, "", "h_qty"),
col("source", 200, "src", "h_source")],
"key_col": "code", "key_mode": "text",
},
"talaba": {
"tkey": "tpl_students",
"cols": [col("no", 55, "no", "h_no"),
col("name", 260, "name", "h_name"),
col("group", 120, "", "h_group"),
col("phone", 180, "phone", "h_phone"),
col("id", 130, "id", "h_id"),
col("source", 200, "src", "h_source")],
"key_col": "phone", "key_mode": "phone",
},
}
def default_schema():
"""The default schema: contacts."""
return copy.deepcopy(TEMPLATES["kontakt"]) | {"name": "kontakt"}
def col_title(c):
"""Column header. Built-in templates are translated, custom ones are not."""
if c.get("tkey"):
return t(c["tkey"])
return c.get("title") or c["key"]
def schema_title(schema):
"""Display name of the schema, shown in the sidebar."""
if schema.get("tkey"):
return t(schema["tkey"])
return t("tpl_opened")
def schema_fields(schema):
return [c["key"] for c in schema["cols"]]
def headers(schema):
"""Column headers for the table and for Excel, in the current language."""
return [col_title(c) for c in schema["cols"]]
def role_col(schema, role):
"""Key of the first column with the given role, or None."""
for c in schema["cols"]:
if c.get("role") == role:
return c["key"]
return None
def data_cols(schema, with_src=False):
"""
The columns read from a file. The row-number column is never read, it
is regenerated. The source column depends on the situation:
- ADDING a contact file: not read, the user types the number
- OPENING our own database: read, otherwise the value would be lost
"""
skip = ("no",) if with_src else ("no", "src")
return [c for c in schema["cols"] if c.get("role") not in skip]
def blank_row(schema):
return {c["key"]: "" for c in schema["cols"]}
def row_key(row, schema, last9=True):
"""Comparison key for duplicate detection; empty when the schema has none."""
kc = schema.get("key_col")
if not kc:
return ""
value = row.get(kc)
mode = schema.get("key_mode", "text")
if mode == "phone":
return norm_phone(value, last9)
if mode == "number":
return re.sub(r"\D", "", cell_text(value))
return cell_text(value).casefold()
def title_variants(c):
"""The header text in all three languages, used to recognise a file."""
if c.get("tkey") and c["tkey"] in TR:
return {s.strip().lower() for s in TR[c["tkey"]] if s.strip()}
return {cell_text(c.get("title") or c["key"]).lower()}
APP_NAME = "Database Manager"
# settings and the error log live here
_APPDATA = os.environ.get("APPDATA") or os.path.expanduser("~")
CONFIG_DIR = os.path.join(_APPDATA, "DatabaseManager")
OLD_CONFIG_DIR = os.path.join(_APPDATA, "BazaMenejeri") # a previous name
CONFIG_PATH = os.path.join(CONFIG_DIR, "settings.json")
LOG_PATH = os.path.join(CONFIG_DIR, "errors.log")
RECENT_LIMIT = 8 # length of the recent-files list
SOURCE_LIMIT = 20 # eslab qolinadigan manba raqamlari soni
UNDO_LIMIT = 30 # changed amalni ortga qaytarish mumkin
UNDO_ROW_BUDGET = 300_000 # undo tarixida total changed row saqlanadi (xotira)
FIELDS = ["no", "name", "phone", "id", "source"]
# Keywords used to recognise column headers automatically.
# All three languages must be recognised, so a database saved in one
# language still lines up when opened in another.
KEYS_SOURCE = ("manba", "kimdan", "source", "olindi", "egasi",
"источник", "от кого", "получено")
KEYS_PHONE = ("telefon", "tel", "phone", "nomer", "raqam", "number",
"mobil", "телефон", "номер")
KEYS_NAME = ("ism", "familiya", "fio", "ф.и.о", "фио", "имя", "name",
"фамилия")
KEYS_ID = ("id", "идент")
KEYS_NO = ("№", "no", "n", "t/r", "tr", "order", "#")
# pulls a phone number out of a line of free text
PHONE_RE = re.compile(r"(?<!\d)(\+?\d[\d\s\-()]{6,}\d)(?!\d)")
LETTER_RE = re.compile(r"[^\W\d_]", re.UNICODE)
TEXT_EXT = (".txt", ".text", ".log", ".tsv", ".tab")
VCARD_EXT = (".vcf", ".vcard")
TABLE_EXT = (".xlsx", ".xlsm", ".csv")
# --- Segoe icon glyphs. Present in both the Windows 11 font (SegoeIcons)
IC_LOGO = "\uE779" # contact list
IC_NEW = "\uE7C3" # updated hujjat
IC_OPEN = "\uE838" # folder ochish
IC_ADD = "\uE710" # plyus
IC_SAVE = "\uE74E" # saqlash
IC_SAVEAS = "\uE792" # boshqa name bilan saqlash
IC_EXTERN = "\uE8A7" # tashqi dasturda ochish
IC_EDIT = "\uE70F" # qalam
IC_DELETE = "\uE74D" # savat
IC_SEARCH = "\uE721" # lupa
IC_SUN = "\uE706" # kunduzgi tema
IC_MOON = "\uE708" # tungi tema
IC_PHONE = "\uE717" # telefon
IC_WARN = "\uE7BA" # ogohlantirish
IC_INFO = "\uE946" # ma'lumot
IC_ERROR = "\uE783" # err
IC_CHECK = "\uE73E" # bajarildi
IC_EMPTY = "\uE8A1" # empty list
IC_ROWS = "\uE8FD" # rows soni
IC_PEOPLE = "\uE716" # sources
IC_FILTER = "\uE71C" # shown rows
IC_FOLDER = "\uE8B7" # folder
IC_UNDO = "\uE7A7" # ortga qaytarish
IC_HISTORY = "\uE81C" # recent files
IC_PERSONADD = "\uE8FA" # add a row by hand
IC_COPY = "\uE8C8" # nusxa olish
IC_GLOBE = "\uE774" # til tanlash
IC_TOOLS = "\uEC7A" # tools
# colours written into Excel (identical in both themes)
XL_DUP_BG = "FFC7CE"
XL_DUP_FG = "9C0006"
XL_HEAD_BG = "2F5597"
PALETTES = {
"light": {
"bg": "#f3f3f3", # asosiy maydon foni
"sidebar": "#fbfbfb", # yon panel
"surface": "#ffffff", # cards, jadval
"text": "#1a1a1a",
"muted": "#616161",
"faint": "#8a8a8a",
"border": "#e5e5e5",
"accent": "#0f6cbd",
"accent_soft": "#eaf3fb",
"accent_dim": "#0c5a9e",
"on_accent": "#ffffff",
"nav_hover": "#ececec",
"stripe": "#f7f8fa",
"dup_bg": "#ffe2e3",
"dup_fg": "#b42318",
"dup_soft": "#fdeeee",
"new_bg": "#e4f6e9",
"new_fg": "#166534",
"new_soft": "#eefaf1",
"bad_bg": "#fdf0d8", # shubhali row (qisqa raqam, harf...)
"bad_fg": "#8a5300",
},
"dark": {
"bg": "#191919",
"sidebar": "#202020",
"surface": "#242424",
"text": "#f5f5f5",
"muted": "#a3a3a3",
"faint": "#7d7d7d",
"border": "#2f2f2f",
"accent": "#4cc2ff",
"accent_soft": "#12313f",
"accent_dim": "#3ba9e0",
"on_accent": "#08202b",
"nav_hover": "#2d2d2d",
"stripe": "#282828",
"dup_bg": "#4a2124",
"dup_fg": "#ffb4ab",
"dup_soft": "#331a1c",
"new_bg": "#1e3a26",
"new_fg": "#a6e5b8",
"new_soft": "#172a1c",
"bad_bg": "#3d3016",
"bad_fg": "#f0c476",
},
}
# ==================================================== settings and error log
def load_config():
"""Read the saved settings. Returns {} when the file is missing or broken."""
path = CONFIG_PATH
if not os.path.exists(path):
# the application had other names before; keep the old settings
old = os.path.join(OLD_CONFIG_DIR, os.path.basename(CONFIG_PATH))
if os.path.exists(old):
path = old
try:
# utf-8-sig so a file written with a BOM is still read
with open(path, "r", encoding="utf-8-sig") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def save_config(data):
"""Write the settings; an interrupted write cannot corrupt the old file."""
try:
os.makedirs(CONFIG_DIR, exist_ok=True)
tmp = CONFIG_PATH + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
os.replace(tmp, CONFIG_PATH)
except Exception:
pass # the app runs even if settings do not save
def log_error(exc_type, exc, tb):
"""
Write the error to a file. The app starts through `pythonw`, so there
is no console: without this log an error would be entirely invisible.
"""
try:
os.makedirs(CONFIG_DIR, exist_ok=True)
with open(LOG_PATH, "a", encoding="utf-8") as f:
f.write("\n" + "=" * 62 + "\n")
f.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "\n")
traceback.print_exception(exc_type, exc, tb, file=f)
except Exception:
pass
def system_lang():
"""Pick the initial language from the Windows UI language (first run)."""
try:
lid = ctypes.windll.kernel32.GetUserDefaultUILanguage() & 0x3FF
except Exception:
return "uz"
return {0x43: "uz", 0x19: "ru", 0x09: "en"}.get(lid, "uz")
def find_icon_file(name="icon.ico"):
"""Locate the icon file, both inside the .exe bundle and next to the script."""
here = os.path.dirname(os.path.abspath(__file__))
for folder in (getattr(sys, "_MEIPASS", None), here):
if folder:
p = os.path.join(folder, name)
if os.path.exists(p):
return p
return None
def message_box(text, title=APP_NAME, icon=0x10):
"""Show a message through the Windows API, for when Tk is not up yet."""
try:
ctypes.windll.user32.MessageBoxW(0, text, title, icon)
except Exception:
pass
# ============================================================ helper functions
def cell_text(v):
"""Turn an Excel cell into clean text (998901234567.0 -> 998901234567)."""
if v is None:
return ""
if isinstance(v, bool):
return str(v)
if isinstance(v, float):
return str(int(v)) if v.is_integer() else repr(v)
return str(v).strip()
def norm_phone(raw, last9=True):
"""Normalise a phone number for comparison."""
digits = re.sub(r"\D", "", cell_text(raw))
if not digits:
return ""
if last9 and len(digits) >= 9:
return digits[-9:]
return digits
def pretty_phone(raw):
"""
Bring a number into one shape:
901112233, 998901112233, +998 90-111-22-33 -> +998 90 111 22 33
Anything that does not look Uzbek only gets its punctuation stripped.
"""
text = cell_text(raw)
digits = re.sub(r"\D", "", text)
if not digits:
return text
if len(digits) == 9: # no country code, assume local
digits = "998" + digits
if digits.startswith("998") and len(digits) == 12:
return (f"+{digits[:3]} {digits[3:5]} {digits[5:8]} "
f"{digits[8:10]} {digits[10:]}")
if len(digits) >= 10: # chet el raqami
return "+" + digits
return text # juda qisqa — tegmaymiz
def row_problem(row, schema):
"""
Return why a row deserves attention, or None when it is fine.
Which checks apply depends on the schema.
"""
pc = role_col(schema, "phone")
if pc:
phone = cell_text(row.get(pc))
digits = re.sub(r"\D", "", phone)
if not digits:
return "phone_yoq"
if LETTER_RE.search(phone): # harf uzunlikdan before — sabab aniqroq
return "harf"
if len(digits) < 9:
return "qisqa"
nc = role_col(schema, "name")
if nc and not cell_text(row.get(nc)):
return "ism_yoq"
kc = schema.get("key_col") # a row whose duplicate key is empty
if kc and not cell_text(row.get(kc)):
return "kalit_yoq"
return None
def read_table(path):
"""Read an xlsx / xlsm / csv file as a raw list of rows."""
ext = os.path.splitext(path)[1].lower()
if ext in (".xlsx", ".xlsm"):
wb = load_workbook(path, data_only=True)
ws = wb.active
rows = [list(r) for r in ws.iter_rows(values_only=True)]
wb.close()
return rows
if ext == ".csv":
for enc in ("utf-8-sig", "cp1251", "latin-1"):
try:
with open(path, "r", newline="", encoding=enc) as f:
sample = f.read(8192)
f.seek(0)
try:
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
except csv.Error:
dialect = csv.excel
return [r for r in csv.reader(f, dialect)]
except UnicodeDecodeError:
continue
raise ValueError("Could not determine the encoding of the CSV file.")
if ext == ".xls":
raise ValueError("The old .xls format is not supported.\n"
"Open it in Excel and save it as .xlsx.")
raise ValueError("Only .xlsx, .xlsm and .csv files are supported.")
def match_header(row, schema, with_src=False):
"""
Sarlavha qatorini sxema ustunlariga solishtiradi.
Qaytaradi: {ustun_kaliti: ustun_raqami} yoki topilmasa None.
"""
cols = data_cols(schema, with_src)
variants = {c["key"]: title_variants(c) for c in cols}
mapping = {}
for idx, val in enumerate(row or []):
text = cell_text(val).lower().rstrip(":").strip()
if not text:
continue
for c in cols:
if c["key"] in mapping:
continue
if text in variants[c["key"]]:
mapping[c["key"]] = idx
break
needed = 1 if len(cols) == 1 else 2
return mapping if len(mapping) >= needed else None
def semantic_header(row, schema, with_src=False):
"""
When the header names do not match the schema, fall back to keywords
("telefon", "имя", "name", "манба" ...). Only useful when the schema
actually has a column with that role.
"""
roles = {}
for idx, val in enumerate(row or []):
text = cell_text(val).lower().rstrip(":").strip()
if not text:
continue
if any(k in text for k in KEYS_SOURCE):
roles.setdefault("src", idx)
elif any(k in text for k in KEYS_PHONE):
roles.setdefault("phone", idx)
elif any(k in text for k in KEYS_NAME):
roles.setdefault("name", idx)
elif text in KEYS_ID or text.startswith("id"):
roles.setdefault("id", idx)
elif text in KEYS_NO:
roles.setdefault("no", idx)
if "phone" not in roles and "name" not in roles:
return None
mapping = {}
for c in data_cols(schema, with_src):
idx = roles.get(c.get("role"))
if idx is not None:
mapping[c["key"]] = idx
return mapping or None
def infer_columns(table, schema, with_src=False):
"""
With no header at all, work the columns out from their CONTENT: which
column holds phone-like values, which holds names made of letters, which
is a plain row number. Only meaningful when the schema has a phone or a
name column.
"""
ncols = max((len(r) for r in table), default=0)
if not ncols:
return {}
stats = {}
for c in range(ncols):
vals = [cell_text(r[c]) for r in table if c < len(r) and cell_text(r[c])]
if not vals:
continue
phone_ratio = sum(1 for v in vals
if len(re.sub(r"\D", "", v)) >= 7) / len(vals)
letters = sum(len(LETTER_RE.findall(v)) for v in vals) / len(vals)
seq_ratio = sum(1 for v in vals
if v.isdigit() and len(v) <= 4) / len(vals)
stats[c] = (phone_ratio, letters, seq_ratio)
roles = {}
# phone: a column where at least half the values have 7+ digits
cand = [(s[0], -c, c) for c, s in stats.items() if s[0] >= 0.5]
if cand:
roles["phone"] = max(cand)[2]
# name: most letters on average (an ID like "u1001" does not qualify)
cand = [(s[1], -c, c) for c, s in stats.items()
if c != roles.get("phone") and s[1] >= 2]
if cand:
roles["name"] = max(cand)[2]
# row number: a column of short whole numbers