Update app.py
Browse files
app.py
CHANGED
|
@@ -1,89 +1,119 @@
|
|
| 1 |
-
import os
|
| 2 |
import streamlit as st
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from llama_index.llms.gemini import Gemini
|
| 5 |
-
from llama_index.
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from llama_index.core.query_engine import RetrieverQueryEngine
|
| 9 |
-
from llama_index.core.retrievers import AutoMergingRetriever
|
| 10 |
-
from llama_index.core.indices.vector_store.retrievers import VectorIndexRetriever
|
| 11 |
-
from llama_index.vector_stores.chroma import ChromaVectorStore
|
| 12 |
-
|
| 13 |
-
import chromadb
|
| 14 |
-
|
| 15 |
from dotenv import load_dotenv
|
|
|
|
| 16 |
|
| 17 |
load_dotenv()
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
Settings.chunk_size = 1024 # Taille des chunks pour l'indexation
|
| 22 |
-
# Nombre de tokens générés par le LLM
|
| 23 |
-
|
| 24 |
-
# Fonction pour charger les données et créer l'index (optimisé pour éviter les rechargements inutiles)
|
| 25 |
-
@st.cache_resource
|
| 26 |
-
def load_data_and_create_index():
|
| 27 |
-
"""Charge les documents PDF et crée l'index vectoriel."""
|
| 28 |
-
documents = SimpleDirectoryReader("./data").load_data()
|
| 29 |
-
|
| 30 |
-
# Créer un pipeline d'ingestion avec extraction de titre et fenêtrage de phrases
|
| 31 |
-
node_parser = SentenceWindowNodeParser.from_defaults(
|
| 32 |
-
window_size=3,
|
| 33 |
-
window_metadata_key="window",
|
| 34 |
-
original_text_metadata_key="original_text",
|
| 35 |
-
)
|
| 36 |
-
|
| 37 |
-
text_splitter = node_parser.get_leaf_nodes_and_parent_nodes
|
| 38 |
-
extractors = [TitleExtractor(nodes=5)]
|
| 39 |
|
| 40 |
-
pipeline = IngestionPipeline(
|
| 41 |
-
transformations=[node_parser, *extractors]
|
| 42 |
-
)
|
| 43 |
-
|
| 44 |
-
# Indexer les documents
|
| 45 |
-
nodes = pipeline.run(documents=documents)
|
| 46 |
-
|
| 47 |
-
# Initialiser la base de données vectorielle (exemple avec Chroma)
|
| 48 |
-
db = chromadb.Client()
|
| 49 |
-
chroma_collection = db.get_or_create_collection("legal_docs")
|
| 50 |
-
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
|
| 51 |
-
|
| 52 |
-
# Créer l'index
|
| 53 |
-
index = VectorStoreIndex.from_documents(nodes, vector_store=vector_store)
|
| 54 |
-
return index
|
| 55 |
-
|
| 56 |
-
# Fonction pour effectuer la requête
|
| 57 |
-
def perform_query(query_str, index):
|
| 58 |
-
"""Effectue une requête sur l'index et renvoie la réponse."""
|
| 59 |
-
# Créer un AutoMergingRetriever
|
| 60 |
-
base_retriever = VectorIndexRetriever(
|
| 61 |
-
index=index,
|
| 62 |
-
similarity_top_k=8,
|
| 63 |
-
)
|
| 64 |
-
retriever = AutoMergingRetriever(base_retriever, index.storage_context)
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
|
| 69 |
-
|
| 70 |
-
return response
|
| 71 |
|
| 72 |
-
#
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
|
| 76 |
-
index
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
-
# Champ de saisie de la question
|
| 79 |
-
query_str = st.text_input("Posez votre question juridique ici :")
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
if query_str:
|
| 84 |
-
with st.spinner("Recherche en cours..."):
|
| 85 |
-
response = perform_query(query_str, index)
|
| 86 |
-
st.success("Réponse :")
|
| 87 |
-
st.write(response)
|
| 88 |
-
else:
|
| 89 |
-
st.error("Veuillez saisir une question.")
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
from llama_index.core import (
|
| 4 |
+
VectorStoreIndex,
|
| 5 |
+
SimpleDirectoryReader,
|
| 6 |
+
Settings,
|
| 7 |
+
)
|
| 8 |
+
from llama_index.core import PromptTemplate
|
| 9 |
from llama_index.llms.gemini import Gemini
|
| 10 |
+
from llama_index.embeddings.gemini import GeminiEmbedding
|
| 11 |
+
import logging
|
| 12 |
+
import google.generativeai as genai
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
from dotenv import load_dotenv
|
| 14 |
+
from pathlib import Path
|
| 15 |
|
| 16 |
load_dotenv()
|
| 17 |
|
| 18 |
+
# Set logging level
|
| 19 |
+
logging.basicConfig(level=logging.INFO)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
# Configure Gemini Pro
|
| 23 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
| 24 |
|
| 25 |
+
model_gemini_pro_vision = "gemini-pro-vision"
|
|
|
|
| 26 |
|
| 27 |
+
# Configure Gemini models
|
| 28 |
+
Settings.llm = Gemini(model=model_gemini_pro_vision,
|
| 29 |
+
api_key=os.getenv("GOOGLE_API_KEY"))
|
| 30 |
+
Settings.embed_model = GeminiEmbedding(
|
| 31 |
+
model_name="models/embedding-001",
|
| 32 |
+
api_key=os.getenv("GOOGLE_API_KEY")
|
| 33 |
+
)
|
| 34 |
|
| 35 |
+
def load_and_index_pdf(pdf_path):
|
| 36 |
+
"""Loads and index the pdf.
|
| 37 |
+
|
| 38 |
+
Args :
|
| 39 |
+
pdf_path (str) : The path to the pdf file
|
| 40 |
+
|
| 41 |
+
Returns :
|
| 42 |
+
index (llama_index.core.VectorStoreIndex): The vector index
|
| 43 |
+
"""
|
| 44 |
+
try:
|
| 45 |
+
logging.info(f"Loading PDF document from: {pdf_path}")
|
| 46 |
+
documents = SimpleDirectoryReader(input_files=[pdf_path]).load_data()
|
| 47 |
+
if documents:
|
| 48 |
+
logging.info("Creating vector store index")
|
| 49 |
+
index = VectorStoreIndex.from_documents(documents)
|
| 50 |
+
return index
|
| 51 |
+
else:
|
| 52 |
+
logging.warning("No documents found in the PDF")
|
| 53 |
+
return None
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logging.error(f"Error loading and indexing PDF: {e}")
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
def translate_text(french_text, index):
|
| 59 |
+
"""Translates french text to Yipunu.
|
| 60 |
+
|
| 61 |
+
Args :
|
| 62 |
+
french_text (str): The french text to translate.
|
| 63 |
+
index (llama_index.core.VectorStoreIndex): The vector index.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
(str): The yipunu translation or an error message.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
logging.info(f"Initiating translation of: {french_text}")
|
| 71 |
+
|
| 72 |
+
template = (
|
| 73 |
+
"Tu es un excellent traducteur du français vers le yipunu. Tu traduis le texte sans donner d'explication. "
|
| 74 |
+
"Texte: {french_text} "
|
| 75 |
+
"Traduction:"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
prompt_template = PromptTemplate(template)
|
| 79 |
+
|
| 80 |
+
query_engine = index.as_query_engine(
|
| 81 |
+
text_qa_template=prompt_template
|
| 82 |
+
)
|
| 83 |
+
response = query_engine.query(french_text)
|
| 84 |
+
logging.info(f"Translation Result: {response.response}")
|
| 85 |
+
return response.response
|
| 86 |
+
except Exception as e:
|
| 87 |
+
logging.error(f"Error during translation: {e}")
|
| 88 |
+
return f"Error during translation: {str(e)}"
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def main():
|
| 92 |
+
"""Main function for streamlit app."""
|
| 93 |
+
|
| 94 |
+
st.title("French to Yipunu Translation App")
|
| 95 |
+
|
| 96 |
+
# PDF File Upload
|
| 97 |
+
uploaded_file = st.file_uploader("Upload a PDF file containing the Punu grammar:", type="pdf")
|
| 98 |
+
|
| 99 |
+
if uploaded_file is not None:
|
| 100 |
+
# Save file to a temporary location
|
| 101 |
+
temp_file_path = Path("temp_file.pdf")
|
| 102 |
+
with open(temp_file_path, "wb") as f:
|
| 103 |
+
f.write(uploaded_file.read())
|
| 104 |
+
|
| 105 |
+
index = load_and_index_pdf(str(temp_file_path))
|
| 106 |
+
if index:
|
| 107 |
+
french_text = st.text_area("Enter French Text:", "Ni vosi yipunu")
|
| 108 |
+
if st.button("Translate"):
|
| 109 |
+
translation = translate_text(french_text, index)
|
| 110 |
+
st.success(f"Yipunu Translation: {translation}")
|
| 111 |
+
|
| 112 |
+
# Clean up temp files
|
| 113 |
+
os.remove(temp_file_path)
|
| 114 |
+
else:
|
| 115 |
+
st.info("Please upload a pdf containing the punu grammar.")
|
| 116 |
|
|
|
|
|
|
|
| 117 |
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|