from fasthtml.common import * from llama_index.core import SimpleDirectoryReader, Document,VectorStoreIndex from llama_index.core.node_parser import SimpleNodeParser from llama_index.core.text_splitter import TokenTextSplitter from llama_index.vector_stores.chroma import ChromaVectorStore from llama_index.core.storage.storage_context import StorageContext from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core import SummaryIndex from llama_index.llms.groq import Groq as GroqLLamaIndex from chromadb import PersistentClient from llama_index.core import Settings #from llama_index.embeddings.huggingface_api import ( # HuggingFaceInferenceAPIEmbedding, #) import chromadb import os import threading import time from llama_index.core.memory import ChatMemoryBuffer import json #from llama_index.llms.ollama import Ollama from llama_index.core.base.response.schema import Response from groq import Groq #import shutil pwd = os.getcwd() def extractConfig(nameModel="SystemData",relPath=os.path.join(pwd,"conf/experiment_config.json"),dataOut="keyantrophics"): configPath=os.path.join(os.getcwd(),relPath) with open(configPath, 'r', encoding='utf-8') as file: config = json.load(file)[nameModel] Output= config[dataOut] return Output keygroq=extractConfig(nameModel="SystemData",dataOut="keygroq") client = Groq(api_key=keygroq) os.environ["GROQ_API_KEY"] = keygroq llm_70b = GroqLLamaIndex(model="llama-3.1-70b-versatile")#llm_70b# llm_localLlamma = llm_70b#Ollama(model="llama3.2") memory = ChatMemoryBuffer.from_defaults(token_limit=3900) model_emb="sentence-transformers/multi-qa-mpnet-base-dot-v1" Settings.llm = llm_localLlamma gridlink = Link(rel="stylesheet", href="https://cdnjs.cloudflare.com/ajax/libs/flexboxgrid/6.3.1/flexboxgrid.min.css", type="text/css") colorpico=Link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.colors.min.css") app= FastHTML(hdrs=(picolink, gridlink,colorpico)) def listUsers(): with os.scandir("static") as files: subdir = [file.name for file in files if file.is_dir()] return subdir def menuusers(users): T=[] n=0 for user in users: T.append(Option(user, value=str(user)) ) return Form( H3("Seleccionar usuario",cls="col-xs-3"), Select(*T,name="user",cls="col-xs-3"), Button("Submit",type="submit",id="buttonMenuuser",cls="col-xs-6"), hx_post="/checkInfoSources",hx_swap="innerHTML",hx_target="#files" ,id="menuuser",cls="row middle-xs") @app.post("/checkInfoSources") def checkInfoSources(user:str): global userdata with os.scandir("static/"+user) as files: subdir = [Option(file.name,value="static/"+user+"/"+file.name) for file in files if (file.is_dir() and file.name!="chroma_db") ] userdata=user print("Cambio",userdata) return Form( H3("Grupos de archivos",cls="col-xs-3"), Select( *subdir,name="data",cls="col-xs-3"), Input(id="name-db", name="collection", placeholder="Enter a collection name",cls="col-xs-4"), Button("Submit",type="submit",cls="col-xs-2"), hx_post="/createCollection",hx_swap="innerHTML",hx_target="#status" ,cls="row middle-xs") def create_or_load_db(path="./chroma_db",collection="init",Nodes=None,modelT=model_emb): embed_model = HuggingFaceEmbedding(model_name=modelT) #embed_model = HuggingFaceInferenceAPIEmbedding( #model_name="BAAI/bge-small-en-v1.5", #token="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", # Optional #) db = chromadb.PersistentClient(path=path) chroma_collection = db.get_or_create_collection(collection) vector_store = ChromaVectorStore(chroma_collection=chroma_collection) storage_context = StorageContext.from_defaults(vector_store=vector_store) if Nodes: index = VectorStoreIndex( Nodes, storage_context=storage_context, embed_model=embed_model ) else: index = VectorStoreIndex.from_vector_store( vector_store, embed_model=embed_model, ) return index def post_process_documents(documents): processed_documents = [] n=0 print(len(documents)) for doc in documents: # 1. Text cleaning n+=1 print(n) text = doc.text.lower() # Convert to lowercase # 2. Remove stopwords stop_words = set("adssss") tokens = text.split(" ") filtered_text = ' '.join([word for word in tokens if word.lower() not in stop_words]) # 3. Custom metadata extraction (example) metadata = doc.metadata.copy() metadata['word_count'] = len(tokens) # 4. Create a new document with processed text and updated metadata processed_doc = Document(text=filtered_text, metadata=metadata) processed_documents.append(processed_doc) node_parser = SimpleNodeParser(chunk_size=360, chunk_overlap=20) nodes = node_parser.get_nodes_from_documents(processed_documents) return nodes @app.get("/listmodelactives") def listmodelactives(): try: print(userdata) except: print("cambio") return Div(id="options",hx_target="this",hx_swap="outerHTML",hx_get="/listmodelactives",hx_trigger="click from:#buttonMenuuser") db = chromadb.PersistentClient(path="static/"+userdata+"/chroma_db") files= db.list_collections() collecs = [Option(file.name, value=file.name)for file in files] return Form( Select( *collecs,name="data",cls="col-xs-6"), Button("Submit",type="submit",cls="col-xs-6"), hx_post="/loadCollection",hx_swap="innerHTML",hx_target="#Infomodel") @app.post("/loadCollection") def loadCollection(data:str): global index index=create_or_load_db(path="static/"+userdata+"/chroma_db",collection=data,modelT=model_emb) return P("El usuario %s colleccion %s"%(userdata,data)) @app.post("/queryprompt") def queryPrompt(question:str): #index=load_create_db(collection="my_collection") query_engine = index.as_query_engine(similarity_top_k=15,vector_store_query_mode="default",response_mode="tree_summarize") summary_prompt = ( "Por favor, genera un resumen completo y detallado del material dado. " "Incluye los principales temas, argumentos y conclusiones. " "Estructura el resumen de manera coherente y organizada." ) tematic_prompt =( "Por favor, genera un texto donde se menciones la tematica que trata el material dado. " "Incluye una tematica general y un indice por temas tratados " "Estructura el texto de manera coherente y organizada." ) issues_prompt =( "Por favor, genera un texto donde se menciones tomando en cuenta el material y el contenido de manera detallada que mejoras podrias realizar al material incluyendo nuevos datos o corrigiendo la informacion proporcionada" "Esta mejora hazla pensado paso a paso y de manera muy cuidadosa, tienes que dar ejemplos del materiar o referenciar directamante el texto a mejorar mencioando la causa de la mejora" "Estructura el texto de manera coherente y organizada." ) Question_prompt =( "Por favor, genera un texto donde indiques preguntas sobre el material que cuando sean respondidas capturen el punto central y puntos importantes del texto" "Estas preguntas hazla pensado paso a paso y de manera muy cuidadosa." "Estructura el texto de manera coherente y organizada." ) response = query_engine.query(summary_prompt) response2 = query_engine.query(tematic_prompt) response3 = query_engine.query(issues_prompt) response4 = query_engine.query(Question_prompt) Output="