Spaces:
Running on Zero
Running on Zero
Major bug fixed
Browse filesFiles changed (3)
- CLAUDE.md+15-2
- app.py+82-34
- llm_graph.py+9-10
9 unmodified lines1011121314151629 unmodified lines464748495051525354555630 unmodified lines878889909 unmodified lines- **app.py**: Main Gradio application with UI components, visualization logic, and caching- **llm_graph.py**: Core LLMGraph class that handles model selection and knowledge graph extraction- **cache/**: Directory for caching visualization data (first example is pre-cached for performance)## Key Components29 unmodified lines# Install dependenciespip install -r requirements.txt# Run the Gradio apppython app.py# Test model extraction directlypython llm_graph.py```## Key Dependencies30 unmodified lines- First example is automatically cached for performance on startup- Cache files stored in `cache/` directory as pickle files- Working directory `sample/` is cleared and recreated on each run- GraphML files generated by LightRAG for Azure OpenAI model backend9 unmodified lines1011121314151617181929 unmodified lines495051525354555657585960616230 unmodified lines939495969798991001011021039 unmodified lines- **app.py**: Main Gradio application with UI components, visualization logic, and caching- **llm_graph.py**: Core LLMGraph class that handles model selection and knowledge graph extraction- **visualize.py**: Standalone script for visualizing GraphML files from LightRAG output- **data/**: Contains sample texts in multiple languages and system prompt templates- **cache/**: Directory for caching visualization data (first example is pre-cached for performance)- **sample/**: Working directory for LightRAG processing, cleared and recreated on each run## Key Components29 unmodified lines# Install dependenciespip install -r requirements.txt# Run the Gradio app locally (default port 7860)python app.py# Test model extraction directlypython llm_graph.py# Visualize existing GraphML files (requires sample/ directory with GraphML file)python visualize.py```## Key Dependencies30 unmodified lines- First example is automatically cached for performance on startup- Cache files stored in `cache/` directory as pickle files- Working directory `sample/` is cleared and recreated on each run- GraphML files generated by LightRAG for Azure OpenAI model backend## Environment Configuration- Uses `.env` file for API keys and endpoints (see Environment Setup section)- Designed for Hugging Face Spaces deployment (see README.md frontmatter)- SpaCy model loading is handled automatically by the application- No additional configuration files (package.json, pyproject.toml, etc.) required
12345678910111213141513 unmodified lines2930313233343536375 unmodified lines4344454647484926 unmodified lines767778798081824 unmodified lines878889909192932 unmodified lines969798991001011021031044 unmodified lines10911011111211311411539 unmodified lines15515615715815916016139 unmodified lines20120220320420520620720820917 unmodified lines22722822923023123223323423523623723842 unmodified lines28128228328428528628728828920 unmodified lines3103113123133143153163173183193203213223233243253263273283293303313323333342 unmodified lines33733833934034134234339 unmodified lines383384385386387388389import osimport timeimport spacyimport shutilimport pickleimport randomimport hashlibimport loggingimport asyncioimport warningsimport rapidjsonimport gradio as grimport networkx as nx13 unmodified linesMIN_CHARS = 20MAX_CHARS = 3500# Keep track of all processed textsdoc_ids = []# Basic CSS for stylingCUSTOM_CSS = """.gradio-container {5 unmodified linesCACHE_DIR = "./cache"WORKING_DIR = "./sample"EXAMPLE_CACHE_FILE = os.path.join(CACHE_DIR, "first_example_cache.pkl")GRAPHML_FILE = WORKING_DIR + "/graph_chunk_entity_relation.graphml"# Load the sample textstext_en_file1 = "./data/sample1_en.txt"26 unmodified linesdef get_random_light_color():"""Color utilities"""r = random.randint(140, 255)4 unmodified linesdef handle_text(text=""):"""Text preprocessing"""# Catch empty text2 unmodified linesreturn " ".join(text.split())def extract_kg(text="", model_name=MODEL_LIST[0], model=None):"""Extract knowledge graph from text"""# Catch empty text4 unmodified linestry:start_time = time.time()result = model.extract(text, model_name)end_time = time.time()duration = end_time - start_time39 unmodified linesdef create_custom_entity_viz(data, full_text, type_col="type"):"""Create custom entity visualization using spaCy's displacy"""nlp = spacy.blank("xx")39 unmodified linesreturn styled_htmldef create_graph(json_data, model_name=MODEL_LIST[0]):"""Create interactive knowledge graph using pyvis"""if model_name == MODEL_LIST[0]:17 unmodified lineslabel = edge.get('label', 'related')G.add_edge(edge['from'], edge['to'], title=label, label=label)else:G = nx.read_graphml(GRAPHML_FILE)# Create network visualizationnetwork = Network(width="100%",# height="700px",height="100vh",notebook=False,bgcolor="#f8fafc",42 unmodified linesallow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""def process_and_visualize(text, model_name, progress=gr.Progress()):"""Process text and visualize knowledge graph and entities"""if not text or not model_name:20 unmodified linesif len(text) > MAX_CHARS:raise gr.Error(f"⚠️ Text is too long! Please provide no more than {MAX_CHARS} characters.")if model_name == MODEL_LIST[1]:# Compute the unique hash for the documentdoc_id = hashlib.md5(text.strip().encode()).hexdigest()if doc_id not in doc_ids:doc_ids.append(doc_id)# Clear the working directory if it existsif os.path.exists(WORKING_DIR):shutil.rmtree(WORKING_DIR)os.makedirs(WORKING_DIR, exist_ok=True)# Initialize the LLMGraph modelmodel = LLMGraph()asyncio.run(model.initialize_rag())# Continue with normal processing if cache failsprogress(0, desc="Starting extraction...")json_data = extract_kg(text, model_name, model)progress(0.5, desc="Creating entity visualization...")if model_name == MODEL_LIST[0]:2 unmodified linesentities_viz = create_custom_entity_viz(json_data, text, type_col="entity_type")progress(0.8, desc="Building knowledge graph...")graph_html = create_graph(json_data, model_name)node_count = len(json_data["nodes"])edge_count = len(json_data["edges"])39 unmodified linesmodel_name = MODEL_LIST[0] if MODEL_LIST else None# Initialize the LLMGraph modelmodel = LLMGraph()asyncio.run(model.initialize_rag())# Extract data123456789101112131415161713 unmodified lines3132333435365 unmodified lines42434445464726 unmodified lines747576777879804 unmodified lines858687888990912 unmodified lines9495969798991001011024 unmodified lines10710810911011111211311411511611711811912012139 unmodified lines16116216316416516616739 unmodified lines20720820921021121221321421517 unmodified lines23323423523623723823924024124224324442 unmodified lines28728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433520 unmodified lines3563573583593603613623633643653663673683693703713723733743753763773783793803813822 unmodified lines38538638738838939039139 unmodified lines431432433434435436437import osimport reimport timeimport spacyimport shutilimport pickleimport randomimport hashlibimport loggingimport asyncioimport warningsimport rapidjsonimport unicodedataimport gradio as grimport networkx as nx13 unmodified linesMIN_CHARS = 20MAX_CHARS = 3500# Basic CSS for stylingCUSTOM_CSS = """.gradio-container {5 unmodified linesCACHE_DIR = "./cache"WORKING_DIR = "./sample"EXAMPLE_CACHE_FILE = os.path.join(CACHE_DIR, "first_example_cache.pkl")# Load the sample textstext_en_file1 = "./data/sample1_en.txt"26 unmodified linesdef get_random_light_color():"""Color utilities."""r = random.randint(140, 255)4 unmodified linesdef handle_text(text=""):"""Text preprocessing."""# Catch empty text2 unmodified linesreturn " ".join(text.split())def extract_kg(text="", model_name=MODEL_LIST[0], model=None, graph_file=""):"""Extract knowledge graph from text."""# Catch empty text4 unmodified linestry:start_time = time.time()if model_name == MODEL_LIST[1] and os.path.exists(graph_file):# Load the graph directly from cachelogging.info(f"Loading graph from cache: {graph_file}")G = nx.read_graphml(graph_file)# Convert the graph to node-link data formatresult = nx.node_link_data(G, edges="edges")else:result = model.extract(text, model_name, graph_file)end_time = time.time()duration = end_time - start_time39 unmodified linesdef create_custom_entity_viz(data, full_text, type_col="type"):"""Create custom entity visualization using spaCy's displaCy."""nlp = spacy.blank("xx")39 unmodified linesreturn styled_htmldef create_graph(json_data, model_name=MODEL_LIST[0], graph_file=""):"""Create interactive knowledge graph using Pyvis."""if model_name == MODEL_LIST[0]:17 unmodified lineslabel = edge.get('label', 'related')G.add_edge(edge['from'], edge['to'], title=label, label=label)else:assert graph_file, "Graph file path cannot be empty or None."G = nx.read_graphml(graph_file)# Create network visualizationnetwork = Network(width="100%",height="100vh",notebook=False,bgcolor="#f8fafc",42 unmodified linesallow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""def fuzzy_text_hash(text, algorithm='md5'):"""Generate a hash that treats nearly identical texts as the same.This function normalizes text by:- Converting to lowercase- Removing punctuation and special characters- Normalizing whitespace (multiple spaces become single space)- Removing leading/trailing whitespace- Normalizing Unicode charactersArgs:text (str): The input text to hashalgorithm (str): Hash algorithm to use ('md5', 'sha1', 'sha256', 'sha512')Returns:str: Hexadecimal hash string"""# Normalize Unicode characters (decompose accented characters, etc.)normalized = unicodedata.normalize('NFKD', text)# Convert to lowercasenormalized = normalized.lower()# Remove all punctuation and special characters, keep only alphanumeric and spacesnormalized = re.sub(r'[^\w\s]', '', normalized)# Normalize whitespace: replace multiple whitespace chars with single spacenormalized = re.sub(r'\s+', ' ', normalized)# Strip leading and trailing whitespacenormalized = normalized.strip()# Create hashhash_obj = hashlib.new(algorithm)hash_obj.update(normalized.encode('utf-8'))return hash_obj.hexdigest()def process_and_visualize(text, model_name, progress=gr.Progress()):"""Process text and visualize knowledge graph and entities."""if not text or not model_name:20 unmodified linesif len(text) > MAX_CHARS:raise gr.Error(f"⚠️ Text is too long! Please provide no more than {MAX_CHARS} characters.")# Compute the unique hash for the document# doc_id = hashlib.md5(text.strip().encode()).hexdigest()doc_id = fuzzy_text_hash(text.strip())logging.info(f"Document ID: {doc_id}")# Create a working directory based on the hashmy_working_dir = os.path.join(WORKING_DIR, doc_id)graph_file = os.path.join(my_working_dir, "graph_chunk_entity_relation.graphml")# Check if the working directory exists (the doc has been processed before)if not os.path.exists(my_working_dir):# Create the working directoryos.makedirs(my_working_dir, exist_ok=True)# Initialize the LLMGraph modelmodel = LLMGraph(working_dir=my_working_dir)asyncio.run(model.initialize_rag())# Continue with normal processing if cache failsprogress(0, desc="Starting extraction...")json_data = extract_kg(text, model_name, model, graph_file)progress(0.5, desc="Creating entity visualization...")if model_name == MODEL_LIST[0]:2 unmodified linesentities_viz = create_custom_entity_viz(json_data, text, type_col="entity_type")progress(0.8, desc="Building knowledge graph...")graph_html = create_graph(json_data, model_name, graph_file)node_count = len(json_data["nodes"])edge_count = len(json_data["edges"])39 unmodified linesmodel_name = MODEL_LIST[0] if MODEL_LIST else None# Initialize the LLMGraph modelmodel = LLMGraph(working_dir=WORKING_DIR)asyncio.run(model.initialize_rag())# Extract data
12345621 unmodified lines28293031323334353616 unmodified lines5354555657585919 unmodified lines798081828384855 unmodified lines91929394959636 unmodified lines1331341351361371381395 unmodified lines145146147148149150151152153154155156157158159import osimport time# import shutilimport numpy as npimport networkx as nx21 unmodified linesAZURE_EMBEDDING_DEPLOYMENT = os.environ["AZURE_EMBEDDING_DEPLOYMENT"]AZURE_EMBEDDING_API_VERSION = os.environ["AZURE_EMBEDDING_API_VERSION"]WORKING_DIR = "./sample"GRAPHML_FILE = WORKING_DIR + "/graph_chunk_entity_relation.graphml"MODEL_LIST = ["EmergentMethods/Phi-3-mini-128k-instruct-graph","OpenAI/GPT-4.1-mini",16 unmodified linesif self.rag is None:self.rag = LightRAG(working_dir=WORKING_DIR,llm_model_func=self._llm_model_func,embedding_func=EmbeddingFunc(embedding_dim=embedding_dimension,19 unmodified lines# return Truedef __init__(self):"""Initialize the Phi3InstructGraph with a specified model."""5 unmodified lines)self.rag = None # Lazy loading of RAG instancedef _generate(self, messages):"""36 unmodified linesreturn messagesdef extract(self, text, model_name=MODEL_LIST[0]):"""Extract knowledge graph in structured format from text."""5 unmodified linesjson_graph = self._generate(messages)return json_graphelse:# Use LightRAG with Azure OpenAIself.rag.insert(text) # Insert the text into the RAG storage# Wait for GRAPHML_FILE to be createdwhile not os.path.exists(GRAPHML_FILE):time.sleep(0.1) # Sleep for 0.1 seconds before checking again# Extract dict format of the knowledge graphG = nx.read_graphml(GRAPHML_FILE)# Convert the graph to node-link data formatdict_graph = nx.node_link_data(G, edges="edges")1234521 unmodified lines27282930313216 unmodified lines4950515253545519 unmodified lines757677787980815 unmodified lines8788899091929336 unmodified lines1301311321331341351365 unmodified lines142143144145146147148149150151152153154155156157158import osimport timeimport numpy as npimport networkx as nx21 unmodified linesAZURE_EMBEDDING_DEPLOYMENT = os.environ["AZURE_EMBEDDING_DEPLOYMENT"]AZURE_EMBEDDING_API_VERSION = os.environ["AZURE_EMBEDDING_API_VERSION"]MODEL_LIST = ["EmergentMethods/Phi-3-mini-128k-instruct-graph","OpenAI/GPT-4.1-mini",16 unmodified linesif self.rag is None:self.rag = LightRAG(working_dir=self.working_dir,llm_model_func=self._llm_model_func,embedding_func=EmbeddingFunc(embedding_dim=embedding_dimension,19 unmodified lines# return Truedef __init__(self, working_dir):"""Initialize the Phi3InstructGraph with a specified model."""5 unmodified lines)self.rag = None # Lazy loading of RAG instanceself.working_dir = working_dirdef _generate(self, messages):"""36 unmodified linesreturn messagesdef extract(self, text, model_name=MODEL_LIST[0], graph_file=""):"""Extract knowledge graph in structured format from text."""5 unmodified linesjson_graph = self._generate(messages)return json_graphelse:assert graph_file, "Graph file path cannot be empty or None."# Use LightRAG with Azure OpenAIself.rag.insert(text) # Insert the text into the RAG storage# Wait for the graph file to be createdwhile not os.path.exists(graph_file):time.sleep(0.1) # Sleep for 0.1 seconds before checking again# Extract dict format of the knowledge graphG = nx.read_graphml(graph_file)# Convert the graph to node-link data formatdict_graph = nx.node_link_data(G, edges="edges")
CLAUDE.md+15-2
app.py+82-34
llm_graph.py+9-10