File size: 3,175 Bytes
b090783
 
 
 
 
 
 
0a1d7fd
b090783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3be9773
 
 
 
 
 
 
b090783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3be9773
7b701bb
3be9773
 
 
 
d40dfec
3be9773
 
 
 
 
d40dfec
 
 
 
 
 
0c8a8d9
3be9773
 
 
 
 
 
 
 
b090783
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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