graph_generator / app.py
juancamval's picture
Update app.py
266dfd2 verified
raw
history blame
4.34 kB
# Aplicacion principal para cargar modelo, generar los prompts, y el la explicacion de los datos
import streamlit as st
import os
import re
import pandas as pd
from supabase import create_client, Client
from transformers import pipeline
# funcion para extraccion de codigo del modelo
def extract_code(llm_output):
code_match = re.search(r"```python\n(.*?)\n```", llm_output, re.DOTALL)
if code_match:
return code_match.group(1)
return None
# funcion para prompts y ejemplo basico
#prompt = "Generate a graph idea based on European fertility data."
#output = generator(prompt, max_length=50, num_return_sequences=1)[0]['generated_text']
# Aqui vamos a añadir los prompts, comparativa entre paises, lo ideal es mas de uno, pero podriamos iniciar en un 1v1 con la metrica
# Vamos a generar un codigo para luego ejecutarlo con un exec() y poder imprimir en Streamlit st.pyplot()
def generate_graph_prompt(country1, country2, metric, start_year, end_year):
prompt = f"""You have access to a database of European countries with data on {metric}, labor force participation, population, and their predictions for future years.
Generate Python code using matplotlib to create a line graph showing the trend of {metric} for {country1} and {country2} from {start_year} to {end_year}.
Also, provide a concise explanation of what this graph represents for an end user who might not be familiar with the data.
"""
return prompt
# Ejemplo de como quedaria el prompt que recibiria el modelo
#prompt = generate_graph_prompt("Germany", "France", "fertility rate", 2020, 2030)
#Aqui van las credenciales, conectar las credenciales de Supabase en "Secrets"
# conexion a supabase
SUPABASE_URL = os.environ.get("SUPABASE_URL")
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
def load_data(table):
"""fertility, geo data, labor, population y predictions """
try:
if supabase:
response = supabase.from_(table).select("*").execute()
print(f"Response object: {response}") # Inspect the entire response
print(f"Response type: {type(response)}") # Check the object type
# Try accessing potential error-related attributes
if hasattr(response, 'data'):
print(f"Response data: {response.data}")
return pd.DataFrame(response.data)
elif hasattr(response, 'status_code'):
print(f"Response status code: {response.status_code}")
elif hasattr(response, '_error'): # Older versions might use this
print(f"Older error attribute: {response._error}")
st.error(f"Error fetching data: {response._error}")
return pd.DataFrame()
else:
st.info("Response object does not have 'data' or known error attributes. Check the logs.")
return pd.DataFrame()
else:
st.error("Supabase client not initialized. Check environment variables.")
return pd.DataFrame()
except Exception as e:
st.error(f"An error occurred during data loading: {e}")
return pd.DataFrame()
data = load_data("labor")
# Pendiente las Keys, dependiendo del modelo que escojamos
model_name = "google/flan-t5-small" # Probando modelos
generator = pipeline("text-generation", model=model_name)
# Inicio de Streamlit (hice lo basico, podemos mejorarla)
st.title("_Europe GraphGen_ :blue[Graph generator] :flag-eu:")
user_input = st.text_input("What graphics do you have in mind")
generate_button = st.button("Generate")
if generate_button and user_input:
if data.empty and supabase is not None:
st.warning("Successfully connected to Supabase, but no data was loaded (either the table is empty or there was a query issue). Check the error message above if any.")
elif not data.empty:
st.success("Successfully connected to Supabase and loaded data!")
st.dataframe(data.head()) # Display a small sample of the data
elif supabase is None:
st.error("Failed to initialize Supabase client. Check environment variables in Settings.")
else:
st.info("Attempted to load data. Check for any error messages above.")