From 7f778867c4151da624ff05830df0768aa155c973 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Delacotte?= Date: Wed, 7 May 2025 15:01:34 +0200 Subject: [PATCH] Affichage json et pkl --- requirements.txt | 2 + src/app.py | 66 +++++++++++++++++++++++- src/static/js/functions.js | 80 +++++++++++++++++++++++++++++ src/templates/index.html | 102 ++++++++++++++++++++++++------------- src/test/test.py | 8 +++ 5 files changed, 222 insertions(+), 36 deletions(-) create mode 100644 src/static/js/functions.js create mode 100644 src/test/test.py diff --git a/requirements.txt b/requirements.txt index d1173ff..a0c5309 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,3 +6,5 @@ pandas-ta==0.3.14b matplotlib Flask==2.2.3 Werkzeug==2.2.3 +joblib==1.4.2 + diff --git a/src/app.py b/src/app.py index ff4a251..2c25dcd 100644 --- a/src/app.py +++ b/src/app.py @@ -1,7 +1,16 @@ +from flask import Flask, jsonify, abort, render_template, send_from_directory +import pandas as pd +import json +import zipfile import os -from flask import Flask, render_template +import pickle +import joblib +from io import TextIOWrapper + app = Flask(__name__) +FILES_DIR = '/mnt/external' + @app.route('/') def home(): @@ -14,10 +23,65 @@ def home(): # Retourne le template avec la liste des fichiers return render_template('index.html', files=files) + @app.route('/process', methods=['POST']) def process(): # Traitez ici les données envoyées par l'utilisateur return "Données traitées !" + +@app.route('/read_json/') +def read_json(filename): + full_path = os.path.join(FILES_DIR, filename) + + if filename.endswith('.json'): + with open(full_path) as f: + return f.read(), 200, {'Content-Type': 'application/json'} + + if filename.endswith('.pkl'): + try: + data = joblib.load(full_path) + if isinstance(data, pd.DataFrame): + return data.to_json(orient='split'), 200, {'Content-Type': 'application/json'} + if isinstance(data, dict): + df = pd.DataFrame.from_dict(data) + return df.to_json(orient='split'), 200, {'Content-Type': 'application/json'} + if isinstance(data, list): + df = pd.DataFrame(data) + return df.to_json(orient='split'), 200, {'Content-Type': 'application/json'} + return json.dumps({"error": f"Type {type(data)} non géré."}), 200 + except Exception as e: + return json.dumps({"error": str(e)}), 500 + + elif filename.endswith('.zip'): + try: + with zipfile.ZipFile(full_path) as z: + zip_contents = {} + for name in z.namelist(): + if name.endswith('.json'): + with z.open(name) as f: + zip_contents[name] = json.load(f) + elif name.endswith('.pkl'): + with z.open(name) as f: + try: + data = joblib.load(f) + if isinstance(data, pd.DataFrame): + return data.to_json(orient='split'), 200, {'Content-Type': 'application/json'} + if isinstance(data, dict): + df = pd.DataFrame.from_dict(data) + return df.to_json(orient='split'), 200, {'Content-Type': 'application/json'} + if isinstance(data, list): + df = pd.DataFrame(data) + return df.to_json(orient='split'), 200, {'Content-Type': 'application/json'} + return json.dumps({"error": f"Type {type(data)} non géré."}), 200 + except Exception as e: + return json.dumps({"error": str(e)}), 500 + return json.dumps(zip_contents) + except Exception as e: + return json.dumps({"error": str(e)}), 500 + + return json.dumps({"error": "Fichier non pris en charge"}), 400 + + if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000) diff --git a/src/static/js/functions.js b/src/static/js/functions.js new file mode 100644 index 0000000..069dc10 --- /dev/null +++ b/src/static/js/functions.js @@ -0,0 +1,80 @@ +function loadJson(filename) { + fetch(`/read_json/${filename}`) + .then(res => res.json()) + .then(data => { + const tabButtons = document.getElementById('tab-buttons'); + const tabContents = document.getElementById('tab-contents'); + tabButtons.innerHTML = ''; + tabContents.innerHTML = ''; + + const isMulti = typeof data === 'object' && !Array.isArray(data); + + if (isMulti) { + Object.entries(data).forEach(([name, content], index) => { + const tabId = `tab-${index}`; + const li = document.createElement('li'); + const btn = document.createElement('button'); + btn.textContent = name; + btn.onclick = () => showTab(tabId); + li.appendChild(btn); + tabButtons.appendChild(li); + + const div = document.createElement('div'); + div.id = tabId; + div.className = 'tab-content'; + div.style.display = index === 0 ? 'block' : 'none'; + div.innerHTML = Array.isArray(content) ? renderTable(content) : `
${JSON.stringify(content, null, 2)}
`; + tabContents.appendChild(div); + }); + } else { + const div = document.createElement('div'); + div.innerHTML = `
${JSON.stringify(data, null, 2)}
`; + tabContents.appendChild(div); + } + }) + .catch(err => alert("Erreur : " + err.message)); +} + +function renderTable(rows) { + if (!rows.length) return "

Aucune donnée

"; + const headers = Object.keys(rows[0]); + const thead = `${headers.map(h => `${h}`).join('')}`; + const tbody = rows.map(r => `${headers.map(h => `${r[h]}`).join('')}`).join(''); + return `${thead}${tbody}
`; +} + + +function showTab(tabId) { + document.querySelectorAll('.tab-content').forEach(div => { + div.style.display = 'none'; + }); + document.getElementById(tabId).style.display = 'block'; +} + +function graph() { + // Initialiser l'instance de graphique + var chart = echarts.init(document.getElementById('chart')); + + // Définir les options du graphique + var option = { + title: { + text: 'Exemple de Graphique Linéaire' + }, + tooltip: {}, + legend: { + data: ['Ventes'] + }, + xAxis: { + data: ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'] + }, + yAxis: {}, + series: [{ + name: 'Ventes', + type: 'line', + data: [5, 20, 36, 10, 10, 20, 30] + }] + }; + + // Utiliser les options pour afficher le graphique + chart.setOption(option); + } \ No newline at end of file diff --git a/src/templates/index.html b/src/templates/index.html index 2df2253..8a2784b 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -5,6 +5,7 @@ Statistiques Freqtrade + @@ -48,51 +103,28 @@

Fichiers :

- - -
-

Graphique

- -
+
+
+
    +
    +
    +
    - diff --git a/src/test/test.py b/src/test/test.py new file mode 100644 index 0000000..7d48bc4 --- /dev/null +++ b/src/test/test.py @@ -0,0 +1,8 @@ +import joblib + +try: + model = joblib.load('/mnt/external/backtest-result-2025-05-05_13-29-26_exited.pkl') + print("Fichier chargé avec joblib.") + print(model) +except Exception as e: + print(f"Erreur avec joblib : {e}")