Spaces:
Runtime error
Runtime error
Commit
·
e4d11a3
1
Parent(s):
df4791f
Subindo Assistente Médico com Docker e Ollama
Browse files- Dockerfile +10 -15
- requirements.txt +8 -3
- src/app.py +96 -0
- src/core_agent.py +97 -0
- src/obter_endereco.py +13 -0
- src/scrapping_especialistas.py +56 -0
- src/streamlit_app.py +0 -40
- src/vector.py +45 -0
Dockerfile
CHANGED
|
@@ -1,21 +1,16 @@
|
|
| 1 |
-
FROM python:3.
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
build-essential \
|
| 7 |
-
curl \
|
| 8 |
-
software-properties-common \
|
| 9 |
-
git \
|
| 10 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
|
| 12 |
-
|
| 13 |
-
COPY src/ ./src/
|
| 14 |
|
| 15 |
-
|
| 16 |
|
| 17 |
-
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
|
| 21 |
-
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
|
| 3 |
+
# Instalações básicas e Ollama
|
| 4 |
+
RUN apt-get update && apt-get install -y curl git && \
|
| 5 |
+
curl -fsSL https://ollama.com/install.sh | sh
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
WORKDIR /app
|
|
|
|
| 8 |
|
| 9 |
+
COPY . /app
|
| 10 |
|
| 11 |
+
RUN pip install --upgrade pip
|
| 12 |
+
RUN pip install -r requirements.txt
|
| 13 |
|
| 14 |
+
EXPOSE 7860
|
| 15 |
|
| 16 |
+
CMD ["streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0"]
|
requirements.txt
CHANGED
|
@@ -1,3 +1,8 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
langchain
|
| 2 |
+
langchain-ollama
|
| 3 |
+
langchain_community
|
| 4 |
+
langchain_chroma
|
| 5 |
+
datasets
|
| 6 |
+
streamlit
|
| 7 |
+
bs4
|
| 8 |
+
lxml
|
src/app.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from core_agent import chat_with_history, chat_especialista_with_history
|
| 3 |
+
from vector import buscar_contexto
|
| 4 |
+
from scrapping_especialistas import retornar_json
|
| 5 |
+
from obter_endereco import obter_endereco
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
st.set_page_config(page_title="Assistente Médico", page_icon="🩺")
|
| 10 |
+
st.title("Assistente Médico com IA")
|
| 11 |
+
|
| 12 |
+
if "session_id" not in st.session_state:
|
| 13 |
+
st.session_state.session_id = "sessao_default"
|
| 14 |
+
|
| 15 |
+
if "messages_sintomas" not in st.session_state:
|
| 16 |
+
st.session_state.messages_sintomas = []
|
| 17 |
+
|
| 18 |
+
if "messages_especialistas" not in st.session_state:
|
| 19 |
+
st.session_state.messages_especialistas = []
|
| 20 |
+
|
| 21 |
+
modo = st.radio("Escolha o tipo de assistência:", ["🩺 Sintomas", "👨⚕️ Especialistas"])
|
| 22 |
+
|
| 23 |
+
if modo == "🩺 Sintomas":
|
| 24 |
+
for msg in st.session_state.messages_sintomas:
|
| 25 |
+
with st.chat_message(msg["role"]):
|
| 26 |
+
st.markdown(msg["content"])
|
| 27 |
+
|
| 28 |
+
user_input = st.chat_input("Descreva seus sintomas aqui...")
|
| 29 |
+
|
| 30 |
+
if user_input:
|
| 31 |
+
st.session_state.messages_sintomas.append({"role": "user", "content": user_input})
|
| 32 |
+
with st.chat_message("user"):
|
| 33 |
+
st.markdown(user_input)
|
| 34 |
+
|
| 35 |
+
contexto = buscar_contexto(user_input)
|
| 36 |
+
|
| 37 |
+
resposta = chat_with_history.invoke(
|
| 38 |
+
{
|
| 39 |
+
"question": user_input,
|
| 40 |
+
"context": contexto,
|
| 41 |
+
},
|
| 42 |
+
config={"configurable": {"session_id": st.session_state.session_id + "_sintomas"}}
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
st.session_state.messages_sintomas.append({"role": "assistant", "content": resposta})
|
| 46 |
+
with st.chat_message("assistant"):
|
| 47 |
+
st.markdown(resposta)
|
| 48 |
+
|
| 49 |
+
if modo == "👨⚕️ Especialistas":
|
| 50 |
+
especialidade = st.selectbox("Escolha a especialidade:", [
|
| 51 |
+
"pediatras", "cardiologistas", "dermatologistas", "neurologistas", "ginecologistas"
|
| 52 |
+
])
|
| 53 |
+
|
| 54 |
+
cep = st.text_input("Digite seu CEP (formato 00000-000)", max_chars=9, placeholder="00000-000")
|
| 55 |
+
|
| 56 |
+
quantidade = st.slider("Quantidade de especialistas a retornar", min_value=1, max_value=10, value=5)
|
| 57 |
+
|
| 58 |
+
botao_consultar = st.button("Consultar Especialistas")
|
| 59 |
+
|
| 60 |
+
if botao_consultar:
|
| 61 |
+
cep_formatado = re.sub(r"[^0-9]", "", cep)
|
| 62 |
+
if len(cep_formatado) != 8:
|
| 63 |
+
st.warning("CEP inválido. Use o formato 00000-000.")
|
| 64 |
+
else:
|
| 65 |
+
cep_formatado = cep_formatado[:5] + '-' + cep_formatado[5:]
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
endereco = obter_endereco(cep_formatado)
|
| 69 |
+
cidade = endereco.get("city", "").lower()
|
| 70 |
+
estado = endereco.get("state", "").lower()
|
| 71 |
+
|
| 72 |
+
st.info(f"🔍 Buscando especialistas em {especialidade} na região de {cidade.upper()} - {estado.upper()}...")
|
| 73 |
+
|
| 74 |
+
dados_especialistas = retornar_json(especialidade, cidade, estado)
|
| 75 |
+
|
| 76 |
+
if dados_especialistas:
|
| 77 |
+
st.success(f"{len(dados_especialistas)} especialistas encontrados.")
|
| 78 |
+
|
| 79 |
+
# Exibe apenas a quantidade solicitada
|
| 80 |
+
for i,especialista in enumerate(dados_especialistas[:quantidade]):
|
| 81 |
+
st.markdown(f"""
|
| 82 |
+
{i + 1}. **Nome:** {especialista.get('name', 'Não informado')}
|
| 83 |
+
- Rua: {especialista.get('rua', 'Não informado')}
|
| 84 |
+
- Bairro: {especialista.get('bairro', 'Não informado')}
|
| 85 |
+
- Cidade: {especialista.get('cidade', 'Não informado')}
|
| 86 |
+
- Estado: {especialista.get('estado', 'Não informado')}
|
| 87 |
+
- Especialidades: {', '.join(especialista.get('especialidades', [])) if especialista.get('especialidades') else 'Não informado'}
|
| 88 |
+
- Convênios: {', '.join(especialista.get('convenios', [])) if especialista.get('convenios') else 'Não informado'}
|
| 89 |
+
- Nota Total: {especialista.get('nota_total', 'Não informado')}
|
| 90 |
+
""")
|
| 91 |
+
|
| 92 |
+
else:
|
| 93 |
+
st.warning("Nenhum especialista encontrado para a região e especialidade informada.")
|
| 94 |
+
|
| 95 |
+
except Exception as e:
|
| 96 |
+
st.error(f"Ocorreu um erro ao buscar os especialistas: {e}")
|
src/core_agent.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_ollama.llms import OllamaLLM
|
| 2 |
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 3 |
+
from langchain_core.chat_history import BaseChatMessageHistory
|
| 4 |
+
from langchain_community.chat_message_histories import ChatMessageHistory
|
| 5 |
+
from langchain_core.runnables.history import RunnableWithMessageHistory
|
| 6 |
+
from vector import buscar_contexto
|
| 7 |
+
import streamlit as st
|
| 8 |
+
|
| 9 |
+
llm = OllamaLLM(model="llama3.2", temperature=0.7)
|
| 10 |
+
|
| 11 |
+
template = """
|
| 12 |
+
Você é um assistente de IA especializado em ajudar pacientes com informações sobre doenças, sintomas e tratamentos.
|
| 13 |
+
Você deve fornecer informações precisas e úteis, mas lembre-se de que não substituir o aconselhamento médico profissional.
|
| 14 |
+
Antes de responder, pergunte ao usuario quantos dias ele está sentindo os sintomas.
|
| 15 |
+
Sempre incentive os usuários a consultar um médico para diagnósticos e tratamentos adequados.
|
| 16 |
+
Quero que apenas envie as possiveis causas dos sintomas, e pergunte ao usuario se ele gostaria de saber mais sobre formas de tratamento ou prevenção.
|
| 17 |
+
|
| 18 |
+
Contexto:
|
| 19 |
+
{context}
|
| 20 |
+
|
| 21 |
+
Histórico:
|
| 22 |
+
{history}
|
| 23 |
+
|
| 24 |
+
Pergunta:
|
| 25 |
+
{question}
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
template_especialista = """
|
| 29 |
+
Você é um assistente de IA que ajuda usuários a encontrar especialistas médicos com base em dados fornecidos.
|
| 30 |
+
|
| 31 |
+
Seu objetivo é:
|
| 32 |
+
|
| 33 |
+
- listar **somente os nomes e endereços** dos especialistas disponíveis, **sem inventar dados**.
|
| 34 |
+
- Caso o usuário solicite outras informações específicas (como convênios ou nota), forneça **apenas o que ele pediu, com base no contexto**.
|
| 35 |
+
- Se a informação não estiver no contexto, responda exatamente: **"Não tenho acesso a essa informação."**
|
| 36 |
+
|
| 37 |
+
Sempre responda se a pergunta for sobre: nota, nota total, convênios, especialidades, estado, cidade, bairro, rua.
|
| 38 |
+
Apenas envie a informação sobre o médico ou médicos da pergunta.
|
| 39 |
+
Apenas envie a lista na primeira vez, caso haja uma outra pergunta, responda só o que for solicitado, sem repetir a lista.
|
| 40 |
+
|
| 41 |
+
Nunca diga que não tem acesso à localização, pois os dados foram fornecidos no contexto.
|
| 42 |
+
Nunca invente ou crie dados.
|
| 43 |
+
|
| 44 |
+
Formato da resposta, mantenha exatamente:
|
| 45 |
+
|
| 46 |
+
1. Nome: 'name'
|
| 47 |
+
- Rua: 'rua'
|
| 48 |
+
- bairro: 'bairro'
|
| 49 |
+
- Cidade: 'cidade'
|
| 50 |
+
- Especialidades: 'especialidades'
|
| 51 |
+
|
| 52 |
+
Contexto:
|
| 53 |
+
{context}
|
| 54 |
+
|
| 55 |
+
Histórico:
|
| 56 |
+
{history}
|
| 57 |
+
|
| 58 |
+
Pergunta:
|
| 59 |
+
{question}
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 63 |
+
("system", template),
|
| 64 |
+
MessagesPlaceholder(variable_name="history"),
|
| 65 |
+
("human", "{question}"),
|
| 66 |
+
])
|
| 67 |
+
|
| 68 |
+
chain = prompt | llm
|
| 69 |
+
|
| 70 |
+
prompt_especialista = ChatPromptTemplate.from_messages([
|
| 71 |
+
("system", template_especialista),
|
| 72 |
+
MessagesPlaceholder(variable_name="history"),
|
| 73 |
+
("human", "{question}"),
|
| 74 |
+
])
|
| 75 |
+
|
| 76 |
+
chain_especialista = prompt_especialista | llm
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
store = {}
|
| 80 |
+
|
| 81 |
+
def get_session_history(session_id):
|
| 82 |
+
if session_id not in store:
|
| 83 |
+
store[session_id] = ChatMessageHistory()
|
| 84 |
+
return store[session_id]
|
| 85 |
+
|
| 86 |
+
chat_with_history = RunnableWithMessageHistory(
|
| 87 |
+
chain,
|
| 88 |
+
get_session_history,
|
| 89 |
+
input_messages_key="question",
|
| 90 |
+
history_messages_key="history"
|
| 91 |
+
)
|
| 92 |
+
chat_especialista_with_history = RunnableWithMessageHistory(
|
| 93 |
+
chain_especialista,
|
| 94 |
+
get_session_history,
|
| 95 |
+
input_messages_key="question",
|
| 96 |
+
history_messages_key="history"
|
| 97 |
+
)
|
src/obter_endereco.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
def formatar_cep(cep):
|
| 6 |
+
return re.sub(r"[^0-9]", "", cep).zfill(8)[:5] + "-" + re.sub(r"[^0-9]", "", cep).zfill(8)[5:]
|
| 7 |
+
|
| 8 |
+
def obter_endereco(cep):
|
| 9 |
+
url = f"https://cdn.apicep.com/file/apicep/{cep}.json"
|
| 10 |
+
resposta = requests.get(url)
|
| 11 |
+
data = resposta.json()
|
| 12 |
+
|
| 13 |
+
return data
|
src/scrapping_especialistas.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
from lxml import html
|
| 3 |
+
|
| 4 |
+
def obter_links(especialidade, cidade, estado):
|
| 5 |
+
|
| 6 |
+
url=f"https://www.boaconsulta.com/especialistas/{especialidade}/{cidade}-{estado}/"
|
| 7 |
+
headers = {
|
| 8 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
|
| 9 |
+
"Accept-Language": "pt-BR,pt;q=0.9",
|
| 10 |
+
}
|
| 11 |
+
page = requests.get(url=url, headers=headers)
|
| 12 |
+
tree = html.fromstring(page.content)
|
| 13 |
+
list = tree.xpath("//a[@id='search-item-name-profile-link']/@href")
|
| 14 |
+
return list
|
| 15 |
+
|
| 16 |
+
def obter_info_especialista(link):
|
| 17 |
+
url = "https://www.boaconsulta.com" + link
|
| 18 |
+
headers = {
|
| 19 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
|
| 20 |
+
"Accept-Language": "pt-BR,pt;q=0.9",
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
page = requests.get(url=url, headers=headers)
|
| 24 |
+
tree = html.fromstring(page.content)
|
| 25 |
+
|
| 26 |
+
name = tree.xpath("//h1[@itemprop='name']/text()")
|
| 27 |
+
rua = tree.xpath("//span[@itemprop='streetAddress']/text()")
|
| 28 |
+
bairro = tree.xpath("//h3[contains(@class,'speakable-locations-name')]/text()")
|
| 29 |
+
cidade = tree.xpath("//span[@itemprop='addressLocality']/text()")
|
| 30 |
+
estado = tree.xpath("//span[@itemprop='addressRegion']/text()")
|
| 31 |
+
especialidades = tree.xpath("//h2[@class='speakable-locations-specialties']//button/text()")
|
| 32 |
+
convenios = tree.xpath("//a[contains(@href, 'agendamento/convenio')]/text()")
|
| 33 |
+
nota_total = tree.xpath("//div[contains(@class,'speakable-locations-reviews')]//p[contains(@class,'text-4xl')]/text()")
|
| 34 |
+
|
| 35 |
+
valores = {
|
| 36 |
+
"name": name[0].strip() if name else "",
|
| 37 |
+
"rua": rua[0].strip() if rua else "",
|
| 38 |
+
"bairro": bairro[0].strip() if bairro else "",
|
| 39 |
+
"cidade": cidade[0].strip() if cidade else "",
|
| 40 |
+
"estado": estado[0].strip() if estado else "",
|
| 41 |
+
"especialidades": [i.strip() for i in especialidades] if especialidades else [],
|
| 42 |
+
"convenios": [i.strip() for i in convenios] if convenios else [],
|
| 43 |
+
"nota_total": nota_total[0].strip() if nota_total else ""
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
return valores
|
| 47 |
+
|
| 48 |
+
def retornar_json(especialista, cidade, estado):
|
| 49 |
+
links = obter_links(especialista,cidade,estado)
|
| 50 |
+
|
| 51 |
+
lista = []
|
| 52 |
+
for i in links:
|
| 53 |
+
retorno = obter_info_especialista(i)
|
| 54 |
+
lista.append(retorno)
|
| 55 |
+
|
| 56 |
+
return lista
|
src/streamlit_app.py
DELETED
|
@@ -1,40 +0,0 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
-
import streamlit as st
|
| 5 |
-
|
| 6 |
-
"""
|
| 7 |
-
# Welcome to Streamlit!
|
| 8 |
-
|
| 9 |
-
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
|
| 10 |
-
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
|
| 11 |
-
forums](https://discuss.streamlit.io).
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/vector.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datasets import load_dataset
|
| 2 |
+
from langchain_ollama import OllamaEmbeddings
|
| 3 |
+
from langchain_chroma import Chroma
|
| 4 |
+
from langchain_core.documents import Document
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
def buscar_contexto(pergunta, k=5):
|
| 8 |
+
docs = vector_store.similarity_search(pergunta, k=k)
|
| 9 |
+
return "\n".join([doc.page_content for doc in docs])
|
| 10 |
+
|
| 11 |
+
embeddings = OllamaEmbeddings(model="mxbai-embed-large")
|
| 12 |
+
dataset = load_dataset("qiaojin/PubMedQA", "pqa_labeled")
|
| 13 |
+
|
| 14 |
+
db_location = "./chroma_db"
|
| 15 |
+
|
| 16 |
+
add_documents = not os.path.exists(db_location)
|
| 17 |
+
|
| 18 |
+
documents = []
|
| 19 |
+
if add_documents:
|
| 20 |
+
|
| 21 |
+
for row in dataset["train"]:
|
| 22 |
+
question = row["question"]
|
| 23 |
+
context_chunk = row["context"]["contexts"]
|
| 24 |
+
|
| 25 |
+
full_context = "\n".join(context_chunk)
|
| 26 |
+
answer = row["long_answer"]
|
| 27 |
+
|
| 28 |
+
doc = Document(
|
| 29 |
+
page_content=f"Pergunta: {question}\nContexto: {full_context}\nResposta: {answer}",
|
| 30 |
+
metadata = {"pubid": row["pubid"], "final_decision": row["final_decision"], "meshes": row["context"]["meshes"],"labels": row["context"]["labels"]}
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
documents.append(doc)
|
| 34 |
+
|
| 35 |
+
vector_store = Chroma.from_documents(
|
| 36 |
+
documents=documents,
|
| 37 |
+
embedding=embeddings,
|
| 38 |
+
persist_directory=db_location
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
else:
|
| 42 |
+
vector_store = Chroma(
|
| 43 |
+
embedding_function=embeddings,
|
| 44 |
+
persist_directory=db_location
|
| 45 |
+
)
|