| import gradio as gr |
| import numpy as np |
| import matplotlib.pyplot as plt |
| import versDV as dv |
| from math import pi |
| import pandas as pd |
| import io |
| import base64 |
| import matplotlib |
| matplotlib.use('Agg') |
| import PIL.Image |
| import tempfile |
| import os |
|
|
| def calculate_dang_van(sigma1, omega, time_final, time_step, point_size, show_grid): |
| """ |
| Fonction principale - Version CORRIGÉE avec fichiers temporaires |
| """ |
| try: |
| print(f"Début calcul: sigma1={sigma1}, omega={omega}") |
| |
| |
| points1 = dv.nuage(sigma1, omega, time_step, time_final) |
| points2 = dv.nuageOrt(sigma1, omega, time_step, time_final) |
| print(f"Points calculés: {len(points1)} et {len(points2)}") |
| |
| |
| alpha = 0.3 |
| beta = float(np.max(points2[:, 1])) |
| print(f"Alpha={alpha}, Beta={beta}") |
| |
| |
| fig, ax = plt.subplots(figsize=(8, 6)) |
| |
| ax.scatter(points1[:, 0], points1[:, 1], c='red', s=point_size, |
| label='Traction-Compression', alpha=0.7) |
| ax.scatter(points2[:, 0], points2[:, 1], c='blue', s=point_size, |
| label='Torsion', alpha=0.7) |
| |
| p_max_val = max(float(np.max(points1[:, 0])), float(np.max(points2[:, 0]))) * 1.2 |
| p_range = np.linspace(0, p_max_val, 50) |
| tau_limit = beta - alpha * p_range |
| ax.plot(p_range, tau_limit, 'g--', linewidth=2, label='Limite fatigue') |
| |
| ax.set_xlabel('Pression hydrostatique (MPa)') |
| ax.set_ylabel('Cisaillement max (MPa)') |
| ax.set_title(f'Diagramme de Dang Van (sigma1={sigma1} MPa)') |
| ax.legend() |
| if show_grid: |
| ax.grid(True, alpha=0.3) |
| |
| |
| buf = io.BytesIO() |
| fig.savefig(buf, format='png', dpi=100) |
| plt.close(fig) |
| buf.seek(0) |
| plot_array = np.array(PIL.Image.open(io.BytesIO(buf.read()))) |
| buf.close() |
| print(f"Graphique créé: {plot_array.shape}") |
| |
| |
| df1 = pd.DataFrame(points1, columns=['Pression_hydro', 'Cisaillement_max']) |
| df2 = pd.DataFrame(points2, columns=['Pression_hydro', 'Cisaillement_max']) |
| |
| |
| temp_file1 = tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') |
| df1.to_csv(temp_file1.name, index=False) |
| temp_file1.close() |
| |
| temp_file2 = tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, encoding='utf-8') |
| df2.to_csv(temp_file2.name, index=False) |
| temp_file2.close() |
| |
| print(f"Fichiers CSV créés: {temp_file1.name}, {temp_file2.name}") |
| |
| |
| rapport = f"""RÉSULTATS - CRITÈRE DE DANG VAN |
| ============================== |
| Date: Analyse automatique |
| |
| PARAMÈTRES: |
| - Contrainte σ₁: {sigma1} MPa |
| - Fréquence ω: {omega:.2f} rad/s |
| - Temps final: {time_final} s |
| - Pas de temps: {time_step} s |
| |
| RÉSULTATS: |
| - Points traction: {len(points1)} |
| - Points torsion: {len(points2)} |
| - α (pression): {alpha} |
| - β (limite): {beta:.2f} MPa |
| - Équation: τ ≤ {beta:.2f} - {alpha} × p_h |
| |
| FIN DU RAPPORT |
| """ |
| |
| print("Calcul terminé avec succès") |
| |
| |
| return plot_array, temp_file1.name, temp_file2.name, rapport |
| |
| except Exception as e: |
| print(f"ERREUR: {e}") |
| import traceback |
| traceback.print_exc() |
| |
| return None, "/tmp/error1.csv", "/tmp/error2.csv", f"ERREUR: {str(e)}" |
|
|
| |
| if __name__ == "__main__": |
| print("=== TEST LOCAL ===") |
| result = calculate_dang_van(100, 6.28, 1.0, 0.1, 30, True) |
| print(f"Image: {type(result[0])}, shape={result[0].shape if hasattr(result[0], 'shape') else 'N/A'}") |
| print(f"CSV1: {result[1]}") |
| print(f"CSV2: {result[2]}") |
| print(f"Rapport: {len(result[3])} chars") |
| |
| |
| for f in [result[1], result[2]]: |
| if os.path.exists(f): |
| print(f"✅ Fichier existe: {f} ({os.path.getsize(f)} bytes)") |
| else: |
| print(f"❌ Fichier n'existe pas: {f}") |
| |
| |
| if result[0] is not None: |
| PIL.Image.fromarray(result[0]).save('test_output.png') |
| print("✅ Image sauvegardée dans test_output.png") |
| |
| print("=== TEST TERMINÉ ===") |
|
|
| |
| demo = gr.Interface( |
| fn=calculate_dang_van, |
| inputs=[ |
| gr.Slider(10, 200, 100, label="Contrainte σ₁ (MPa)"), |
| gr.Slider(0.1, 10, 6.28, label="Fréquence ω (rad/s)"), |
| gr.Slider(0.1, 2.0, 1.0, label="Temps final (s)"), |
| gr.Slider(0.001, 0.1, 0.1, label="Pas de temps (s)"), |
| gr.Slider(10, 100, 30, label="Taille points"), |
| gr.Checkbox(True, label="Afficher grille") |
| ], |
| outputs=[ |
| gr.Image(type="numpy", label="📈 Graphique Dang Van"), |
| gr.File(label="💾 Données traction (.csv)"), |
| gr.File(label="💾 Données torsion (.csv)"), |
| gr.Textbox(label="📋 Rapport d'analyse", lines=10) |
| ], |
| title="Dang Van - École Centrale Lyon", |
| description="Application d'analyse de fatigue selon le critère de Dang Van" |
| ) |
|
|
| if __name__ == "__main__": |
| demo.launch(server_name="0.0.0.0", server_port=7860) |