import pandas as pd import numpy as np import tkinter as tk from tkinter import…
- User
import pandas as pd import numpy as np import tkinter as tk from tkinter import messagebox, filedialog from openpyxl import Workbook from openpyxl.utils.dataframe import dataframe_to_rows from openpyxl.chart import BarChart, Reference, LineChart from openpyxl.drawing.image import Image
from sklearn.linear_model import LinearRegression
def abrir_limites_margen(): limite_window = tk.Toplevel(app) limite_window.title("Límites de Margen por Percepción")
tk.Label(limite_window, text="Configura los límites de margen para cada percepción:").grid(row=0, columnspan=2, pady=5) row_num = 1 for percepcion, limite_var in limites_margen.items(): tk.Label(limite_window, text=f"Límite para {percepcion}:").grid(row=row_num, column=0, pady=5) tk.Entry(limite_window, textvariable=limite_var).grid(row=row_num, column=1, pady=5) row_num += 1 tk.Button(limite_window, text="Confirmar", command=limite_window.destroy).grid(row=row_num, columnspan=2, pady=10)def crear_ventana_parametros(): param_window = tk.Toplevel(app) param_window.title("Parámetros de Cálculo de Márgenes")
tk.Label(param_window, text="Margen Mínimo por Unidad:").grid(row=0, column=0, pady=5) margen_minimo_entry = tk.Entry(param_window) margen_minimo_entry.grid(row=0, column=1, pady=5) margen_minimo_entry.insert(0, "10") tk.Label(param_window, text="Margen Máximo por Unidad:").grid(row=1, column=0, pady=5) margen_maximo_entry = tk.Entry(param_window) margen_maximo_entry.grid(row=1, column=1, pady=5) margen_maximo_entry.insert(0, "25") tk.Label(param_window, text="Porcentaje Máximo Margen:").grid(row=2, column=0, pady=5) porcentaje_margen_entry = tk.Entry(param_window) porcentaje_margen_entry.grid(row=2, column=1, pady=5) porcentaje_margen_entry.insert(0, "0.35") tk.Label(param_window, text="Margen Objetivo Mínimo:").grid(row=3, column=0, pady=5) margen_min_entry = tk.Entry(param_window) margen_min_entry.grid(row=3, column=1, pady=5) margen_min_entry.insert(0, "16") tk.Label(param_window, text="Margen Objetivo Máximo:").grid(row=4, column=0, pady=5) margen_max_entry = tk.Entry(param_window) margen_max_entry.grid(row=4, column=1, pady=5) margen_max_entry.insert(0, "17") tk.Button(param_window, text="Calcular", command=lambda: ejecutar_calculo( margen_minimo_entry.get(), margen_maximo_entry.get(), porcentaje_margen_entry.get(), margen_min_entry.get(), margen_max_entry.get(), param_window)).grid(row=5, columnspan=2, pady=10)def validar_entrada(valor): try: val = float(valor) if val < 0: raise ValueError return val except ValueError: raise ValueError("Por favor, introduce un número válido y mayor o igual a cero.")
def calcular_margen(df, margen_minimo_por_unidad, margen_maximo_por_unidad, porcentaje_maximo_margen, margen_objetivo_min, margen_objetivo_max): df_resultado = pd.DataFrame() margen_objetivo_promedio = (margen_objetivo_min + margen_objetivo_max) / 2
for column in ['Percepció', 'Costo neto', 'Unitats 2024', 'PVP NEX']: if column not in df.columns: raise ValueError(f"La columna '{column}' no se encuentra en el DataFrame.") for perception, grupo in df.groupby('Percepció'): multiplicador = percepcion_margen.get(perception, 1.0) grupo['Margen por Unidad'] = grupo['Costo neto'] * multiplicador * porcentaje_maximo_margen grupo['Margen por Unidad'] = np.clip(grupo['Margen por Unidad'], margen_minimo_por_unidad, margen_maximo_por_unidad) limite_margen_percepcion = limites_margen.get(perception).get() for idx, row in grupo.iterrows(): if pd.notna(row['PVP NEX']) and row['PVP NEX'] > 0: pvp_final = row['Costo neto'] + row['Margen por Unidad'] diferencia = row['PVP NEX'] - pvp_final if diferencia < 0 or diferencia > limite_margen_percepcion: margen_ajuste = min(max(0, diferencia), limite_margen_percepcion) nuevo_pvp_final = row['PVP NEX'] - margen_ajuste grupo.at[idx, 'Margen por Unidad'] = max(0, nuevo_pvp_final - row['Costo neto']) grupo['Check'] = np.where(grupo['PVP NEX'] > 0, grupo['Costo neto'] + grupo['Margen por Unidad'] - grupo['PVP NEX'], np.nan) df_resultado = pd.concat([df_resultado, grupo]) margen_promedio_ponderado_final = (df_resultado['Margen por Unidad'] * df_resultado['Unitats 2024']).sum() / df_resultado['Unitats 2024'].sum() return df_resultado, margen_promedio_ponderado_final - Assistant
Para lograr que tu programa de Python se ejecute sin necesidad de abrir Jupyter Notebook, puedes seguir estos pasos para crear un ejecutable que se ejecute al hacer clic en un icono. Te mostraré cómo hacerlo usando
PyInstaller, que es una herramienta que empaqueta tu aplicación de Python en un único ejecutable: - User
============================================================= A RecursionError (maximum recursion depth exceeded) occurred. For working around please follow these instructions
-
In your program's .spec file add this line near the top::
import sys ; sys.setrecursionlimit(sys.getrecursionlimit() * 5)
-
Build your program by running PyInstaller with the .spec file as argument::
pyinstaller myprog.spec
-
If this fails, you most probably hit an endless recursion in PyInstaller. Please try to track this down has far as possible, create a minimal example so we can reproduce and open an issue at https://github.com/pyinstaller/pyinstaller/issues following the instructions in the issue template. Many thanks.
Explanation: Python's stack-limit is a safety-belt against endless recursion, eating up memory. PyInstaller imports modules recursively. If the structure how modules are imported within your program is awkward, this leads to the nesting being too deep and hitting Python's stack-limit.
With the default recursion limit (1000), the recursion error occurs at about 115 nested imported, with limit 2000 at about 240, with limit 5000 at about 660.
-
- Assistant
- User
- Assistant
Parece que estás ejecutando el programa
pyinstallerpara convertir tu archivo Python en un ejecutable, pero obtuviste un error que menciona que el archivo de especificaciones no se encontró. Esto puede suceder si no usaste antes con tu script, o si el archivo se encuentra en una ubicación diferente. Aquí tienes cómo proceder para crear correctamente el ejecutable de tu script de Python: - User
- Assistant
- User
1837 INFO: PyInstaller: 6.7.0, contrib hooks: 2024.8 1838 INFO: Python: 3.12.3 (conda) 1880 INFO: Platform: Windows-11-10.0.22631-SP0 Traceback (most recent call last): File "C:\Users\ismael.gallardo\AppData\Local\anaconda3\Scripts\pyinstaller-script.py", line 10, in sys.exit(run()) ^^^^^ File "C:\Users\ismael.gallardo\AppData\Local\anaconda3\Lib\site-packages\PyInstaller_main_.py", line 212, in run run_build(pyi_config, spec_file, **vars(args)) File "C:\Users\ismael.gallardo\AppData\Local\anaconda3\Lib\site-packages\PyInstaller_main_.py", line 69, in run_build PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs) File "C:\Users\ismael.gallardo\AppData\Local\anaconda3\Lib\site-packages\PyInstaller\building\build_main.py", line 1189, in main build(specfile, distpath, workpath, clean_build) File "C:\Users\ismael.gallardo\AppData\Local\anaconda3\Lib\site-packages\PyInstaller\building\build_main.py", line 1126, in build code = compile(f.read(), spec, 'exec') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "daniPneu.spec", line 19 hiddenimports=['MySQLdb', 'psycopg2'], ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: keyword argument repeated: hiddenimports
- Assistant