Spaces:
Build error
Build error
Upload 2 files
Browse files- app.py +94 -23
- requirements.txt +0 -0
app.py
CHANGED
|
@@ -4,7 +4,9 @@ from geopy.distance import geodesic
|
|
| 4 |
import folium
|
| 5 |
from streamlit_folium import st_folium
|
| 6 |
from groq import Groq
|
| 7 |
-
from
|
|
|
|
|
|
|
| 8 |
|
| 9 |
client = Groq(
|
| 10 |
api_key="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",
|
|
@@ -15,11 +17,28 @@ promotions_df = pd.read_csv("promotions.csv")
|
|
| 15 |
|
| 16 |
# Função para obter a localização do usuário
|
| 17 |
def get_user_location():
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
# Função para encontrar promoções próximas
|
| 24 |
def find_nearby_promotions(user_latitude, user_longitude, radius=5):
|
| 25 |
nearby_promotions = []
|
|
@@ -31,6 +50,7 @@ def find_nearby_promotions(user_latitude, user_longitude, radius=5):
|
|
| 31 |
nearby_promotions.append(row)
|
| 32 |
return nearby_promotions
|
| 33 |
|
|
|
|
| 34 |
# Função para obter recomendações do LLM
|
| 35 |
def get_llm_recommendations(user_latitude, user_longitude, category, nearby_promotions):
|
| 36 |
# Formata as promoções próximas para o prompt do LLM
|
|
@@ -81,22 +101,57 @@ def create_map(user_latitude, user_longitude, nearby_promotions):
|
|
| 81 |
|
| 82 |
return promo_map
|
| 83 |
|
| 84 |
-
#
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
# Menu de opções
|
| 88 |
-
option = st.sidebar.selectbox("Selecione uma opção", ["Mapa", "Recomendação", "Adicionar Promoção"])
|
| 89 |
|
|
|
|
| 90 |
# Executa a função correspondente à opção selecionada
|
| 91 |
if option == "Mapa":
|
| 92 |
# Obtém a localização do usuário
|
| 93 |
-
user_latitude, user_longitude = get_user_location()
|
| 94 |
-
|
| 95 |
-
# Encontra promoções próximas
|
| 96 |
-
nearby_promotions = find_nearby_promotions(user_latitude, user_longitude)
|
| 97 |
-
|
| 98 |
# Cria o mapa interativo com Folium
|
| 99 |
-
promo_map = create_map(user_latitude, user_longitude, promotions_df)
|
| 100 |
|
| 101 |
# Exibe o mapa na interface Streamlit
|
| 102 |
st_data = st_folium(promo_map, width=725)
|
|
@@ -109,15 +164,11 @@ elif option == "Recomendação":
|
|
| 109 |
category = st.selectbox("Categoria", ["Eletrônicos", "Vestuário", "Alimentos", "Outros"])
|
| 110 |
|
| 111 |
# Encontra promoções próximas
|
| 112 |
-
nearby_promotions = find_nearby_promotions(user_latitude, user_longitude)
|
| 113 |
|
| 114 |
# Mostra promoções próximas
|
| 115 |
-
if nearby_promotions:
|
| 116 |
-
|
| 117 |
-
#for promotion in nearby_promotions:
|
| 118 |
-
# st.write(f"**{promotion['product']}** em **{promotion['store']}** ({promotion['discount']}% de desconto)")
|
| 119 |
-
# Obtém recomendações do LLM
|
| 120 |
-
recommendations = get_llm_recommendations(user_latitude, user_longitude, category, nearby_promotions)
|
| 121 |
st.subheader("Recomendações Personalizadas:")
|
| 122 |
st.write(recommendations)
|
| 123 |
|
|
@@ -126,21 +177,41 @@ elif option == "Recomendação":
|
|
| 126 |
|
| 127 |
|
| 128 |
elif option == "Adicionar Promoção":
|
| 129 |
-
user_latitude, user_longitude = get_user_location()
|
| 130 |
st.subheader("Adicionar Nova Promoção")
|
| 131 |
product = st.text_input("Produto")
|
| 132 |
store = st.text_input("Loja")
|
| 133 |
discount = st.number_input("Desconto (%)", min_value=0, max_value=100)
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
# Adiciona a nova promoção ao banco de dados
|
| 136 |
if st.button("Adicionar"):
|
| 137 |
new_promotion = {
|
| 138 |
"product": product,
|
| 139 |
"store": store,
|
| 140 |
"discount": discount,
|
| 141 |
-
"latitude":
|
| 142 |
-
"longitude":
|
|
|
|
| 143 |
}
|
| 144 |
promotions_df = pd.concat([promotions_df, pd.DataFrame([new_promotion])], ignore_index=True)
|
| 145 |
promotions_df.to_csv("promotions.csv", index=False)
|
| 146 |
st.success("Promoção adicionada com sucesso!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import folium
|
| 5 |
from streamlit_folium import st_folium
|
| 6 |
from groq import Groq
|
| 7 |
+
from streamlit_geolocation import streamlit_geolocation
|
| 8 |
+
from streamlit_js_eval import streamlit_js_eval, get_geolocation
|
| 9 |
+
import time
|
| 10 |
|
| 11 |
client = Groq(
|
| 12 |
api_key="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",
|
|
|
|
| 17 |
|
| 18 |
# Função para obter a localização do usuário
|
| 19 |
def get_user_location():
|
| 20 |
+
try:
|
| 21 |
+
location = get_geolocation()
|
| 22 |
+
|
| 23 |
+
time.sleep(6)
|
| 24 |
+
|
| 25 |
+
latitude = location['coords']['latitude']
|
| 26 |
+
longitude = location['coords']['longitude']
|
| 27 |
+
|
| 28 |
+
return latitude, longitude
|
| 29 |
+
except Exception as e:
|
| 30 |
+
time.sleep(6)
|
| 31 |
+
st.error(f"Aguarde um pouco...: {e}")
|
| 32 |
+
return None, None
|
| 33 |
|
| 34 |
|
| 35 |
+
# Função para encontrar promoções
|
| 36 |
+
def find_promotions():
|
| 37 |
+
promotions = []
|
| 38 |
+
for index, row in promotions_df.iterrows():
|
| 39 |
+
promotions.append(row)
|
| 40 |
+
return promotions
|
| 41 |
+
|
| 42 |
# Função para encontrar promoções próximas
|
| 43 |
def find_nearby_promotions(user_latitude, user_longitude, radius=5):
|
| 44 |
nearby_promotions = []
|
|
|
|
| 50 |
nearby_promotions.append(row)
|
| 51 |
return nearby_promotions
|
| 52 |
|
| 53 |
+
|
| 54 |
# Função para obter recomendações do LLM
|
| 55 |
def get_llm_recommendations(user_latitude, user_longitude, category, nearby_promotions):
|
| 56 |
# Formata as promoções próximas para o prompt do LLM
|
|
|
|
| 101 |
|
| 102 |
return promo_map
|
| 103 |
|
| 104 |
+
# Função para o chat com o LLM
|
| 105 |
+
def chat_with_llm(user_latitude, user_longitude, promotions):
|
| 106 |
+
# Inicia o chat
|
| 107 |
+
st.subheader("Chat com o Especialista em Promoções")
|
| 108 |
+
user_input = st.text_input("Digite sua pergunta:")
|
| 109 |
+
|
| 110 |
+
# Formata as promoções próximas para o prompt do LLM
|
| 111 |
+
promotions_str = "\n".join(
|
| 112 |
+
f"Promoção {i+1}: {row['product']} em {row['store']} cujo endereço é: {row['endereco']} ({row['discount']}% de desconto)"
|
| 113 |
+
for i, row in enumerate(promotions)
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# Processa a pergunta do usuário
|
| 117 |
+
if user_input:
|
| 118 |
+
# Cria o prompt para o LLM
|
| 119 |
+
prompt = f"""
|
| 120 |
+
Você é um especialista em recomendação de produtos baseado em promoções.
|
| 121 |
+
Promoções próximas:
|
| 122 |
+
{promotions_str}
|
| 123 |
+
Um usuário em ({user_latitude}, {user_longitude}) fez a seguinte pergunta:
|
| 124 |
+
{user_input}
|
| 125 |
+
|
| 126 |
+
Responda à pergunta do usuário de forma útil e informativa.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
chat_completion = client.chat.completions.create(
|
| 130 |
+
messages=[
|
| 131 |
+
{"role": "system", "content": "Você é especialista em recomendação de produtos baseado em promoções"},
|
| 132 |
+
{"role": "user", "content": prompt}
|
| 133 |
+
],
|
| 134 |
+
model="llama3-8b-8192",
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# Exibe a resposta do LLM
|
| 138 |
+
st.write(chat_completion.choices[0].message.content)
|
| 139 |
|
| 140 |
+
# Interface do Streamlit
|
| 141 |
+
st.title("OfertasBot")
|
| 142 |
+
st.write("O OfertasBot, tem o objetivo de se tornar o Waze das ofertas e promoções.")
|
| 143 |
+
st.write("O seu novo assistente pessoal para economizar em grande estilo! Com a inteligência do nosso chatbot, você receberá recomendações exclusivas de promoções e descontos em produtos que realmente interessam a você. Basta conversar com o OfertasBot e deixar que ele encontre as melhores ofertas em tempo real, de acordo com suas preferências e localização. Nunca foi tão fácil fazer compras inteligentes! Colabore com a comunidade adicionado ofertas.")
|
| 144 |
# Menu de opções
|
| 145 |
+
option = st.sidebar.selectbox("Selecione uma opção", ["Mapa", "Recomendação", "Adicionar Promoção", "Chat"])
|
| 146 |
|
| 147 |
+
st.title("Mapa de Ofertas")
|
| 148 |
# Executa a função correspondente à opção selecionada
|
| 149 |
if option == "Mapa":
|
| 150 |
# Obtém a localização do usuário
|
| 151 |
+
user_latitude, user_longitude = get_user_location()
|
| 152 |
+
|
|
|
|
|
|
|
|
|
|
| 153 |
# Cria o mapa interativo com Folium
|
| 154 |
+
promo_map = create_map(float(user_latitude), float(user_longitude), promotions_df)
|
| 155 |
|
| 156 |
# Exibe o mapa na interface Streamlit
|
| 157 |
st_data = st_folium(promo_map, width=725)
|
|
|
|
| 164 |
category = st.selectbox("Categoria", ["Eletrônicos", "Vestuário", "Alimentos", "Outros"])
|
| 165 |
|
| 166 |
# Encontra promoções próximas
|
| 167 |
+
nearby_promotions = find_nearby_promotions(float(user_latitude), float(user_longitude))
|
| 168 |
|
| 169 |
# Mostra promoções próximas
|
| 170 |
+
if nearby_promotions:
|
| 171 |
+
recommendations = get_llm_recommendations(float(user_latitude), float(user_longitude), category, nearby_promotions)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
st.subheader("Recomendações Personalizadas:")
|
| 173 |
st.write(recommendations)
|
| 174 |
|
|
|
|
| 177 |
|
| 178 |
|
| 179 |
elif option == "Adicionar Promoção":
|
| 180 |
+
#user_latitude, user_longitude = get_user_location()
|
| 181 |
st.subheader("Adicionar Nova Promoção")
|
| 182 |
product = st.text_input("Produto")
|
| 183 |
store = st.text_input("Loja")
|
| 184 |
discount = st.number_input("Desconto (%)", min_value=0, max_value=100)
|
| 185 |
|
| 186 |
+
st.write("Clique no botão para obter a localização:")
|
| 187 |
+
geolocator = streamlit_geolocation()
|
| 188 |
+
|
| 189 |
+
promotion_latitude = geolocator['latitude']
|
| 190 |
+
promotion_longitude = geolocator['longitude']
|
| 191 |
+
|
| 192 |
+
endereco = st.text_input("Forneça o Endereço algum ponto de referência")
|
| 193 |
+
|
| 194 |
# Adiciona a nova promoção ao banco de dados
|
| 195 |
if st.button("Adicionar"):
|
| 196 |
new_promotion = {
|
| 197 |
"product": product,
|
| 198 |
"store": store,
|
| 199 |
"discount": discount,
|
| 200 |
+
"latitude": float(promotion_latitude),
|
| 201 |
+
"longitude": float(promotion_longitude),
|
| 202 |
+
"endereco":endereco,
|
| 203 |
}
|
| 204 |
promotions_df = pd.concat([promotions_df, pd.DataFrame([new_promotion])], ignore_index=True)
|
| 205 |
promotions_df.to_csv("promotions.csv", index=False)
|
| 206 |
st.success("Promoção adicionada com sucesso!")
|
| 207 |
+
|
| 208 |
+
elif option == "Chat":
|
| 209 |
+
# Obtém a localização do usuário
|
| 210 |
+
#user_latitude, user_longitude = get_user_location()
|
| 211 |
+
# Inicia o chat com o LLM
|
| 212 |
+
user_latitude, user_longitude = get_user_location()
|
| 213 |
+
|
| 214 |
+
chat_with_llm(float(user_latitude), float(user_longitude),find_promotions())
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
|
requirements.txt
CHANGED
|
Binary files a/requirements.txt and b/requirements.txt differ
|
|
|