import streamlit as st import requests import pandas as pd def fetch_data(keyword, location, lang): url = f"https://google-keyword-insight1.p.rapidapi.com/keysuggest?keyword={keyword}&location={location}&lang={lang}" headers = { 'X-RapidAPI-Key': '63e53aa879mshac0f7ff04cc8922p1a89dbjsn96a2ea051ea7', 'X-RapidAPI-Host': 'google-keyword-insight1.p.rapidapi.com' } response = requests.get(url, headers=headers) if response.status_code == 200: return response.json() else: return [] def round_to_nearest_five_cents(value): if value == 0: return '0' rounded_value = round(value * 20) / 20 return '0.10' if rounded_value < 0.1 else f'{rounded_value:.2f}' def round_trend_to_percentage(value): return f'{round(value)} %' st.title('Búsqueda de Palabras Clave') keyword = st.text_input('Palabra clave:', placeholder='Ingrese la búsqueda', key='keyword') location = st.text_input('Ubicación:', value='ES', key='location') lang = st.text_input('Idioma:', value='es', key='lang') # Initialize session state variables if 'show_all' not in st.session_state: st.session_state.show_all = False if 'results' not in st.session_state: st.session_state.results = None if st.button('Buscar'): results = fetch_data(keyword, location, lang) if results: df = pd.DataFrame(results) df['Nivel de Competencia'] = df['competition_level'].map({ 'LOW': 'Baja', 'MEDIUM': 'Media', 'HIGH': 'Alta' }).fillna('-') df['Oferta Baja'] = df['low_bid'].apply(round_to_nearest_five_cents) df['Oferta Alta'] = df['high_bid'].apply(round_to_nearest_five_cents) df['Tendencia'] = df['trend'].apply(round_trend_to_percentage) df['Ads'] = df['low_bid'].apply(lambda x: 'Sí' if x > 0 else 'No') df = df[['text', 'volume', 'Nivel de Competencia', 'competition_index', 'Oferta Baja', 'Oferta Alta', 'Tendencia', 'Ads']] df.columns = ['Texto', 'Volumen', 'Nivel de Competencia', 'Índice de Competencia', 'Oferta Baja', 'Oferta Alta', 'Tendencia', 'Ads'] df.sort_values(by='Volumen', ascending=False, inplace=True) st.session_state.results = df st.session_state.show_all = False # Reset the view to default when new search is performed # Display results if available if st.session_state.results is not None: df = st.session_state.results rows_to_display = 20 if not st.session_state.show_all else len(df) st.table(df.head(rows_to_display)) col1, col2 = st.columns([1, 1]) with col1: if len(df) > 20: if st.button('Ver más'): st.session_state.show_all = not st.session_state.show_all # Reset button text after showing all if st.session_state.show_all: st.button('Ver menos') with col2: csv = df.to_csv(index=False) st.download_button( label="Descargar resultados como CSV", data=csv, file_name='resultados.csv', mime='text/csv', ) # Run the app using the command: streamlit run app.py