-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2489 lines (2115 loc) · 107 KB
/
main.py
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 gzip
import sys
import shutil # <-- I use shutil.rmtree() to remove chunk folders
import requests
import platform
import subprocess
import pandas as pd
import xml.etree.ElementTree as ET
from threading import Thread, Lock
import webbrowser # <-- for opening social media links
import csv
import queue
from tkinter import filedialog
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from tkinter import messagebox
from tkinter import StringVar # Import StringVar
import time
from datetime import datetime, timedelta
import json
import os
import math
from pathlib import Path
from tkinter import messagebox
from PIL import Image, ImageDraw, ImageFont, ImageFilter
###############################################################################
# XML → DataFrame logic
###############################################################################
def xml_to_df(xml_path: Path, record_tag: str) -> pd.DataFrame:
"""
Convert an XML file to a pandas DataFrame, handling two levels of nested tags.
Automatically detects list-type columns based on multiple occurrences of tags.
Nested tags are stored as lists and serialized as JSON strings for CSV compatibility.
"""
records = []
current_record = {}
current_path = []
nested_data = {}
tag_counts = {}
for event, elem in ET.iterparse(str(xml_path), events=("start", "end")):
if event == "start":
current_path.append(elem.tag)
if elem.tag == record_tag:
current_record = {}
nested_data = {}
tag_counts = {}
elif event == "end":
if elem.tag == record_tag:
# Merge nested_data into current_record
for key, value in nested_data.items():
if key in current_record:
if isinstance(current_record[key], list):
current_record[key].append(value)
else:
current_record[key] = [current_record[key], value]
else:
current_record[key] = value
records.append(current_record)
current_record = {}
nested_data = {}
tag_counts = {}
else:
if elem.text and not elem.text.isspace():
if len(current_path) >= 3:
# Two levels deep
parent_tag = current_path[-3]
child_tag = current_path[-2]
full_tag = f"{parent_tag}_{child_tag}_{elem.tag}"
elif len(current_path) == 2:
# One level deep
full_tag = f"{current_path[-2]}_{elem.tag}"
else:
# Root level
full_tag = elem.tag
# Initialize tag count
tag_counts[full_tag] = tag_counts.get(full_tag, 0) + 1
value = elem.text.strip()
if tag_counts[full_tag] > 1:
# If tag occurs multiple times, store as list
if full_tag in nested_data:
nested_data[full_tag].append(value)
else:
nested_data[full_tag] = [nested_data.get(full_tag, []), value]
else:
nested_data[full_tag] = value
# Handle attributes
for attr, value in elem.attrib.items():
if len(current_path) >= 3:
parent_tag = current_path[-3]
child_tag = current_path[-2]
tag_name = f"{parent_tag}_{child_tag}_{elem.tag}_{attr}"
elif len(current_path) == 2:
tag_name = f"{current_path[-2]}_{elem.tag}_{attr}"
else:
tag_name = f"{elem.tag}_{attr}"
# Initialize tag count
tag_counts[tag_name] = tag_counts.get(tag_name, 0) + 1
if tag_counts[tag_name] > 1:
# If attribute occurs multiple times, store as list
if tag_name in nested_data:
nested_data[tag_name].append(value)
else:
nested_data[tag_name] = [nested_data.get(tag_name, []), value]
else:
nested_data[tag_name] = value
current_path.pop()
elem.clear()
# Create DataFrame from records
df = pd.DataFrame(records)
# Dynamically serialize list-type columns as JSON strings
for col in df.columns:
if df[col].apply(lambda x: isinstance(x, list)).any():
df[col] = df[col].apply(lambda x: json.dumps(x) if isinstance(x, list) else x)
return df
###############################################################################
# Helper to convert a single XML file to CSV
###############################################################################
def convert_extracted_file_to_csv(extracted_file_path: Path, output_csv_path: Path, record_tag: str, logger=None) -> bool:
"""
Use xml_to_df logic to convert the extracted XML file into a CSV.
Handles nested tags by writing them as JSON lists.
Returns True if successful, False otherwise.
"""
if not extracted_file_path.exists():
if logger:
logger(f"File not found: {extracted_file_path}", "ERROR")
else:
print(f"[ERROR] File not found: {extracted_file_path}")
return False
try:
df = xml_to_df(extracted_file_path, record_tag)
df.to_csv(output_csv_path, index=False)
if logger:
logger(f"Converted {extracted_file_path} to {output_csv_path}", "INFO")
else:
print(f"[INFO] Converted {extracted_file_path} to {output_csv_path}")
return True
except Exception as e:
if logger:
logger(f"convert_extracted_file_to_csv: {e}", "ERROR")
else:
print(f"[ERROR] convert_extracted_file_to_csv: {e}")
return False
###############################################################################
# CHUNKING LOGIC (Using iterparse to avoid mismatch)
###############################################################################
def chunk_xml_by_type(xml_file: Path, content_type: str, records_per_file: int = 10000, logger=None):
"""
1. Pass: Split large XML into smaller chunks by record type.
"""
chunk_folder = xml_file.parent / f"chunked_{content_type}"
chunk_folder.mkdir(exist_ok=True)
record_tag = content_type[:-1] # e.g., "releases" -> "release"
chunk_count = 0
record_count = 0
current_chunk = None
for event, elem in ET.iterparse(str(xml_file), events=("start", "end")):
if event == "start":
if elem.tag == record_tag:
if record_count % records_per_file == 0:
if current_chunk is not None:
current_chunk.write(f"</{content_type}>")
current_chunk.close()
# Use zfill to ensure proper sorting (e.g., chunk_001.xml)
chunk_count += 1
chunk_file = chunk_folder / f"chunk_{str(chunk_count).zfill(6)}.xml"
current_chunk = open(chunk_file, "w", encoding="utf-8")
current_chunk.write(f'<?xml version="1.0" encoding="utf-8"?>\n<{content_type}>')
if logger:
logger(f"Created new chunk: {chunk_file.name}", "INFO")
else:
print(f"Created new chunk: {chunk_file.name}")
record_count += 1
current_chunk.write(ET.tostring(elem, encoding="unicode"))
elif event == "end" and elem.tag == record_tag:
elem.clear()
if current_chunk is not None:
current_chunk.write(f"</{content_type}>")
current_chunk.close()
if logger:
logger(f"Chunking completed. Created {chunk_count} chunks.", "INFO")
else:
print(f"Chunking completed. Created {chunk_count} chunks.")
###############################################################################
# STREAMING: Two-pass approach for each chunk
###############################################################################
def update_columns_from_chunk(chunk_file_path: Path, all_columns: set, record_tag: str, logger=None):
"""
1. Pass: Parse the chunk file line by line.
- Add discovered tag/attribute names to the 'all_columns' set.
- No data is stored in memory.
"""
current_path = []
for event, elem in ET.iterparse(str(chunk_file_path), events=("start", "end")):
if event == "start":
current_path.append(elem.tag)
# Discover attributes
for attr, value in elem.attrib.items():
if len(current_path) >= 3:
# Two levels deep
parent_tag = current_path[-3]
current_tag = current_path[-2]
tag_name = f"{parent_tag}_{current_tag}_{elem.tag}_{attr}"
elif len(current_path) == 2:
# One level deep
tag_name = f"{current_path[-2]}_{elem.tag}_{attr}"
else:
# Root or unexpected depth
tag_name = f"{elem.tag}_{attr}"
all_columns.add(tag_name)
elif event == "end":
if elem.text and not elem.text.isspace():
if len(current_path) >= 3:
# Two levels deep
parent_tag = current_path[-3]
current_tag = current_path[-2]
tag_name = f"{parent_tag}_{current_tag}_{elem.tag}"
elif len(current_path) == 2:
# One level deep
tag_name = f"{current_path[-2]}_{elem.tag}"
else:
# Root or unexpected depth
tag_name = elem.tag
all_columns.add(tag_name)
if elem.tag == record_tag:
# Record ended, do nothing except ensure we clear
pass
current_path.pop()
elem.clear()
if logger:
logger(f"Updated columns from {chunk_file_path.name}. Total columns now: {len(all_columns)}", "INFO")
else:
print(f"Updated columns from {chunk_file_path.name}. Total columns now: {len(all_columns)}")
def write_chunk_to_csv(chunk_file_path: Path, csv_writer: csv.DictWriter, all_columns: list, record_tag: str,
logger=None):
"""
2. Pass: Parse the chunk file line by line.
For each <record_tag>...</record_tag> record, write a single row to the CSV.
Nested tags are serialized as JSON strings.
"""
current_path = []
record_data = {}
nested_data = {}
for event, elem in ET.iterparse(str(chunk_file_path), events=("start", "end")):
if event == "start":
current_path.append(elem.tag)
# Save attributes
for attr, value in elem.attrib.items():
if len(current_path) >= 3:
# Two levels deep
parent_tag = current_path[-3]
current_tag = current_path[-2]
tag_name = f"{parent_tag}_{current_tag}_{elem.tag}_{attr}"
elif len(current_path) == 2:
# One level deep
tag_name = f"{current_path[-2]}_{elem.tag}_{attr}"
else:
# Root or unexpected depth
tag_name = f"{elem.tag}_{attr}"
# Handle multiple attributes by storing in lists
if tag_name in nested_data:
if isinstance(nested_data[tag_name], list):
nested_data[tag_name].append(value)
else:
nested_data[tag_name] = [nested_data[tag_name], value]
else:
nested_data[tag_name] = value
elif event == "end":
if elem.text and not elem.text.isspace():
if len(current_path) >= 3:
# Two levels deep
parent_tag = current_path[-3]
current_tag = current_path[-2]
tag_name = f"{parent_tag}_{current_tag}_{elem.tag}"
elif len(current_path) == 2:
# One level deep
tag_name = f"{current_path[-2]}_{elem.tag}"
else:
# Root or unexpected depth
tag_name = elem.tag
# Handle multiple tags by storing in lists
if tag_name in nested_data:
if isinstance(nested_data[tag_name], list):
nested_data[tag_name].append(elem.text.strip())
else:
nested_data[tag_name] = [nested_data[tag_name], elem.text.strip()]
else:
nested_data[tag_name] = elem.text.strip()
if elem.tag == record_tag:
# Record completed, write to CSV
# Merge nested_data into current_record
for key, value in nested_data.items():
if key in record_data:
if isinstance(record_data[key], list):
record_data[key].append(value)
else:
record_data[key] = [record_data[key], value]
else:
record_data[key] = value
# Serialize nested structures as JSON strings
row_to_write = {}
for col in all_columns:
value = record_data.get(col, None)
if isinstance(value, (dict, list)):
row_to_write[col] = json.dumps(value)
else:
row_to_write[col] = value
csv_writer.writerow(row_to_write)
record_data.clear()
nested_data.clear()
current_path.pop()
elem.clear()
if logger:
logger(f"Written data from {chunk_file_path.name} to CSV.", "INFO")
else:
print(f"Written data from {chunk_file_path.name} to CSV.")
def convert_progress_callback(self, current_step, total_steps):
"""Called when each chunk is completed during the conversion process."""
if total_steps == 0:
percentage = 0
else:
percentage = (current_step / total_steps) * 100
self.pb["value"] = percentage
self.prog_message_var.set(f"Converting: {percentage:.2f}%")
self.update_idletasks()
def convert_chunked_files_to_csv(
chunk_folder: Path,
output_csv: Path,
content_type: str,
logger=None,
progress_cb=None # Callback for progress updates
):
"""
1) Discover columns across all chunk files (pass 1).
2) Write all chunk files to CSV (pass 2).
If progress_cb(current_step, total_steps) is provided,
it will be called after each chunk is processed.
"""
import csv
record_tag = content_type[:-1] # "releases" -> "release"
chunk_files = sorted(chunk_folder.glob("chunk_*.xml"))
if not chunk_files:
if logger:
logger(f"[WARNING] No chunk_*.xml files found in {chunk_folder}", "WARNING")
else:
print(f"[WARNING] No chunk_*.xml files found in {chunk_folder}")
return
# 1) PASS: Discover columns
total_chunks = len(chunk_files)
current_step = 0
all_columns = set()
# Total steps: PASS 1 + PASS 2 = 2 * total_chunks
total_steps = 2 * total_chunks
for cf in chunk_files:
update_columns_from_chunk(cf, all_columns, record_tag=record_tag, logger=logger)
current_step += 1
# Update progress bar after each chunk
if progress_cb:
progress_cb(current_step, total_steps)
all_columns = sorted(all_columns) # Keep columns ordered
# 2) PASS: Write to CSV
with open(output_csv, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=all_columns)
writer.writeheader()
for cf in chunk_files:
write_chunk_to_csv(cf, writer, all_columns, record_tag=record_tag, logger=logger)
current_step += 1
if progress_cb:
progress_cb(current_step, total_steps)
if logger:
logger(f"Done! Created CSV: {output_csv}", "INFO")
else:
print(f"[INFO] Done! Created CSV: {output_csv}")
###############################################################################
# S3 + UI + Main Logic
###############################################################################
if getattr(sys, 'frozen', False):
# PyInstaller ile paketlenmiş
BASE_DIR = Path(sys._MEIPASS)
else:
# Normal Python çalışması
BASE_DIR = Path(__file__).parent
PATH = BASE_DIR / 'assets'
def human_readable_size(num_bytes):
"""Convert a file size in bytes to a human-readable string (KB, MB, or GB),
with 0 digits after the decimal."""
if num_bytes < 1024:
return f"{num_bytes} B"
elif num_bytes < 1024 ** 2:
return f"{num_bytes // 1024} KB"
elif num_bytes < 1024 ** 3:
return f"{num_bytes // (1024 ** 2)} MB"
else:
return f"{num_bytes // (1024 ** 3)} GB"
def list_directories_from_s3(base_url="https://discogs-data-dumps.s3.us-west-2.amazonaws.com/", prefix="data/"):
"""Retrieve a list of 'directories' (common prefixes) from the S3 XML listing."""
import xml.etree.ElementTree as ET
url = base_url + "?prefix=" + prefix + "&delimiter=/"
r = requests.get(url)
r.raise_for_status()
ns = "{http://s3.amazonaws.com/doc/2006-03-01/}"
root = ET.fromstring(r.text)
dirs = []
for cp in root.findall(ns + 'CommonPrefixes'):
p = cp.find(ns + 'Prefix').text
dirs.append(p)
return dirs
def list_files_in_directory(base_url, directory_prefix):
"""List all files (key, size, last_modified) in a particular S3 directory prefix."""
import xml.etree.ElementTree as ET
url = base_url + "?prefix=" + directory_prefix
r = requests.get(url)
r.raise_for_status()
ns = "{http://s3.amazonaws.com/doc/2006-03-01/}"
root = ET.fromstring(r.text)
data = []
for content in root.findall(ns + 'Contents'):
key = content.find(ns + 'Key').text
size_str = content.find(ns + 'Size').text
last_modified = content.find(ns + 'LastModified').text
try:
size_bytes = int(size_str)
size_hr = human_readable_size(size_bytes)
except:
size_hr = "0 B"
ctype = "unknown"
lname = key.lower()
if "checksum" in lname:
ctype = "checksum"
elif "artist" in lname:
ctype = "artists"
elif "master" in lname:
ctype = "masters"
elif "label" in lname:
ctype = "labels"
elif "release" in lname:
ctype = "releases"
data.append({
"last_modified": last_modified,
"size": size_hr,
"key": key,
"content": ctype,
"URL": base_url + key
})
return pd.DataFrame(data)
class CollapsingFrame(ttk.Frame):
"""A collapsible Frame widget for grouping content."""
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.columnconfigure(0, weight=1)
self.cumulative_rows = 0
def add(self, child, title="", bootstyle=PRIMARY, **kwargs):
if child.winfo_class() != 'TFrame':
return
# Create the header frame with a fixed height
frm = ttk.Frame(self, bootstyle=bootstyle, height=43) # Set fixed height for grey background
frm.grid(row=self.cumulative_rows, column=0, sticky=EW, pady=(0, 0))
frm.grid_propagate(False) # Prevent the frame from shrinking to fit content
header = ttk.Label(master=frm, text=title, bootstyle=(bootstyle, INVERSE))
if kwargs.get('textvariable'):
header.configure(textvariable=kwargs.get('textvariable'))
# Center the label vertically in the frame
header.place(relx=0, rely=0.5, x=10, anchor='w')
child.grid(row=self.cumulative_rows + 1, column=0, sticky=NSEW, pady=(0, 0))
self.cumulative_rows += 2
class DiscogsDataProcessorUI(ttk.Frame):
def __init__(self, master, data_df, **kwargs):
super().__init__(master, **kwargs)
self.pack(fill=BOTH, expand=YES)
self.data_df = data_df
self.stop_flag = False
# [UPDATED] New variable: Download folder (default: ~/Downloads/Discogs)
default_download_dir = Path.home() / "Downloads" / "Discogs"
self.download_dir_var = StringVar(value=str(default_download_dir)) # Use StringVar
# Add status indicator variables
self.status_indicator_visible = True
self.status_indicator_active = False
self.blink_after_id = None
# Initialize StringVar variables for status
self.prog_message_var = StringVar(value='Idle...')
self.prog_speed_var = StringVar(value='Speed: 0.00 MB/s')
self.prog_time_started_var = StringVar(value='Not started')
self.prog_time_elapsed_var = StringVar(value='Elapsed: 0 sec')
self.prog_time_left_var = StringVar(value='Left: 0 sec')
self.scroll_message_var = StringVar(value='Log: Ready.')
# For checkboxes in table
self.check_vars = {}
self.checkbuttons = {}
#######################################################################
# 1) Load all images in a dictionary + self.photoimages
#######################################################################
image_files = {
'settings': 'icons8-settings-30.png',
'info': 'icons8-info-30.png',
'download': 'icons8-download-30.png',
'stop': 'icons8-cancel-30.png',
'refresh': 'icons8-refresh-30.png',
'opened-folder': 'icons8-folder-30.png',
'fetch': 'icons8-data-transfer-30.png',
'delete': 'icons8-trash-30.png',
'extract': 'icons8-open-archive-30.png',
'convert': 'icons8-export-csv-30.png',
'coverart': 'icons8-image-30.png',
'logo': 'logo.png',
'linkedin': 'linkedin.png',
'github': 'github.png',
'kaggle': 'kaggle.png',
'avatar': 'avatar.png'
}
self.photoimages = {}
imgpath = BASE_DIR / 'assets'
for key, val in image_files.items():
_path = imgpath / val
if _path.exists():
try:
self.photoimages[key] = ttk.PhotoImage(name=key, file=_path)
except Exception as e:
print(f"[ERROR] Failed to load image: {e}")
else:
print(f"[WARNING] Image file not found: {_path}")
#######################################################################
# NEW TOP BANNER FRAME
#######################################################################
top_banner_frame = ttk.Frame(self)
top_banner_frame.pack(side=TOP, fill=X)
# [UPDATED] Discogs logo on the left with click event
if 'logo' in self.photoimages:
banner = ttk.Label(top_banner_frame, image='logo')
banner.pack(side=LEFT, padx=10, pady=5)
# Open discogs.com on click
banner.bind("<Button-1>", lambda e: self.open_url("https://www.discogs.com"))
else:
banner = ttk.Label(top_banner_frame, text="Discogs Data Processor", font=("Arial", 16, "bold"))
banner.pack(side=LEFT, padx=10, pady=5)
# Social media icons on the right
social_frame = ttk.Frame(top_banner_frame)
social_frame.pack(side=RIGHT, padx=10, pady=5)
if 'linkedin' in self.photoimages:
btn_linkedin = ttk.Button(
social_frame,
image='linkedin',
bootstyle=LINK,
command=lambda: self.open_url("https://www.linkedin.com/in/ofurkancoban/")
)
btn_linkedin.pack(side=LEFT, padx=2)
if 'github' in self.photoimages:
btn_github = ttk.Button(
social_frame,
image='github',
bootstyle=LINK,
command=lambda: self.open_url("https://github.com/ofurkancoban")
)
btn_github.pack(side=LEFT, padx=2)
if 'kaggle' in self.photoimages:
btn_kaggle = ttk.Button(
social_frame,
image='kaggle',
bootstyle=LINK,
command=lambda: self.open_url("https://www.kaggle.com/ofurkancoban")
)
btn_kaggle.pack(side=LEFT, padx=2)
#######################################################################
# TOP BUTTON BAR
#######################################################################
buttonbar = ttk.Frame(self, style='primary.TFrame')
buttonbar.pack(fill=X, pady=1, side=TOP)
self.scroll_message_var.set('Log: Ready.')
# 1. Fetch Data
btn = ttk.Button(buttonbar, text='Fetch Data', image='fetch', compound=TOP, command=self.start_scraping)
btn.pack(side=LEFT, ipadx=1, ipady=5, padx=1, pady=1)
# 3. Download
btn = ttk.Button(buttonbar, text='Download', image='download', compound=TOP, command=self.download_selected)
btn.pack(side=LEFT, ipadx=1, ipady=5, padx=1, pady=1)
# 4. Extract
btn = ttk.Button(buttonbar, text='Extract', image='extract', compound=TOP, command=self.extract_selected)
btn.pack(side=LEFT, ipadx=1, ipady=5, padx=1, pady=1)
# 5. Convert
btn = ttk.Button(buttonbar, text='Convert', image='convert', compound=TOP, command=self.convert_selected)
btn.pack(side=LEFT, ipadx=1, ipady=5, padx=1, pady=1)
# 6. Delete
btn = ttk.Button(buttonbar, text='Delete', image='delete', compound=TOP, command=self.delete_selected)
btn.pack(side=LEFT, ipadx=1, ipady=5, padx=1, pady=1)
btn = ttk.Button(
buttonbar,
text='Cover Art',
# you could pick an icon from your assets if desired, e.g. 'info' or 'settings'
image='coverart',
compound=TOP,
command=self.open_coverart_window # <--- We'll define this below
)
btn.pack(side=LEFT, ipadx=1, ipady=5, padx=1, pady=1)
# Settings
btn = ttk.Button(
buttonbar,
text='Settings',
image='settings',
compound=TOP,
command=self.open_settings # Settings window
)
btn.pack(side=LEFT, ipadx=1, ipady=5, padx=1, pady=1)
# [UPDATED] Info Button (no scrollbar in the info window)
btn = ttk.Button(
buttonbar,
text='Info',
image='info',
compound=TOP,
command=self.open_info
)
btn.pack(side=LEFT, ipadx=1, ipady=5, padx=1, pady=1)
#######################################################################
# LEFT PANEL
#######################################################################
left_panel = ttk.Frame(self, style='bg.TFrame', width=250)
left_panel.pack(side=LEFT, fill=BOTH, expand=True)
left_panel.pack_propagate(False)
ds_cf = CollapsingFrame(left_panel)
ds_cf.pack(fill=BOTH, expand=True, pady=1)
ds_frm = ttk.Frame(ds_cf, padding=0)
ds_frm.columnconfigure(0, weight=1)
ds_frm.rowconfigure(0, weight=1)
ds_cf.add(child=ds_frm, title='Data Summary', bootstyle=SECONDARY)
lbl = ttk.Label(ds_frm, text='Download Folder:', padding=(10, 0)) # Added left padding
lbl.grid(row=0, column=0, sticky=W, pady=2)
self.download_folder_label = ttk.Label(ds_frm, textvariable=self.download_dir_var, padding=(10, 0))
self.download_folder_label.grid(row=1, column=0, sticky=W, padx=0, pady=2)
lbl = ttk.Label(ds_frm, text='Size of Downloaded Files:', padding=(10, 0))
lbl.grid(row=2, column=0, sticky=W, pady=2)
self.downloaded_size_var = StringVar(value="Calculating...")
lbl = ttk.Label(ds_frm, textvariable=self.downloaded_size_var, padding=(10, 0))
lbl.grid(row=3, column=0, sticky=W, padx=0, pady=2)
_func = self.open_discogs_folder
open_btn = ttk.Button(ds_frm, text='Open Folder', command=_func,
image='opened-folder', compound=LEFT)
open_btn.grid(row=5, column=0, columnspan=2, sticky=EW)
# Status panel
status_cf = CollapsingFrame(left_panel)
status_cf.pack(fill=BOTH, expand=True, pady=1)
status_frm = ttk.Frame(status_cf, padding=0)
status_frm.columnconfigure(0, weight=1)
status_cf.add(child=status_frm, title='Status', bootstyle=SECONDARY)
# Create status header frame with indicator
status_header = ttk.Frame(status_frm)
status_header.grid(row=0, column=0, columnspan=2, sticky=W, pady=(10,5), padx=10)
# Add status indicator canvas
self.status_indicator = ttk.Canvas(status_header, width=10, height=10)
self.status_indicator.pack(side=LEFT, padx=(0,5))
self.indicator_oval = self.status_indicator.create_oval(2, 2, 8, 8, fill='gray', outline='')
# Status message next to indicator
lbl = ttk.Label(status_header, textvariable=self.prog_message_var, font='Arial 11 bold')
lbl.pack(side=LEFT)
# Add progress bar back
self.pb = ttk.Progressbar(status_frm, bootstyle="success-striped")
self.pb.grid(row=1, column=0, columnspan=2, sticky=EW, padx=10, pady=5)
self.prog_current_file_var = StringVar(value="File: none")
lbl = ttk.Label(status_frm, textvariable=self.prog_current_file_var, padding=(10, 0))
lbl.grid(row=2, column=0, columnspan=2, sticky=EW, pady=2)
lbl = ttk.Label(status_frm, textvariable=self.prog_time_started_var, padding=(10, 0))
lbl.grid(row=3, column=0, columnspan=2, sticky=EW, pady=2)
self.prog_time_started_var.set('Not started')
lbl = ttk.Label(status_frm, textvariable=self.prog_speed_var, padding=(10, 0))
lbl.grid(row=4, column=0, columnspan=2, sticky=EW, pady=2)
self.prog_speed_var.set('Speed: 0.00 MB/s')
lbl = ttk.Label(status_frm, textvariable=self.prog_time_elapsed_var, padding=(10, 0))
lbl.grid(row=5, column=0, columnspan=2, sticky=EW, pady=2)
self.prog_time_elapsed_var.set('Elapsed: 0 sec')
lbl = ttk.Label(status_frm, textvariable=self.prog_time_left_var, padding=(10, 0))
lbl.grid(row=6, column=0, columnspan=2, sticky=EW, pady=2)
self.prog_time_left_var.set('Left: 0 sec')
stop_btn = ttk.Button(status_frm, command=self.stop_download, image='stop', text='Stop', compound=LEFT)
stop_btn.grid(row=7, column=0, columnspan=2, sticky=EW)
lbl_ver = ttk.Label(left_panel, text="V.0.1", style='bg.TLabel')
lbl_ver.pack(side='bottom', anchor='center', pady=2)
lbl_name = ttk.Label(left_panel, text="ofurkancoban", style='bg.TLabel')
lbl_name.pack(side='bottom', anchor='center', pady=2)
# Add avatar at the bottom (if exists)
if 'avatar' in self.photoimages:
lbl = ttk.Label(left_panel, image='avatar', style='bg.TLabel')
else:
lbl = ttk.Label(left_panel, text="Avatar", style='bg.TLabel')
lbl.pack(side='bottom', anchor='center', pady=2)
#######################################################################
# RIGHT PANEL
#######################################################################
right_panel = ttk.Frame(self, padding=(2, 0))
right_panel.pack(side=RIGHT, fill=BOTH, expand=NO)
self.style = ttk.Style()
self.style.configure(
"Treeview.Heading",
padding=(0, 11),
font=("Arial", 13, "bold")
)
right_panel.columnconfigure(0, weight=1)
right_panel.rowconfigure(0, weight=1)
right_panel.rowconfigure(1, weight=1)
tv = ttk.Treeview(right_panel, show='headings', height=16, style="Treeview")
tv.configure(columns=(" ", "month", "content", "size", "Downloaded", "Extracted", "Processed"))
tv.column(" ", width=1, anchor=CENTER)
tv.column("month", width=15, anchor=CENTER)
tv.column("content", width=20, anchor=CENTER)
tv.column("size", width=25, anchor=CENTER)
tv.column("Downloaded", width=35, anchor=CENTER)
tv.column("Extracted", width=35, anchor=CENTER)
tv.column("Processed", width=35, anchor=CENTER)
vsb = ttk.Scrollbar(right_panel, orient="vertical", command=tv.yview)
tv.configure(yscrollcommand=vsb.set)
tv.grid(row=0, column=0, sticky='nsew', pady=1)
vsb.grid(row=0, column=1, sticky='ns')
buttonbar2 = ttk.Frame(self, style='primary.TFrame')
buttonbar2.pack(fill=X, pady=1, side=BOTTOM)
def _scrollbar_set(first, last):
vsb.set(first, last)
self.position_checkbuttons()
tv.configure(yscrollcommand=_scrollbar_set)
for col in tv["columns"]:
tv.heading(col, text=col.capitalize(), anchor=CENTER)
scroll_cf = CollapsingFrame(right_panel)
scroll_cf.grid(row=1, column=0, columnspan=2, sticky='nsew')
output_container = ttk.Frame(scroll_cf, padding=0)
_value = 'Log: Ready.'
self.scroll_message_var.set(_value)
console_frame = ttk.Frame(output_container)
console_frame.pack(fill=BOTH, expand=NO)
console_frame.columnconfigure(0, weight=1)
console_frame.rowconfigure(0, weight=1)
# Create Text widget
st = ttk.Text(console_frame, wrap='word', state='disabled', height=15)
st.grid(row=0, column=0, sticky='nsew')
# Create ttk Scrollbar
console_scrollbar = ttk.Scrollbar(console_frame, orient='vertical', command=st.yview,
style='Vertical.TScrollbar')
console_scrollbar.grid(row=0, column=1, sticky='ns')
# Configure Text widget to use the scrollbar
st.configure(yscrollcommand=console_scrollbar.set)
self.console_text = st
scroll_cf.add(output_container, textvariable=self.scroll_message_var)
self.tree = tv
self.tree.bind("<Configure>", lambda e: self.position_checkbuttons())
self.tree.bind("<Motion>", lambda e: self.position_checkbuttons())
self.tree.bind("<ButtonRelease-1>", lambda e: self.position_checkbuttons())
self.tree.bind("<<TreeviewSelect>>", lambda e: self.position_checkbuttons())
right_panel.bind("<Configure>", lambda e: self.position_checkbuttons())
self.log_to_console("Welcome to the Discogs Data Processor", "INFO")
self.log_to_console("The application is fetching data automatically, please wait...", "INFO")
# Start scraping after short delay
self.after(100, self.start_scraping)
self.update_downloaded_size()
# -------------------------------------------------------------------------
# NEW FUNCTION: OPEN COVERART WINDOW
# -------------------------------------------------------------------------
def open_coverart_window(self):
"""
Opens a new Toplevel window to:
1) Select an image
2) Choose YEAR + spelled-out MONTH from combobox
3) Select a .ttf font file (optional)
4) Apply coverart => writes "YEAR - MONTH" to the image
5) The output file is named after the selected MONTH and saved to ~/Discogs/Cover Arts
"""
wm_win = ttk.Toplevel(self)
wm_win.title("Create Cover Art")
# Pencere boyutlarını belirleyin
window_width = 500
window_height = 500
# Ekran boyutlarını alın
screen_width = wm_win.winfo_screenwidth()
screen_height = wm_win.winfo_screenheight()
# Pencereyi ekranın ortasına yerleştirmek için koordinatları hesaplayın
center_x = int((screen_width - window_width) / 2)
center_y = int((screen_height - window_height) / 2)
# Geometry ayarını güncelleyin (örneğin: "500x500+center_x+center_y")
wm_win.geometry(f"{window_width}x{window_height}+{center_x}+{center_y}")
wm_win.resizable(False, False)
# Spelled-out months
month_choices = [
"JANUARY", "FEBRUARY", "MARCH", "APRIL",
"MAY", "JUNE", "JULY", "AUGUST",
"SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
]
# By default, pick the current year and spelled-out month
now = datetime.now()
default_year = str(now.year)
default_month = month_choices[now.month - 1]
# Tk variables for form fields
self.wm_image_path = ttk.StringVar(value="")
self.wm_font_path = ttk.StringVar(value="")
self.wm_selected_year = ttk.StringVar(value=default_year)
self.wm_selected_month = ttk.StringVar(value=default_month)
# 1) Image file selection
frm_top = ttk.Frame(wm_win, padding=10)
frm_top.pack(fill="x", pady=5)
lbl_img = ttk.Label(frm_top, text="Select Image:", width=12)
lbl_img.pack(side="left")
ent_img = ttk.Entry(frm_top, textvariable=self.wm_image_path, width=25)
ent_img.pack(side="left", padx=5)
def browse_image():
filepath = filedialog.askopenfilename(
title="Select an Image",
filetypes=[
("Image files", "*.jpg *.jpeg *.png *.bmp *.gif *.tiff *.webp"),
("All files", "*.*")
]
)
if filepath:
self.wm_image_path.set(filepath)
btn_img = ttk.Button(frm_top, text="Browse", command=browse_image)
btn_img.pack(side="left")
# 2) Year & spelled-out Month
frm_ym = ttk.Frame(wm_win, padding=10)
frm_ym.pack(fill="x", pady=5)
lbl_year = ttk.Label(frm_ym, text="Year:")
lbl_year.grid(row=0, column=0, padx=5, sticky="e")
cmb_year = ttk.Combobox(frm_ym, values=[str(y) for y in range(2000, now.year + 10)],
textvariable=self.wm_selected_year, width=6)
cmb_year.grid(row=0, column=1, padx=5, sticky="w")
lbl_month = ttk.Label(frm_ym, text="Month:")
lbl_month.grid(row=0, column=2, padx=5, sticky="e")
cmb_month = ttk.Combobox(frm_ym, values=month_choices,
textvariable=self.wm_selected_month, width=10)
cmb_month.grid(row=0, column=3, padx=5, sticky="w")
# 3) Font selection (optional)
frm_font = ttk.Frame(wm_win, padding=10)
frm_font.pack(fill="x", pady=5)
lbl_font = ttk.Label(frm_font, text="Font (.ttf):")
lbl_font.pack(side="left")
ent_font = ttk.Entry(frm_font, textvariable=self.wm_font_path, width=25)
ent_font.pack(side="left", padx=5)
def browse_font():
font_file = filedialog.askopenfilename(
title="Select a TTF Font",
filetypes=[("TrueType Font", "*.ttf"), ("All files", "*.*")]
)
if font_file:
self.wm_font_path.set(font_file)
btn_font = ttk.Button(frm_font, text="Browse", command=browse_font)
btn_font.pack(side="left")
# 4) Apply coverart => new file = selected month
frm_btn = ttk.Frame(wm_win, padding=10)
frm_btn.pack(fill="x", pady=10)
# Assuming BASE_DIR is defined elsewhere, e.g.:
# BASE_DIR = Path(__file__).parent