Spaces:
Sleeping
Sleeping
fschwartzer
commited on
Commit
•
2598bbd
1
Parent(s):
17a40a4
Update app.py
Browse files
app.py
CHANGED
@@ -2,6 +2,7 @@ import gradio as gr
|
|
2 |
import requests
|
3 |
import pandas as pd
|
4 |
from scipy import stats
|
|
|
5 |
|
6 |
import google.generativeai as genai
|
7 |
|
@@ -28,85 +29,59 @@ model = genai.GenerativeModel(model_name="gemini-pro",
|
|
28 |
generation_config=generation_config,
|
29 |
safety_settings=safety_settings)
|
30 |
|
31 |
-
def
|
32 |
prompt_parts = [
|
33 |
-
f"input: \"
|
34 |
"output: ",
|
35 |
f"input: {query}",
|
36 |
"output: ",
|
37 |
]
|
38 |
|
39 |
response = model.generate_content(prompt_parts)
|
40 |
-
|
41 |
-
|
42 |
-
def extract_refined_query(gemini_output):
|
43 |
-
"""
|
44 |
-
Parses the Gemini model's output to extract a refined query for Mercado Livre.
|
45 |
-
|
46 |
-
Args:
|
47 |
-
- gemini_output (str): The output text from the Gemini model.
|
48 |
-
|
49 |
-
Returns:
|
50 |
-
- str: A refined query term extracted from the Gemini output.
|
51 |
-
"""
|
52 |
-
# Placeholder for parsing logic. This should be replaced with actual parsing
|
53 |
-
# based on the structure of the Gemini model's output.
|
54 |
-
# For demonstration, let's assume the model's output is a descriptive text
|
55 |
-
# that includes keywords or phrases that can be used for a more focused search.
|
56 |
-
|
57 |
-
# Example parsing logic (simple and needs to be adapted):
|
58 |
-
# Assuming the output might contain phrases like "focus on [keyword] for best results"
|
59 |
-
# This is a very basic example and should be replaced with actual parsing logic.
|
60 |
-
refined_query = "default query" # Fallback query if parsing fails or finds no specific keywords
|
61 |
-
|
62 |
-
# Example: Search for a phrase indicating a refined query within the model's output
|
63 |
-
if "focus on" in gemini_output:
|
64 |
-
start_index = gemini_output.find("focus on") + len("focus on ")
|
65 |
-
end_index = gemini_output.find(" for best results", start_index)
|
66 |
-
refined_query = gemini_output[start_index:end_index] if end_index != -1 else gemini_output[start_index:start_index+20] # Extract the keyword or use a substring as a fallback
|
67 |
-
|
68 |
return refined_query
|
69 |
-
|
70 |
-
def fetch_data_to_dataframe(query, limit=50, source="mercadolibre"
|
71 |
if source == "mercadolibre":
|
72 |
BASE_URL = "https://api.mercadolibre.com/sites/MLB/search"
|
73 |
params = {'q': query, 'limit': limit}
|
74 |
response = requests.get(BASE_URL, params=params)
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
df = pd.DataFrame()
|
85 |
-
if not df.empty:
|
86 |
-
pass
|
87 |
|
88 |
-
|
|
|
|
|
|
|
|
|
89 |
|
90 |
def integrated_app(query):
|
91 |
-
|
92 |
-
refined_query =
|
93 |
-
|
|
|
|
|
|
|
94 |
if df.empty:
|
95 |
-
return "
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
return median_price, df
|
102 |
|
103 |
|
104 |
-
# Define the updated Gradio interface
|
105 |
iface = gr.Interface(fn=integrated_app,
|
106 |
inputs=gr.Textbox(label="Digite sua consulta"),
|
107 |
outputs=[gr.Textbox(label="Preço Mediano"), gr.Dataframe(label="Resultados da Pesquisa")],
|
108 |
title="Análise Integrada de Bens",
|
109 |
-
description="Esta aplicação
|
110 |
|
111 |
-
# Launch the interface
|
112 |
iface.launch()
|
|
|
2 |
import requests
|
3 |
import pandas as pd
|
4 |
from scipy import stats
|
5 |
+
from difflib import get_close_matches
|
6 |
|
7 |
import google.generativeai as genai
|
8 |
|
|
|
29 |
generation_config=generation_config,
|
30 |
safety_settings=safety_settings)
|
31 |
|
32 |
+
def interpretar_e_refinar_busca(query):
|
33 |
prompt_parts = [
|
34 |
+
f"input: \"Corrigir e refinar a busca: '{query}' para uma consulta mais precisa.\"",
|
35 |
"output: ",
|
36 |
f"input: {query}",
|
37 |
"output: ",
|
38 |
]
|
39 |
|
40 |
response = model.generate_content(prompt_parts)
|
41 |
+
refined_query = response.text.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
return refined_query
|
43 |
+
|
44 |
+
def fetch_data_to_dataframe(query, limit=50, source="mercadolibre"):
|
45 |
if source == "mercadolibre":
|
46 |
BASE_URL = "https://api.mercadolibre.com/sites/MLB/search"
|
47 |
params = {'q': query, 'limit': limit}
|
48 |
response = requests.get(BASE_URL, params=params)
|
49 |
+
if response.status_code == 200:
|
50 |
+
data = response.json()
|
51 |
+
if 'results' in data:
|
52 |
+
items = data['results']
|
53 |
+
df = pd.DataFrame(items)
|
54 |
+
df = df[['title', 'price', 'currency_id', 'condition', 'permalink']]
|
55 |
+
df.columns = ['Title', 'Price', 'Currency', 'Condition', 'Link']
|
56 |
+
return df
|
57 |
+
return pd.DataFrame()
|
|
|
|
|
|
|
58 |
|
59 |
+
def filtrar_itens_similares(df, termo_pesquisa, limite=5):
|
60 |
+
titulos = df['Title'].tolist()
|
61 |
+
titulos_similares = get_close_matches(termo_pesquisa, titulos, n=limite, cutoff=0.1)
|
62 |
+
df_filtrado = df[df['Title'].isin(titulos_similares)]
|
63 |
+
return df_filtrado
|
64 |
|
65 |
def integrated_app(query):
|
66 |
+
# Primeiro, use o GEMINI para interpretar e possivelmente corrigir/refinar a busca
|
67 |
+
refined_query = interpretar_e_refinar_busca(query)
|
68 |
+
|
69 |
+
# Depois, busque os dados no Mercado Livre usando a query refinada
|
70 |
+
df = fetch_data_to_dataframe(refined_query, 50, "mercadolibre")
|
71 |
+
|
72 |
if df.empty:
|
73 |
+
return "Nenhum dado encontrado. Tente uma consulta diferente.", pd.DataFrame()
|
74 |
+
|
75 |
+
# A partir daqui, você pode continuar com a filtragem por similaridade ou outra lógica de pós-processamento
|
76 |
+
# Por simplicidade, vamos retornar diretamente os resultados
|
77 |
+
median_price = df['Price'].median()
|
78 |
+
return f"Preço Mediano: {median_price}", df
|
|
|
79 |
|
80 |
|
|
|
81 |
iface = gr.Interface(fn=integrated_app,
|
82 |
inputs=gr.Textbox(label="Digite sua consulta"),
|
83 |
outputs=[gr.Textbox(label="Preço Mediano"), gr.Dataframe(label="Resultados da Pesquisa")],
|
84 |
title="Análise Integrada de Bens",
|
85 |
+
description="Esta aplicação busca dados no Mercado Livre e filtra para encontrar itens com nomes similares ao termo de pesquisa, oferecendo uma análise de preços e características desses itens.")
|
86 |
|
|
|
87 |
iface.launch()
|