Spaces:
Sleeping

Engenios / app.py
Samuelandrade's picture
Update app.py
ade8e5e verified
Raw History Blame Contribute Delete
8.71 kB
import os
import uuid
import re
from typing import List
import gradio as gr
from openai import OpenAI
from qdrant_client import QdrantClient
from qdrant_client.models import PointStruct, VectorParams, Distance, OptimizersConfigDiff
from qdrant_client.http.models import Filter, FieldCondition, MatchValue
from docx import Document
import pandas as pd
import pdfplumber
# ============================================================
# 1. CONFIGURAÇÃO
# ============================================================
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
QDRANT_URL = os.getenv("QDRANT_URL")
QDRANT_API_KEY = os.getenv("QDRANT_API_KEY")
if not OPENAI_API_KEY or not QDRANT_URL or not QDRANT_API_KEY:
raise RuntimeError("Configure OPENAI_API_KEY, QDRANT_URL e QDRANT_API_KEY.")
client_oa = OpenAI(api_key=OPENAI_API_KEY)
client_qd = QdrantClient(
url=QDRANT_URL,
api_key=QDRANT_API_KEY,
timeout=20
)
COLLECTION_NAME = "engenios_docs"
EMBED_MODEL = "text-embedding-3-large"
# ============================================================
# 2. EMBEDDINGS + CHUNKING
# ============================================================
def embed_text(text: str) -> List[float]:
"""Embedding moderno (OpenAI API 2025)"""
resp = client_oa.embeddings.create(
model=EMBED_MODEL,
input=text
)
return resp.data[0].embedding
def chunk_text(text: str, max_chars=1600):
text = text.replace("\r\n", "\n")
lines = text.split("\n")
chunks, buf = [], ""
for line in lines:
ln = line.strip()
if not ln:
continue
if len(buf) + len(ln) + 1 > max_chars:
chunks.append(buf.strip())
buf = ln
else:
buf += ("\n" + ln) if buf else ln
if buf.strip():
chunks.append(buf.strip())
return chunks
# ============================================================
# 3. EXTRAÇÃO DE ARQUIVOS
# ============================================================
def extract_docx(raw: bytes):
path = "/tmp/tmp.docx"
with open(path, "wb") as f:
f.write(raw)
doc = Document(path)
return "\n".join(p.text for p in doc.paragraphs)
def extract_xlsx(raw: bytes):
path = "/tmp/tmp.xlsx"
with open(path, "wb") as f:
f.write(raw)
excel = pd.ExcelFile(path)
out = []
for sheet in excel.sheet_names:
df = excel.parse(sheet).fillna("")
out.append(f"--- ABA: {sheet} ---")
for _, row in df.iterrows():
line = " | ".join(str(v).strip() for v in row.values if str(v).strip())
if line:
out.append(line)
return "\n".join(out)
def extract_pdf(raw: bytes):
path = "/tmp/tmp.pdf"
with open(path, "wb") as f:
f.write(raw)
text = ""
with pdfplumber.open(path) as pdf:
for p in pdf.pages:
text += (p.extract_text() or "") + "\n\n"
return text
def extract_text(file_obj):
# NO HUGGINGFACE + GRADIO 6, file_obj É UMA STRING (CAMINHO TEMPORÁRIO)
filepath = file_obj
name = filepath.lower()
with open(filepath, "rb") as f:
raw = f.read()
if name.endswith(".txt"):
try:
return raw.decode("utf-8"), "txt"
except:
return raw.decode("latin-1"), "txt"
if name.endswith(".docx"):
return extract_docx(raw), "docx"
if name.endswith(".xlsx"):
return extract_xlsx(raw), "xlsx"
if name.endswith(".pdf"):
return extract_pdf(raw), "pdf"
return "", "unsupported"
# ============================================================
# 4. METADADOS
# ============================================================
def detect_module(text: str):
t = text.lower()
if "usuario" in t or "usuário" in t:
return "usuarios"
if "plano" in t:
return "planos"
if "vistoria" in t or "checklist" in t:
return "vistoria"
if "agenda" in t:
return "agenda"
if "documento" in t:
return "documentos"
if "empreendimento" in t:
return "empreendimento"
return "geral"
def detect_type(chunk: str):
c = chunk.lower()
if "tela" in c:
return "tela"
if "tabela" in c:
return "tabela"
if re.search(r"rf\.\d", c):
return "requisito"
if re.search(r"rnf\.\d", c):
return "requisito_nfunc"
if "fluxo" in c:
return "fluxo"
return "geral"
# ============================================================
# 5. COLEÇÃO QDRANT
# ============================================================
def ensure_collection():
cols = client_qd.get_collections().collections
if COLLECTION_NAME in [c.name for c in cols]:
return
dim = len(embed_text("Teste para obter dimensão"))
client_qd.recreate_collection(
collection_name=COLLECTION_NAME,
vectors_config=VectorParams(size=dim, distance=Distance.COSINE),
optimizers_config=OptimizersConfigDiff(memmap_threshold=20000),
)
# ============================================================
# 6. INGESTÃO COMPLETA
# ============================================================
def ingest_file(fobj):
if not fobj:
return "Nenhum arquivo enviado."
text, tipo = extract_text(fobj)
if tipo == "unsupported":
return "Formato não suportado."
ensure_collection()
chunks = chunk_text(text)
points = []
for idx, ck in enumerate(chunks):
if not ck.strip():
continue
vector = embed_text(ck)
points.append(
PointStruct(
id=str(uuid.uuid4()),
vector=vector,
payload={
"texto": ck,
"origem": fobj.name,
"tipo_arquivo": tipo,
"modulo": detect_module(ck),
"tipo_conteudo": detect_type(ck),
"indice": idx
}
)
)
client_qd.upsert(collection_name=COLLECTION_NAME, points=points)
return f"{len(points)} trechos ingeridos de {fobj.name}."
def clear_collection():
try:
client_qd.delete_collection(COLLECTION_NAME)
except:
pass
ensure_collection()
return "Base limpa com sucesso."
# ============================================================
# 7. BUSCA RAG
# ============================================================
def build_filter(query: str):
q = query.lower()
must = []
for mod in ["usuarios", "planos", "vistoria", "agenda", "documentos", "empreendimento"]:
if mod[:-1] in q:
must.append(FieldCondition(key="modulo", match=MatchValue(mod)))
return Filter(must=must) if must else None
def search_rag(query: str):
vec = embed_text(query)
flt = build_filter(query)
res = client_qd.query_points(
collection_name=COLLECTION_NAME,
query=vec,
limit=12,
query_filter=flt,
with_payload=True
)
ctx = []
for p in res.points:
ctx.append(p.payload.get("texto", ""))
return "\n\n".join(ctx[:10])
def chat(history, message):
contexto = search_rag(message)
prompt = f"""
Contexto recuperado:
{contexto}
Pergunta:
{message}
Responda baseado APENAS no contexto acima.
"""
resp = client_oa.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": "Você é o assistente Engenios."},
{"role": "user", "content": prompt}
]
)
answer = resp.choices[0].message.content
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": answer})
return history, ""
# ============================================================
# 8. INTERFACE
# ============================================================
with gr.Blocks(title="Engenios RAG — Completo") as demo:
gr.Markdown("# 🧠 Engenios — RAG Completo")
with gr.Tab("Chat"):
chatbot = gr.Chatbot()
entrada = gr.Textbox(label="Pergunta")
limpar = gr.Button("Limpar")
entrada.submit(chat, [chatbot, entrada], [chatbot, entrada])
limpar.click(lambda: [], None, chatbot)
with gr.Tab("Ingestão"):
gr.Markdown("### Upload de arquivos (PDF, DOCX, XLSX, TXT)")
arquivo = gr.File()
btn_ing = gr.Button("Ingerir")
saida_ing = gr.Textbox()
btn_ing.click(ingest_file, arquivo, saida_ing)
gr.Markdown("---")
limpar_qdrant = gr.Button("Limpar Base")
saida_limpar = gr.Textbox()
limpar_qdrant.click(clear_collection, None, saida_limpar)
demo.launch()