Affichage json et pkl

This commit is contained in:
Jérôme Delacotte
2025-05-07 15:01:34 +02:00
parent e18d112e54
commit 7f778867c4
5 changed files with 222 additions and 36 deletions

View File

@@ -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/<path:filename>')
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)

View File

@@ -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) : `<pre>${JSON.stringify(content, null, 2)}</pre>`;
tabContents.appendChild(div);
});
} else {
const div = document.createElement('div');
div.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
tabContents.appendChild(div);
}
})
.catch(err => alert("Erreur : " + err.message));
}
function renderTable(rows) {
if (!rows.length) return "<p>Aucune donnée</p>";
const headers = Object.keys(rows[0]);
const thead = `<thead><tr>${headers.map(h => `<th>${h}</th>`).join('')}</tr></thead>`;
const tbody = rows.map(r => `<tr>${headers.map(h => `<td>${r[h]}</td>`).join('')}</tr>`).join('');
return `<table border="1">${thead}<tbody>${tbody}</tbody></table>`;
}
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);
}

View File

@@ -5,6 +5,7 @@
<meta charset="UTF-8">
<title>Statistiques Freqtrade</title>
<script src="{{ url_for('static', filename='js/echarts.js') }}"></script>
<script src="{{ url_for('static', filename='js/functions.js') }}"></script>
<style>
/* Style de la page */
body {
@@ -40,6 +41,60 @@
background-color: #f0f0f0;
}
.file-list li {
cursor: pointer;
margin: 5px 0;
}
.content {
flex-grow: 1;
padding: 10px;
}
.tab {
display: none;
}
.tab.active {
display: block;
}
.tab-header {
font-weight: bold;
margin-top: 20px;
}
pre {
background: #f5f5f5;
padding: 10px;
overflow-x: auto;
}
#json-tabs {
display: flex;
flex-direction: column;
}
#tab-buttons {
list-style: none;
padding: 0;
display: flex;
gap: 0.5rem;
}
#tab-buttons li {
display: inline;
}
#tab-buttons button {
padding: 0.4rem 1rem;
cursor: pointer;
}
.tab-content {
border: 1px solid #ccc;
padding: 1rem;
background: #f9f9f9;
margin-top: 1rem;
white-space: pre-wrap;
}
</style>
</head>
<body>
@@ -48,51 +103,28 @@
<h3>Fichiers :</h3>
<ul>
{% for file in files %}
<li>{{ file }}</li>
<li onclick="loadJson('{{ file }}')">{{ file }}</li>
{% endfor %}
</ul>
</div>
<!-- Colonne droite avec le graphique (remplacez avec votre graphique) -->
<div class="graph-container">
<h3>Graphique</h3>
<!-- Div où le graphique sera affiché -->
<div id="chart" style="width: 600px; height: 400px;"></div>
<div class="content">
<div id="json-tabs">
<ul id="tab-buttons"></ul>
<div id="tab-contents"></div>
</div>
</div>
<!-- Colonne droite avec le graphique (remplacez avec votre graphique)
<div class="graph-container">
<h3>Graphique</h3>
<div id="chart" style="width: 600px; height: 400px;"></div>
</div>
-->
<form action="/process" method="post">
<input type="text" name="data" placeholder="Entrez des données">
<button type="submit">Envoyer</button>
</form>
<script>
// 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);
</script>
</body>
</html>

8
src/test/test.py Normal file
View File

@@ -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}")