stable-v1_0.1

This commit is contained in:
joel committed 2026-10-01 14:47:43 +02:00
1 parent bb912d66a4
commit 9a62dd49d1
4 files changed
+331 -79

No files matched your search

Vendored
BIN
View File
Binary file not shown.
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""
fcco-Converter V1 – Build-Skript
Erstellt plattformabhängige Standalone-Executables (.exe / .app) mit PyInstaller.
Aufruf: python build.py
"""
import platform
import subprocess
import sys
import shutil
from pathlib import Path
def build():
system = platform.system()
project_dir = Path(__file__).parent.resolve()
dist_dir = project_dir / "dist"
app_name = "fcco-Converter"
if system == "Darwin":
old_app = dist_dir / f"{app_name}.app"
else:
old_app = dist_dir / f"{app_name}.exe"
if old_app.exists():
if old_app.is_dir():
shutil.rmtree(old_app)
else:
old_app.unlink()
# Basis-Argumente für PyInstaller
args = [
sys.executable,
"-m",
"PyInstaller",
"--onefile",
"--windowed",
"--name",
app_name,
"--clean",
]
# Icon hinzufügen (wenn vorhanden)
icon_path = project_dir / "icon.ico"
if icon_path.exists():
args.extend(["--icon", str(icon_path)])
if system == "Windows":
args.extend(["--add-data", f"{icon_path};."])
else:
args.extend(["--add-data", f"{icon_path}:."])
# settings.json mit einbinden
settings_path = project_dir / "settings.json"
if settings_path.exists():
if system == "Windows":
args.extend(["--add-data", f"{settings_path};."])
else:
args.extend(["--add-data", f"{settings_path}:."])
# Versteckte Imports
hidden_imports = [
"mutagen",
"mutagen.easyid3",
"mutagen.id3",
"static_ffmpeg",
"tkinter",
"tkinter.ttk",
"tkinter.filedialog",
"tkinter.messagebox",
"tkinter.simpledialog",
]
for imp in hidden_imports:
args.extend(["--hidden-import", imp])
# static_ffmpeg-Binaries einbinden (FFmpeg komplett offline bündeln)
try:
import static_ffmpeg
print("Lade FFmpeg-Binaries herunter (falls noch nicht vorhanden)...")
static_ffmpeg.run.get_or_fetch_platform_executables_else_raise()
sf_path = Path(static_ffmpeg.__file__).parent
if system == "Windows":
args.extend(["--add-data", f"{sf_path};static_ffmpeg"])
else:
args.extend(["--add-data", f"{sf_path}:static_ffmpeg"])
except Exception as e:
print(f"WARNUNG: static_ffmpeg konnte nicht gebündelt werden: {e}")
# Hauptdatei
args.append(str(project_dir / "main.py"))
print(f"Build für {system}...")
print(f"Befehl: {' '.join(args)}")
print()
result = subprocess.run(args, cwd=str(project_dir))
if result.returncode == 0:
# Kopiere settings.json in den dist Ordner
if settings_path.exists():
shutil.copy(settings_path, dist_dir / "settings.json")
# ZIP-Archiv für das Release erstellen
import tempfile
sys_name = "macos" if system == "Darwin" else system.lower()
zip_name = f"fcco-Converter-v1-{sys_name}"
zip_path = dist_dir / zip_name
with tempfile.TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
# App/Exe ins Temp-Verzeichnis kopieren
if system == "Darwin":
shutil.copytree(dist_dir / f"{app_name}.app", tmp / f"{app_name}.app")
else:
shutil.copy(dist_dir / f"{app_name}.exe", tmp / f"{app_name}.exe")
# settings.json mit in die ZIP packen
if settings_path.exists():
shutil.copy(settings_path, tmp / "settings.json")
shutil.make_archive(str(zip_path), "zip", str(tmp))
print()
print(f"Build erfolgreich! Ausgabe in: {dist_dir}")
print(f"ZIP für Release: {zip_path}.zip")
else:
print()
print(f"Build fehlgeschlagen (Code {result.returncode}).")
sys.exit(1)
if __name__ == "__main__":
build()
+191 -77
View File
@@ -3,12 +3,21 @@ import json
import ctypes
import threading
import subprocess
import sys
import io
import shutil
from datetime import datetime
from tkinter import filedialog, messagebox, simpledialog, Toplevel, Button
from tkinter import *
from tkinter.ttk import Progressbar
from concurrent.futures import ThreadPoolExecutor, as_completed
# Behebe NoneType 'write' Fehler in windowed GUI-Modus (PyInstaller --windowed auf Windows/macOS)
if sys.stdout is None:
sys.stdout = io.StringIO()
if sys.stderr is None:
sys.stderr = io.StringIO()
try:
from mutagen.easyid3 import EasyID3
from mutagen.id3 import ID3, APIC
@@ -16,8 +25,42 @@ except ImportError:
messagebox.showerror("Fehler", "Die Bibliothek 'mutagen' ist nicht installiert. Bitte installieren Sie sie mit 'pip install mutagen'.")
exit()
SETTINGS_FILE = "settings.json"
HISTORY_FILE = "history.json"
try:
import static_ffmpeg
except ImportError:
static_ffmpeg = None
def get_ffmpeg_paths():
if static_ffmpeg is not None:
try:
ffmpeg_path, ffprobe_path = static_ffmpeg.run.get_or_fetch_platform_executables_else_raise()
return ffmpeg_path, ffprobe_path
except Exception:
pass
sys_ffmpeg = shutil.which("ffmpeg")
sys_ffprobe = shutil.which("ffprobe")
if sys_ffmpeg and sys_ffprobe:
return sys_ffmpeg, sys_ffprobe
raise RuntimeError("FFmpeg/FFprobe konnte weder über static_ffmpeg noch im System gefunden werden.")
def get_resource_path(relative_path):
if hasattr(sys, "_MEIPASS"):
path = os.path.join(sys._MEIPASS, relative_path)
if os.path.exists(path):
return path
return os.path.join(os.path.abspath("."), relative_path)
def get_config_dir():
if getattr(sys, "frozen", False):
return os.path.dirname(sys.executable)
return os.path.abspath(".")
SETTINGS_FILE = os.path.join(get_config_dir(), "settings.json")
HISTORY_FILE = os.path.join(get_config_dir(), "history.json")
WEEKDAY_SHORT_DE = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]
@@ -25,52 +68,80 @@ DEFAULT_EXPORT_PATHS = {
"Gottesdienst": "gottesdienste",
"Hochzeit": "hochzeiten",
"Weissagung": "weissagungen",
"Jugend": "jugend"
"Jugend": "jugend",
}
def load_settings():
if os.path.exists(SETTINGS_FILE):
with open(SETTINGS_FILE, "r") as f:
return json.load(f)
try:
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
bundled_settings = get_resource_path("settings.json")
if os.path.exists(bundled_settings):
try:
with open(bundled_settings, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return {
"export_paths": DEFAULT_EXPORT_PATHS.copy(),
"threads": 0 # 0 = auto, use all available cores
"threads": 0, # 0 = auto, use all available cores
}
def save_settings(settings):
with open(SETTINGS_FILE, "w") as f:
json.dump(settings, f, indent=2)
def save_settings(settings_data):
try:
with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump(settings_data, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"Fehler beim Speichern der Einstellungen: {e}")
def save_export_history(entry):
history = []
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, "r") as f:
history = json.load(f)
try:
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
history = json.load(f)
except Exception:
history = []
history.append(entry)
with open(HISTORY_FILE, "w") as f:
json.dump(history, f, indent=2)
# Fix pixelation on high-DPI displays
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2) # Per-monitor DPI awareness
except:
try:
ctypes.windll.user32.SetProcessDPIAware() # Fallback for older Windows
except:
pass
with open(HISTORY_FILE, "w", encoding="utf-8") as f:
json.dump(history, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"Fehler beim Speichern der Historie: {e}")
# DPI-Awareness auf Windows setzen (vor Tkinter UI)
if sys.platform == "win32":
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2) # Per-monitor DPI awareness
except Exception:
try:
ctypes.windll.user32.SetProcessDPIAware() # Fallback for older Windows
except Exception:
pass
settings = load_settings()
def set_window_icon(window):
try:
window.iconbitmap("icon.ico")
icon_path = get_resource_path("icon.ico")
if os.path.exists(icon_path):
window.iconbitmap(icon_path)
except Exception:
pass
root = Tk()
set_window_icon(root)
root.title("fcco Converter")
root.geometry("800x1200")
root.geometry("800x800")
Label(root, text="Wähle WAV-Dateien oder Ordner aus:").pack(pady=5)
file_listbox = Listbox(root, width=60)
@@ -86,14 +157,16 @@ base_folder = None # Set when folder is selected
is_converting = False # Track conversion status
conversion_running = False # Prevent multiple conversions
def choose_files():
global file_entries, base_folder
paths = filedialog.askopenfilenames(filetypes=[("WAV-Dateien", "*.wav")])
if paths:
base_folder = None
file_entries = [{'full_path': p, 'rel_dir': ''} for p in paths]
file_entries = [{"full_path": p, "rel_dir": ""} for p in paths]
update_file_list()
def choose_folder():
global file_entries, base_folder
folder = filedialog.askdirectory()
@@ -102,12 +175,13 @@ def choose_folder():
file_entries = []
for root_dir, _, files in os.walk(folder):
for f in files:
if f.lower().endswith('.wav'):
if f.lower().endswith(".wav"):
full_path = os.path.join(root_dir, f)
rel_path = os.path.relpath(root_dir, folder)
file_entries.append({'full_path': full_path, 'rel_dir': rel_path})
file_entries.append({"full_path": full_path, "rel_dir": rel_path})
update_file_list()
def update_file_list():
file_listbox.delete(0, END)
file_status_listbox.delete(0, END)
@@ -115,29 +189,34 @@ def update_file_list():
bar.destroy()
progress_bars.clear()
for entry in file_entries:
basename = os.path.basename(entry['full_path'])
display_name = os.path.join(entry['rel_dir'], basename) if entry['rel_dir'] else basename
basename = os.path.basename(entry["full_path"])
display_name = os.path.join(entry["rel_dir"], basename) if entry["rel_dir"] else basename
file_listbox.insert(END, display_name)
file_status_listbox.insert(END, f"0% – {basename} – Wartet...")
progress = Progressbar(root, orient=HORIZONTAL, length=400, mode='determinate')
progress = Progressbar(root, orient=HORIZONTAL, length=400, mode="determinate")
progress.pack(pady=2)
progress_bars.append(progress)
Button(root, text="Dateien auswählen", command=choose_files).pack(pady=5)
Button(root, text="Ordner auswählen", command=choose_folder).pack(pady=5)
def generate_album_name(veranstaltung=""):
return datetime.now().strftime("%d.%m.%Y") + (f" {veranstaltung}" if veranstaltung else "")
def generate_folder_name(date_part, veranstaltung):
return f"{date_part} {veranstaltung}" if veranstaltung else date_part
def extract_event_from_folder(file_path):
folder_name = os.path.basename(os.path.dirname(file_path))
if len(folder_name) >= 8 and folder_name[:6].isdigit() and folder_name[6:8] in WEEKDAY_SHORT_DE:
return folder_name[:8], folder_name[8:].strip() if len(folder_name) > 8 else ""
return "", ""
def open_settings_window():
win = Toplevel(root)
set_window_icon(win)
@@ -179,10 +258,7 @@ def open_settings_window():
messagebox.showerror("Fehler", "Bitte geben Sie eine gültige Zahl für Threads ein.")
return
settings["metadata"] = {
"artist": artist_entry.get(),
"cover": cover_entry.get()
}
settings["metadata"] = {"artist": artist_entry.get(), "cover": cover_entry.get()}
settings["export_paths"] = {k: v.get() for k, v in entries.items()}
settings["threads"] = threads
save_settings(settings)
@@ -191,12 +267,14 @@ def open_settings_window():
Button(win, text="Speichern", command=save_all).pack(pady=10)
Button(root, text="Einstellungen öffnen", command=open_settings_window).pack(pady=5)
def confirm_metadata_and_type():
meta = settings.get("metadata", {}).copy()
if file_entries:
date_part, veranstaltung = extract_event_from_folder(file_entries[0]['full_path'])
date_part, veranstaltung = extract_event_from_folder(file_entries[0]["full_path"])
if not date_part:
date_part = datetime.now().strftime("%y%m%d") + WEEKDAY_SHORT_DE[datetime.now().weekday()]
else:
@@ -273,19 +351,27 @@ def confirm_metadata_and_type():
return confirmed_data if confirmed_data else None
def get_duration(file):
def get_duration(file, ffprobe_path):
cmd = [
"ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", file
ffprobe_path,
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
file,
]
try:
return float(subprocess.check_output(cmd, universal_newlines=True).strip())
except:
return float(subprocess.check_output(cmd, universal_newlines=True, stderr=subprocess.DEVNULL).strip())
except Exception:
return 0
def convert_file(entry, index, export_dir, meta, use_subdirs):
file = entry['full_path']
rel_dir = entry['rel_dir']
def convert_file(entry, index, export_dir, meta, use_subdirs, ffmpeg_path, ffprobe_path):
file = entry["full_path"]
rel_dir = entry["rel_dir"]
try:
title = os.path.splitext(os.path.basename(file))[0]
if use_subdirs and rel_dir:
@@ -295,34 +381,41 @@ def convert_file(entry, index, export_dir, meta, use_subdirs):
else:
mp3_path = os.path.join(export_dir, f"{title}.mp3")
duration = get_duration(file)
duration = get_duration(file, ffprobe_path)
if duration == 0:
raise Exception("Could not determine file duration.")
raise Exception("Dauer der Datei konnte nicht ermittelt werden.")
threads = settings.get("threads", 0)
cmd = [
"ffmpeg",
"-i", file,
"-threads", str(threads) if threads > 0 else "0",
"-c:a", "libmp3lame",
"-b:a", "192k",
ffmpeg_path,
"-i",
file,
"-threads",
str(threads) if threads > 0 else "0",
"-c:a",
"libmp3lame",
"-b:a",
"192k",
"-y",
mp3_path
"-vn",
mp3_path,
]
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, universal_newlines=True)
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, universal_newlines=True)
while True:
line = process.stderr.readline()
if not line:
break
if "time=" in line:
time_str = line.split("time=")[1].split(" ")[0]
try:
h, m, s = map(float, time_str.split(':'))
time_str = line.split("time=")[1].split(" ")[0]
h, m, s = map(float, time_str.split(":"))
current_time = h * 3600 + m * 60 + s
percentage = min(int((current_time / duration) * 100), 100)
root.after(0, lambda idx=index, pct=percentage, ttl=title: update_progress(idx, pct, ttl, "Konvertiert..."))
except:
root.after(
0, lambda idx=index, pct=percentage, ttl=title: update_progress(idx, pct, ttl, "Konvertiert...")
)
except Exception:
pass
process.wait()
@@ -331,22 +424,22 @@ def convert_file(entry, index, export_dir, meta, use_subdirs):
audiofile = EasyID3(mp3_path)
audiofile["title"] = title
audiofile["artist"] = meta["artist"] or "Unbekannt"
audiofile["album"] = meta["album"] or "Unbekanntes Album"
audiofile["artist"] = meta.get("artist") or "Unbekannt"
audiofile["album"] = meta.get("album") or "Unbekanntes Album"
audiofile["tracknumber"] = str(index + 1)
audiofile["date"] = meta.get("year", "")
audiofile.save()
audiofile = ID3(mp3_path)
with open(meta["cover"], "rb") as img:
audiofile.add(APIC(
encoding=3,
mime='image/jpeg',
type=3,
desc=u'Cover',
data=img.read()
))
audiofile.save()
cover_path = meta.get("cover")
if cover_path and os.path.exists(cover_path):
try:
mime = "image/png" if cover_path.lower().endswith(".png") else "image/jpeg"
audiofile = ID3(mp3_path)
with open(cover_path, "rb") as img:
audiofile.add(APIC(encoding=3, mime=mime, type=3, desc="Cover", data=img.read()))
audiofile.save()
except Exception as e:
print(f"Warnung: Cover konnte nicht eingebunden werden: {e}")
return (index, f"{title}.mp3", None)
except subprocess.CalledProcessError as e:
@@ -354,12 +447,14 @@ def convert_file(entry, index, export_dir, meta, use_subdirs):
except Exception as e:
return (index, os.path.basename(file), str(e))
def update_progress(index, percentage, filename, status):
file_status_listbox.delete(index)
file_status_listbox.insert(index, f"{percentage}% – {filename} – {status}")
progress_bars[index]["value"] = percentage
root.update_idletasks()
def convert():
global is_converting, conversion_running
if not file_entries or conversion_running:
@@ -376,10 +471,12 @@ def convert():
meta = result
content_type = meta["type"]
veranstaltung = meta.get("event", "").strip()
date_part = meta.get("date_part", datetime.now().strftime("%y%m%d") + WEEKDAY_SHORT_DE[datetime.now().weekday()])
date_part = meta.get(
"date_part", datetime.now().strftime("%y%m%d") + WEEKDAY_SHORT_DE[datetime.now().weekday()]
)
# Use subdirectories if a folder was selected
use_subdirs = (base_folder is not None)
use_subdirs = base_folder is not None
if content_type in settings.get("export_paths", {}) and content_type != "Sonstiges":
base_dir = settings["export_paths"][content_type]
@@ -396,8 +493,7 @@ def convert():
settings["last_export_dir"] = export_dir
save_settings(settings)
sorted_entries = sorted(file_entries, key=lambda x: os.path.basename(x['full_path']).lower())
total = len(sorted_entries)
sorted_entries = sorted(file_entries, key=lambda x: os.path.basename(x["full_path"]).lower())
file_status_listbox.delete(0, END)
for e in sorted_entries:
file_status_listbox.insert(END, f"0% – {os.path.basename(e['full_path'])} – Wartet...")
@@ -406,10 +502,24 @@ def convert():
global is_converting, conversion_running
is_converting = True
successful_files = []
try:
ffmpeg_path, ffprobe_path = get_ffmpeg_paths()
except Exception as e:
root.after(0, lambda: messagebox.showerror("FFmpeg Fehler", str(e)))
is_converting = False
conversion_running = False
return
max_workers = settings.get("threads", 0) or os.cpu_count() or 1
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_file = {executor.submit(convert_file, entry, idx, export_dir, meta, use_subdirs): idx for idx, entry in enumerate(sorted_entries)}
future_to_file = {
executor.submit(
convert_file, entry, idx, export_dir, meta, use_subdirs, ffmpeg_path, ffprobe_path
): idx
for idx, entry in enumerate(sorted_entries)
}
for future in as_completed(future_to_file):
index = future_to_file[future]
result = future.result()
@@ -420,11 +530,13 @@ def convert():
update_progress(index, 100, filename, "Fertig!")
successful_files.append(filename)
save_export_history({
"datum": datetime.now().strftime("%d.%m.%Y %H:%M"),
"ordner": export_dir,
"dateien": successful_files
})
save_export_history(
{
"datum": datetime.now().strftime("%d.%m.%Y %H:%M"),
"ordner": export_dir,
"dateien": successful_files,
}
)
# Custom completion popup with "OK" and "Programm schließen"
win = Toplevel(root)
@@ -441,6 +553,7 @@ def convert():
threading.Thread(target=run_conversion).start()
def on_closing():
global is_converting
if is_converting:
@@ -449,6 +562,7 @@ def on_closing():
else:
root.destroy()
Button(root, text="Konvertieren", command=convert).pack(pady=10)
root.protocol("WM_DELETE_WINDOW", on_closing)
+3 -2
View File
@@ -1,2 +1,3 @@
pydub
mutagen
mutagen>=1.47.0
static-ffmpeg>=2.7
pyinstaller>=6.0