-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.py
More file actions
173 lines (146 loc) · 6.81 KB
/
script.py
File metadata and controls
173 lines (146 loc) · 6.81 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
import os
import sys
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from PyPDF2 import PdfReader, PdfWriter
# =======================================================
# CONFIGURACIÓN DE RUTAS (PARA PYINSTALLER)
# =======================================================
def resource_path(relative_path):
""" Obtiene la ruta absoluta de los recursos, compatible con PyInstaller """
try:
# PyInstaller crea una carpeta temporal y almacena la ruta en _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
# =======================================================
# TABLA DE EQUIVALENCIAS
# =======================================================
EQUIVALENCIAS = [
("Director", 0, "DIR"), ("Flautín", 1, "FLTN"), ("Flauta 1", 2, "FLT1"),
("Flauta 2", 3, "FLT2"), ("Oboe 1", 4, "OB1"), ("Oboe 2", 5, "OB2"),
("Fagot", 6, "FAG"), ("Clarinete Pral.", 7, "CLPR"), ("Clarinete 1", 8, "CL1"),
("Clarinete 2", 9, "CL2"), ("Clarinete 3", 10, "CL3"), ("Clarinete Bajo", 11, "CLB"),
("Saxo alto 1", 12, "SXA1"), ("Saxo alto 2", 13, "SXA2"), ("Saxo tenor 1", 14, "SXT1"),
("Saxo tenor 2", 15, "SXT2"), ("Saxo Barítino", 16, "SXB"), ("Fliscorno 1", 17, "FLIS1"),
("Fliscorno 2", 18, "FLIS2"), ("Trompeta 1", 19, "TPT1"), ("Trompeta 2", 20, "TPT2"),
("Trompeta 3", 21, "TPT3"), ("Trompa 1", 22, "TPA1"), ("Trompa 2", 23, "TPA2"),
("Trompa 3", 24, "TPA3"), ("Trombón 1", 25, "TBN1"), ("Trombón 2", 26, "TBN2"),
("Trombón 3", 27, "TBN3"), ("Bombardino 1", 28, "BOMB DO"), ("Bombardino 2", 28, "BOMB DO 2"),
("Bombardino 1 sib", 28, "BOMB SIB"), ("Bombardino 2 sib", 28, "BOMB SIB 2"),
("Tuba 1", 29, "TB1"), ("Tuba 2", 29, "TB2"), ("Caja", 30, "CAJ"),
("Bombo y Platos", 31, "BYP"), ("Tambores", 34, "TAMB"), ("Otros", 32, "TIMB"),
("Corneta", 40, "COR")
]
# =======================================================
# FUNCIONES LÓGICAS
# =======================================================
def generar_diccionario_equivalencias():
eq = {}
for instrumento, cod1, cod2 in EQUIVALENCIAS:
clave = instrumento.lower().replace(".", "").strip()
eq[clave] = (cod1, cod2)
return eq
def encontrar_equivalencia(nombre_instrumento, equivalencias_dict):
nombre = nombre_instrumento.lower().strip()
for instrumento, (cod1, cod2) in equivalencias_dict.items():
if instrumento in nombre:
return cod1, cod2
return None
def extraer_paginas(pdf_path, start, end, output_path):
reader = PdfReader(pdf_path)
writer = PdfWriter()
for i in range(start - 1, end):
if i < len(reader.pages):
writer.add_page(reader.pages[i])
with open(output_path, "wb") as f:
writer.write(f)
def procesar(pdf_path, output_dir, tabla):
equivalencias_dict = generar_diccionario_equivalencias()
nombre_marcha = os.path.splitext(os.path.basename(pdf_path))[0].upper()
carpeta_salida = os.path.join(output_dir, nombre_marcha)
os.makedirs(carpeta_salida, exist_ok=True)
for item in tabla.get_children():
nombre_instr, inicio, fin = tabla.item(item)['values']
if not str(inicio).isdigit() or not str(fin).isdigit():
continue
start, end = int(inicio), int(fin)
equivalencia = encontrar_equivalencia(nombre_instr, equivalencias_dict)
if equivalencia:
cod1, cod2 = equivalencia
nuevo_nombre = f"{cod1}. {cod2} {nombre_marcha}.pdf"
output_path = os.path.join(carpeta_salida, nuevo_nombre)
extraer_paginas(pdf_path, start, end, output_path)
messagebox.showinfo("Proceso completado", "🎶 Todos los PDFs han sido generados.")
# =======================================================
# INTERFAZ GRÁFICA (TKINTER)
# =======================================================
root = tk.Tk()
root.title("Divisor de PDF por Instrumento")
# --- MANEJO DE ICONOS COMPATIBLE ---
try:
if sys.platform == "win32":
# Windows acepta .ico directamente
root.iconbitmap(resource_path("icon.ico"))
elif sys.platform == "darwin":
# Mac requiere .icns o PhotoImage para la ventana
# Si tienes icon.icns, lo usamos:
icon_img = tk.PhotoImage(file=resource_path("icon.icns"))
root.iconphoto(True, icon_img)
except Exception as e:
print(f"Aviso: No se pudo cargar el icono personalizado: {e}")
pdf_path = tk.StringVar()
output_dir = tk.StringVar()
def seleccionar_pdf():
path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
if path: pdf_path.set(path)
def seleccionar_salida():
path = filedialog.askdirectory()
if path: output_dir.set(path)
frame = ttk.Frame(root, padding=10)
frame.pack(fill="both", expand=True)
# Selección de archivos
ttk.Label(frame, text="PDF maestro:").grid(row=0, column=0, sticky="w")
ttk.Entry(frame, textvariable=pdf_path, width=50).grid(row=0, column=1, padx=5)
ttk.Button(frame, text="Seleccionar", command=seleccionar_pdf).grid(row=0, column=2)
ttk.Label(frame, text="Carpeta de salida:").grid(row=1, column=0, sticky="w", pady=5)
ttk.Entry(frame, textvariable=output_dir, width=50).grid(row=1, column=1, padx=5)
ttk.Button(frame, text="Seleccionar", command=seleccionar_salida).grid(row=1, column=2)
# Tabla de instrumentos
tabla = ttk.Treeview(frame, columns=("Instrumento", "Inicio", "Fin"), show="headings", height=15)
tabla.grid(row=2, column=0, columnspan=3, pady=10)
for col in ("Instrumento", "Inicio", "Fin"):
tabla.heading(col, text=col)
tabla.column(col, width=140)
for instrumento, _, _ in EQUIVALENCIAS:
tabla.insert("", "end", values=(instrumento, "", ""))
def editar_celda(event):
item = tabla.identify_row(event.y)
col = tabla.identify_column(event.x)
if not item or col == "#1": return
x, y, width, height = tabla.bbox(item, col)
valor_actual = tabla.item(item, "values")[int(col[1]) - 1]
entry = tk.Entry(tabla)
entry.place(x=x, y=y, width=width, height=height)
entry.insert(0, valor_actual)
entry.focus()
def guardar(event):
nuevo_valor = entry.get()
valores = list(tabla.item(item, "values"))
col_index = int(col[1]) - 1
valores[col_index] = nuevo_valor
if col_index == 1 and (valores[2] == "" or valores[2] is None):
valores[2] = nuevo_valor
tabla.item(item, values=valores)
entry.destroy()
entry.bind("<Return>", guardar)
entry.bind("<FocusOut>", lambda e: entry.destroy())
tabla.bind("<Double-1>", editar_celda)
def ejecutar():
if not pdf_path.get() or not output_dir.get():
messagebox.showerror("Error", "Selecciona el PDF y la carpeta de salida.")
return
procesar(pdf_path.get(), output_dir.get(), tabla)
ttk.Button(frame, text="Generar PDFs", command=ejecutar).grid(row=3, column=1, pady=10)
root.mainloop()