The error "invalid pdf structure" generally indicates that the PDF file being generated is either corrupted or not being saved correctly. Here are a few potential issues and their solutions to help you troubleshoot the problem:
-
Indentation and Code Structure:
Ensure proper indentation and structure in your code. Python code blocks should be correctly indented. Your try-except block and the for loop must have proper indentation.
-
Correct Path Handling:
Make sure to use consistent and correct path operations. The way paths are being joined and used should be correct to avoid any path issues.
-
Saving Figures:
Make sure each figure is properly created and saved. Ensure the plot(i) function is defined and working correctly.
-
MLflow Logging:
Ensure that the artifact logging to MLflow is happening after the PDF file has been properly closed and saved.
-
Exception Handling:
Your exception handling in the try-except block catches an exception but continues execution, which might bypass necessary steps if an error occurs.
Here's an improved version of your script, addressing these issues:
import os
import mlflow
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Your plot function should be defined. Here's a simple placeholder.
def plot(i):
fig, ax = plt.subplots()
ax.plot([0, 1, 2], [i, i**2, i**3]) # Example plot
return fig
# Set your MLflow tracking URI
mlflow.set_tracking_uri("http://od-eto:5002/")
# Search for runs
runs = mlflow.search_runs(experiment_ids=experiment_id, order_by=["start_time desc"], max_results=1)
if len(runs) > 0:
run_id = runs['run_id'][0]
else:
raise ValueError("No runs found for the given experiment ID.")
# Start run
mlflow.start_run(run_id=run_id)
try:
plot_path = os.path.join(os.getcwd(), f'{work_plots_path}', f'График для {run_name} для модели {model_rev} тестовой выборке.pdf')
with PdfPages(plot_path) as pdf:
for i in range(0, forecasts.shape[0]):
fig = plot(i)
pdf.savefig(fig, bbox_inches='tight')
plt.close(fig)
# Log artifact in MLflow
mlflow.log_artifact(plot_path)
finally:
mlflow.end_run()
Key Improvements:
- Indentation: Corrected indentation throughout the code, which is crucial for Python scripts.
- Ensuring Figures are Created: Ensured that a valid figure is created in the
plot(i) function.
- Closing the PDF File Properly: Ensured the
PdfPages context manager closes properly before logging the artifact.
- Path Handling: Used
os.path.join more consistently and correctly.
Ensure to replace placeholder parts like experiment_id, work_plots_path, run_name, model_rev, and forecasts with actual variables and valid data from your environment.
If the issue persists or the plot function itself is at fault, consider inspecting if any part of plot(i) might be failing to generate a valid figure or if there are issues with your data.