Upload folder using huggingface_hub
Browse files4 unmodified lines56789101193 unmodified lines1051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341354 unmodified lines14014114214314414514614714814915015115215315448 unmodified lines2032042052062072082092102112122132142152162172181 unmodified line22022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125216 unmodified lines26927027127227327427527627727827928028128228328428528628728828929029129241 unmodified lines33433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037148 unmodified lines4204214224234244254264274284 unmodified linesimport requestsfrom pypdf import PdfReaderimport gradio as grfrom neo4j import GraphDatabaseimport numpy as npload_dotenv(override=True)93 unmodified linesself.openai = OpenAI()self.name = "Alexandre Saadoun"# Initialize Neo4j connectionself.neo4j_driver = GraphDatabase.driver(os.getenv("NEO4J_URI", "bolt://localhost:7687"),auth=(os.getenv("NEO4J_USER", "neo4j"), os.getenv("NEO4J_PASSWORD", "password")))# Initialize RAG system - this will auto-load all files in me/self._setup_neo4j_schema()self._populate_initial_data()def _setup_neo4j_schema(self):"""Setup Neo4j schema for RAG"""with self.neo4j_driver.session() as session:# Create vector index for embeddingstry:session.run("""CREATE VECTOR INDEX knowledge_embeddings IF NOT EXISTSFOR (n:Knowledge) ON (n.embedding)OPTIONS {indexConfig: {`vector.dimensions`: 1536,`vector.similarity_function`: 'cosine'}}""")except Exception as e:print(f"Index might already exist: {e}")def _get_embedding(self, text):"""Get embedding for text using OpenAI"""4 unmodified linesreturn response.data[0].embeddingdef _populate_initial_data(self):"""Store initial knowledge in Neo4j"""with self.neo4j_driver.session() as session:# Check if data already existsresult = session.run("MATCH (n:Knowledge) RETURN count(n) as count")count = result.single()["count"]if count == 0: # Only populate if emptyprint("Auto-loading all files from me/ directory...")self._auto_load_me_directory()def _auto_load_me_directory(self):"""Automatically load and process all files in the me/ directory"""48 unmodified linesprint("Reloading me/ directory...")# Clear existing me/ contentwith self.neo4j_driver.session() as session:result = session.run("""MATCH (n:Knowledge)WHERE n.source STARTS WITH 'me_'DELETE nRETURN count(n) as deleted""")deleted = result.single()["deleted"]if deleted > 0:print(f"Cleared {deleted} existing files from me/")# Reload everythingself._auto_load_me_directory()1 unmodified linedef _search_knowledge(self, query, limit=3):"""Search for relevant knowledge using vector similarity"""query_embedding = self._get_embedding(query)with self.neo4j_driver.session() as session:result = session.run("""CALL db.index.vector.queryNodes('knowledge_embeddings', $limit, $query_embedding)YIELD node, scoreRETURN node.content as content, node.type as type, scoreORDER BY score DESC""", query_embedding=query_embedding, limit=limit)return [{"content": record["content"], "type": record["type"], "score": record["score"]}for record in result]def _store_new_knowledge(self, information, context=""):"""Store new information in Neo4j"""embedding = self._get_embedding(information)with self.neo4j_driver.session() as session:session.run("""CREATE (n:Knowledge {content: $content,type: 'conversation',context: $context,embedding: $embedding,timestamp: datetime()})""", content=information, context=context, embedding=embedding)def bulk_load_text_content(self, text_content, source_name="raw_text", chunk_size=800):"""16 unmodified linesprint(f"Created {len(chunks)} chunks")# Store each chunkwith self.neo4j_driver.session() as session:for i, chunk in enumerate(chunks):embedding = self._get_embedding(chunk)session.run("""CREATE (n:Knowledge {content: $content,type: 'text_content',source: $source,chunk_index: $chunk_index,embedding: $embedding,timestamp: datetime()})""",content=chunk,source=source_name,chunk_index=i,embedding=embedding)print(f"Loaded {len(chunks)} chunks from {source_name}")41 unmodified linesClear all or specific type of knowledge from the databaseArgs:knowledge_type: If specified, only delete nodes of this type"""with self.neo4j_driver.session() as session:if knowledge_type:result = session.run("MATCH (n:Knowledge {type: $type}) DELETE n RETURN count(n) as deleted",type=knowledge_type)else:result = session.run("MATCH (n:Knowledge) DELETE n RETURN count(n) as deleted")deleted_count = result.single()["deleted"]print(f"Deleted {deleted_count} knowledge nodes")def get_knowledge_stats(self):"""Get statistics about the knowledge base"""with self.neo4j_driver.session() as session:result = session.run("""MATCH (n:Knowledge)RETURN n.type as type, count(n) as countORDER BY count DESC""")stats = {}total = 0for record in result:stats[record["type"]] = record["count"]total += record["count"]print(f"Knowledge Base Stats (Total: {total} documents):")for doc_type, count in stats.items():print(f" {doc_type}: {count}")return statsdef handle_tool_call(self, tool_calls):results = []48 unmodified linesreturn response.choices[0].message.contentdef __del__(self):"""Close Neo4j connection"""if hasattr(self, 'neo4j_driver'):self.neo4j_driver.close()if __name__ == "__main__":4 unmodified lines56789101193 unmodified lines1051061071081091101111121131141151161171181191201211221231241254 unmodified lines13013113213313413513613713813914014114248 unmodified lines1911921931941951961971981992002012022032042052062071 unmodified line20921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925016 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029129229329441 unmodified lines33633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738848 unmodified lines4374384394404414424434444454 unmodified linesimport requestsfrom pypdf import PdfReaderimport gradio as grimport chromadbimport numpy as npload_dotenv(override=True)93 unmodified linesself.openai = OpenAI()self.name = "Alexandre Saadoun"# Initialize Chroma connectionself.chroma_client = chromadb.PersistentClient(path="./chroma_db")# Initialize RAG system - this will auto-load all files in me/self._setup_chroma_collection()self._populate_initial_data()def _setup_chroma_collection(self):"""Setup Chroma collection for RAG"""try:self.collection = self.chroma_client.get_collection(name="knowledge_base")print("✅ Loaded existing knowledge base")except:self.collection = self.chroma_client.create_collection(name="knowledge_base")print("✅ Created new knowledge base")def _get_embedding(self, text):"""Get embedding for text using OpenAI"""4 unmodified linesreturn response.data[0].embeddingdef _populate_initial_data(self):"""Store initial knowledge in Chroma"""# Check if data already existscount = self.collection.count()if count == 0: # Only populate if emptyprint("Auto-loading all files from me/ directory...")self._auto_load_me_directory()def _auto_load_me_directory(self):"""Automatically load and process all files in the me/ directory"""48 unmodified linesprint("Reloading me/ directory...")# Clear existing me/ contenttry:# Get all documents from me/ filesresults = self.collection.get(include=["metadatas"])me_ids = [results["ids"][i] for i, metadata in enumerate(results["metadatas"])if metadata.get("source", "").startswith("me_")]if me_ids:self.collection.delete(ids=me_ids)print(f"Cleared {len(me_ids)} existing files from me/")except Exception as e:print(f"Error clearing existing data: {e}")# Reload everythingself._auto_load_me_directory()1 unmodified linedef _search_knowledge(self, query, limit=3):"""Search for relevant knowledge using vector similarity"""try:results = self.collection.query(query_texts=[query],n_results=limit,include=["documents", "metadatas", "distances"])search_results = []if results["documents"] and results["documents"][0]:for i, doc in enumerate(results["documents"][0]):search_results.append({"content": doc,"type": results["metadatas"][0][i].get("type", "unknown") if results["metadatas"] else "unknown","score": 1 - results["distances"][0][i] if results["distances"] else 1.0})return search_resultsexcept Exception as e:print(f"Search error: {e}")return []def _store_new_knowledge(self, information, context=""):"""Store new information in Chroma"""try:doc_id = f"conv_{len(self.collection.get()['ids'])}"self.collection.add(documents=[information],metadatas=[{"type": "conversation","context": context,"timestamp": str(np.datetime64('now'))}],ids=[doc_id])except Exception as e:print(f"Error storing knowledge: {e}")def bulk_load_text_content(self, text_content, source_name="raw_text", chunk_size=800):"""16 unmodified linesprint(f"Created {len(chunks)} chunks")# Store each chunktry:documents = []metadatas = []ids = []for i, chunk in enumerate(chunks):documents.append(chunk)metadatas.append({"type": "text_content","source": source_name,"chunk_index": i,"timestamp": str(np.datetime64('now'))})ids.append(f"{source_name}_chunk_{i}")self.collection.add(documents=documents,metadatas=metadatas,ids=ids)except Exception as e:print(f"Error storing chunks: {e}")print(f"Loaded {len(chunks)} chunks from {source_name}")41 unmodified linesClear all or specific type of knowledge from the databaseArgs:knowledge_type: If specified, only delete documents of this type"""try:if knowledge_type:# Get documents of specific typeresults = self.collection.get(include=["metadatas"])type_ids = [results["ids"][i] for i, metadata in enumerate(results["metadatas"])if metadata.get("type") == knowledge_type]if type_ids:self.collection.delete(ids=type_ids)print(f"Deleted {len(type_ids)} {knowledge_type} documents")else:print(f"No {knowledge_type} documents found")else:# Clear entire collectionall_ids = self.collection.get()["ids"]if all_ids:self.collection.delete(ids=all_ids)print(f"Deleted {len(all_ids)} documents")else:print("No documents to delete")except Exception as e:print(f"Error clearing knowledge base: {e}")def get_knowledge_stats(self):"""Get statistics about the knowledge base"""try:results = self.collection.get(include=["metadatas"])stats = {}total = len(results["ids"])for metadata in results["metadatas"]:doc_type = metadata.get("type", "unknown")stats[doc_type] = stats.get(doc_type, 0) + 1print(f"Knowledge Base Stats (Total: {total} documents):")for doc_type, count in sorted(stats.items(), key=lambda x: x[1], reverse=True):print(f" {doc_type}: {count}")return statsexcept Exception as e:print(f"Error getting stats: {e}")return {}def handle_tool_call(self, tool_calls):results = []48 unmodified linesreturn response.choices[0].message.contentdef __del__(self):"""Clean up Chroma connection"""# Chroma client doesn't need explicit closingpassif __name__ == "__main__":
app.py+121-104