StreamlitKCDI / app.py
Mdolores's picture
Upload app.py
c027433 verified
import os
import pandas as pd
from flask import Flask, request, jsonify, render_template_string
app = Flask(__name__)
# Simulación de la función de cálculo del KCDI
# Reemplaza esta función con tu lógica real de cálculo del KCDI
def calculate_kcdi(df):
"""
Calcula el KCDI a partir de un DataFrame de pandas.
"""
try:
# Aquí iría tu código para procesar el DataFrame de Scopus
# y calcular los valores de KCDI, entropía, etc.
# Por ejemplo, basándote en la estructura de tu análisis.
# Valores simulados para fines de demostración
kcdi = 0.916
h_shannon = 1.668
w_bar = 0.12
description = "Resultado simulado para demostración"
return {
'kcdi_value': kcdi,
'H_shannon': h_shannon,
'W_bar': w_bar,
'description': description
}
except Exception as e:
return {'error': f'Error en el cálculo: {str(e)}'}
# Plantilla HTML y JavaScript directamente en el código de Python
html_template = """
<!DOCTYPE html>
<html>
<head>
<title>Calculadora KCDI</title>
<style>
body { font-family: 'Helvetica', 'Arial', sans-serif; line-height: 1.6; padding: 20px; max-width: 800px; margin: auto; }
h1 { color: #333; }
.container { background: #f9f9f9; padding: 20px; border-radius: 8px; border: 1px solid #ddd; }
input[type="file"] { margin-bottom: 10px; }
button { background-color: #4CAF50; color: white; padding: 10px 15px; border: none; border-radius: 5px; cursor: pointer; }
button:hover { background-color: #45a049; }
#results { margin-top: 20px; padding: 15px; border: 1px solid #ccc; border-radius: 5px; background: #fff; }
</style>
</head>
<body>
<div class="container">
<h1>Calculadora de Índice KCDI</h1>
<p>Sube tu archivo CSV exportado de Scopus para calcular el KCDI.</p>
<form id="upload-form" enctype="multipart/form-data">
<input type="file" name="file" accept=".csv">
<button type="submit">Calcular KCDI</button>
</form>
</div>
<div id="results">
</div>
<script>
document.getElementById('upload-form').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = '<p>Calculando...</p>';
fetch('/calculate', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.error) {
resultsDiv.innerHTML = `<p style="color:red;">Error: ${data.error}</p>`;
} else {
resultsDiv.innerHTML = `
<h2>Resultados:</h2>
<p>KCDI: <strong>${data.kcdi_value}</strong></p>
<p>Entropía (H): <strong>${data.H_shannon}</strong></p>
<p>W Bar: <strong>${data.W_bar}</strong></p>
<p>Descripción: <strong>${data.description}</strong></p>
`;
}
})
.catch(error => {
resultsDiv.innerHTML = `<p style="color:red;">Error de conexión: ${error}</p>`;
});
});
</script>
</body>
</html>
"""
@app.route('/')
def index():
return render_template_string(html_template)
@app.route('/calculate', methods=['POST'])
def calculate():
if 'file' not in request.files:
return jsonify({'error': 'No se encontró el archivo'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No se seleccionó ningún archivo'}), 400
if file:
try:
df = pd.read_csv(file)
results = calculate_kcdi(df)
return jsonify(results), 200
except Exception as e:
return jsonify({'error': f'Error en el procesamiento del archivo: {str(e)}'}), 500
if __name__ == '__main__':
app.run(debug=True)