Spaces:
Running on Zero
Running on Zero
Adding LightRAG KG
Browse filesFiles changed (6)
- CLAUDE.mdAdded+79
- app.py+30-15
- app_old.pyDeleted-280
- llm_graph.py+125-16
- main.pyDeleted-392
- requirements.txt+4-2
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Application Overview
This is a Text2Graph application that extracts knowledge graphs from natural language text. It's a Gradio web app that uses either OpenAI GPT-4.1-mini via Azure or Phi-3-mini-128k-instruct-graph via Hugging Face to extract entities and relationships from text, then visualizes them as interactive graphs.
## Architecture
- **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 Components
### LLMGraph Class (llm_graph.py)- Supports two model backends: Azure OpenAI (GPT-4.1-mini) and Hugging Face (Phi-3-mini-128k-instruct-graph)- Uses LightRAG for Azure OpenAI integration- Direct inference API calls for Hugging Face models- Extracts structured JSON with nodes (entities) and edges (relationships)
### Visualization Pipeline (app.py)- Entity recognition visualization using spaCy's displacy- Interactive knowledge graph using pyvis and NetworkX- Caching system for performance optimization- Color-coded entity types with random light colors
## Environment Setup
Required environment variables:```HF_TOKEN=<huggingface_token>HF_API_ENDPOINT=<huggingface_inference_endpoint>AZURE_OPENAI_API_KEY=<azure_openai_key>AZURE_OPENAI_ENDPOINT=<azure_endpoint>AZURE_OPENAI_API_VERSION=<api_version>AZURE_OPENAI_DEPLOYMENT=<deployment_name>AZURE_EMBEDDING_DEPLOYMENT=<embedding_deployment>AZURE_EMBEDDING_API_VERSION=<embedding_api_version>```
## Running the Application
```bash# Install dependenciespip install -r requirements.txt
# Run the Gradio apppython app.py```
## Key Dependencies
- **gradio**: Web interface framework- **lightrag-hku**: RAG framework for Azure OpenAI integration- **transformers**: Hugging Face model integration- **pyvis**: Interactive network visualization- **networkx**: Graph data structure and algorithms- **spacy**: Natural language processing and entity visualization- **openai**: Azure OpenAI client
## Data Flow
1. User inputs text and selects model2. LLMGraph.extract() processes text using selected model backend3. JSON response contains nodes (entities) and edges (relationships)4. Visualization functions create entity highlighting and interactive graph5. Results cached for performance (first example only)
## Model Behavior
The application expects JSON output with this schema:```json{ "nodes": [{"id": "entity", "type": "broad_type", "detailed_type": "specific_type"}], "edges": [{"from": "entity1", "to": "entity2", "label": "relationship"}]}```2 unmodified lines34567892 unmodified lines12131415161735 unmodified lines535455565758592 unmodified lines6263646566676869147 unmodified lines21721821922022122222314 unmodified lines23823924024124224324424524624724817 unmodified lines26626726826927027127220 unmodified lines29329429529629729829930030130230330430530630730830931031131211 unmodified lines3243253263273283293303313323333343353363373383393403413 unmodified lines3453463473483493503512 unmodified linesimport spacyimport pickleimport randomimport rapidjsonimport gradio as grimport networkx as nx2 unmodified linesfrom spacy import displacyfrom spacy.tokens import Span# ConstantsTITLE = "π Text2Graph: Extract Knowledge Graphs from Natural Language"SUBTITLE = "β¨ Extract and visualize knowledge graphs from texts in any language!"35 unmodified linesreturn " ".join(text.split())# @spaces.GPUdef extract_kg(text="", model=None):"""Extract knowledge graph from text"""2 unmodified linesif not text or not model:raise gr.Error("β οΈ Both text and model must be provided!")try:model = LLMGraph(model=model)result = model.extract(text)return rapidjson.loads(result)except Exception as e:raise gr.Error(f"β Extraction error: {str(e)}")147 unmodified linesallow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""def process_and_visualize(text, model, progress=gr.Progress()):"""Process text and visualize knowledge graph and entities"""14 unmodified linesprogress(1.0, desc="Loaded from cache!")return cache_data["graph_html"], cache_data["entities_viz"], cache_data["json_data"], cache_data["stats"]except Exception as e:print(f"Cache loading error: {str(e)}")# Continue with normal processing if cache failsprogress(0, desc="Starting extraction...")json_data = extract_kg(text, model)progress(0.5, desc="Creating entity visualization...")entities_viz = create_custom_entity_viz(json_data, text)17 unmodified lineswith open(EXAMPLE_CACHE_FILE, 'wb') as f:pickle.dump(cache_data, f)except Exception as e:print(f"Cache saving error: {str(e)}")progress(1.0, desc="Complete!")return graph_html, entities_viz, json_data, stats20 unmodified linesles buis et Γ arroser les rosiers, perpΓ©tuant ainsi une tradition d'excellence horticole qui fait la fiertΓ© de la capitale franΓ§aise.""")],]def generate_first_example_cache():"""Generate cache for the first example if it doesn't exist when the app starts"""if not os.path.exists(EXAMPLE_CACHE_FILE):print("Generating cache for first example...")try:text = EXAMPLES[0][0]model = MODEL_LIST[0] if MODEL_LIST else None# Extract datajson_data = extract_kg(text, model)entities_viz = create_custom_entity_viz(json_data, text)graph_html = create_graph(json_data)11 unmodified lineswith open(EXAMPLE_CACHE_FILE, 'wb') as f:pickle.dump(cached_data, f)print("First example cache generated successfully")return cached_dataexcept Exception as e:print(f"Error generating first example cache: {str(e)}")else:print("First example cache already exists")try:with open(EXAMPLE_CACHE_FILE, 'rb') as f:return pickle.load(f)except Exception as e:print(f"Error loading existing cache: {str(e)}")return None3 unmodified lines"""# Try to generate/load the first example cachefirst_example_cache = generate_first_example_cache()with gr.Blocks(css=CUSTOM_CSS, title=TITLE) as demo:# Header2 unmodified lines34567891011122 unmodified lines151617181920212235 unmodified lines585960616263642 unmodified lines676869707172737475147 unmodified lines22322422522622722822914 unmodified lines24424524624724824925025125225325425517 unmodified lines27327427527627727827928020 unmodified lines30130230330430530630730830931031131231331431531631731831932032111 unmodified lines3333343353363373383393403413423433443453463473483493503513523533543553563 unmodified lines3603613623633643653662 unmodified linesimport spacyimport pickleimport randomimport loggingimport rapidjsonimport asyncioimport gradio as grimport networkx as nx2 unmodified linesfrom spacy import displacyfrom spacy.tokens import Spanlogging.basicConfig(level=logging.INFO)# ConstantsTITLE = "π Text2Graph: Extract Knowledge Graphs from Natural Language"SUBTITLE = "β¨ Extract and visualize knowledge graphs from texts in any language!"35 unmodified linesreturn " ".join(text.split())# @spaces.GPUasync def extract_kg(text="", model=None):"""Extract knowledge graph from text"""2 unmodified linesif not text or not model:raise gr.Error("β οΈ Both text and model must be provided!")try:model_instance = LLMGraph(model=model)result = await model_instance.extract(text)return rapidjson.loads(result)except Exception as e:raise gr.Error(f"β Extraction error: {str(e)}")147 unmodified linesallow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""async def process_and_visualize(text, model, progress=gr.Progress()):"""Process text and visualize knowledge graph and entities"""14 unmodified linesprogress(1.0, desc="Loaded from cache!")return cache_data["graph_html"], cache_data["entities_viz"], cache_data["json_data"], cache_data["stats"]except Exception as e:# print(f"Cache loading error: {str(e)}")logging.error(f"Cache loading error: {str(e)}")# Continue with normal processing if cache failsprogress(0, desc="Starting extraction...")json_data = await extract_kg(text, model)progress(0.5, desc="Creating entity visualization...")entities_viz = create_custom_entity_viz(json_data, text)17 unmodified lineswith open(EXAMPLE_CACHE_FILE, 'wb') as f:pickle.dump(cache_data, f)except Exception as e:# print(f"Cache saving error: {str(e)}")logging.error(f"Cache saving error: {str(e)}")progress(1.0, desc="Complete!")return graph_html, entities_viz, json_data, stats20 unmodified linesles buis et Γ arroser les rosiers, perpΓ©tuant ainsi une tradition d'excellence horticole qui fait la fiertΓ© de la capitale franΓ§aise.""")],]async def generate_first_example_cache():"""Generate cache for the first example if it doesn't exist when the app starts"""if not os.path.exists(EXAMPLE_CACHE_FILE):# print("Generating cache for first example...")logging.info("Generating cache for first example...")try:text = EXAMPLES[0][0]model = MODEL_LIST[0] if MODEL_LIST else None# Extract datajson_data = await extract_kg(text, model)entities_viz = create_custom_entity_viz(json_data, text)graph_html = create_graph(json_data)11 unmodified lineswith open(EXAMPLE_CACHE_FILE, 'wb') as f:pickle.dump(cached_data, f)# print("First example cache generated successfully")logging.info("First example cache generated successfully")return cached_dataexcept Exception as e:# print(f"Error generating first example cache: {str(e)}")logging.error(f"Error generating first example cache: {str(e)}")else:# print("First example cache already exists")logging.info("First example cache already exists")# Load existing cachetry:with open(EXAMPLE_CACHE_FILE, 'rb') as f:return pickle.load(f)except Exception as e:# print(f"Error loading existing cache: {str(e)}")logging.error(f"Error loading existing cache: {str(e)}")return None3 unmodified lines"""# Try to generate/load the first example cachefirst_example_cache = asyncio.run(generate_first_example_cache())with gr.Blocks(css=CUSTOM_CSS, title=TITLE) as demo:# Header
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280# import spacesimport gradio as grfrom llm_graph import MODEL_LIST, LLMGraphimport rapidjsonfrom pyvis.network import Networkimport networkx as nximport spacyfrom spacy import displacyfrom spacy.tokens import Spanimport randomfrom tqdm import tqdm
# ConstantsTITLE = "π GraphMind: Phi-3 Instruct Graph Explorer"SUBTITLE = "β¨ Extract and visualize knowledge graphs from any text in multiple languages"
# Custom CSS for stylingCUSTOM_CSS = """.gradio-container { font-family: 'Inter', 'Segoe UI', Roboto, sans-serif;}.gr-button-primary { background-color: #6366f1 !important;}.gr-button-secondary { border-color: #6366f1 !important; color: #6366f1 !important;}"""
# Color utilitiesdef get_random_light_color(): r = random.randint(140, 255) g = random.randint(140, 255) b = random.randint(140, 255) return f"#{r:02x}{g:02x}{b:02x}"
# Text preprocessingdef handle_text(text): return " ".join(text.split())
# Main processing functions# @spaces.GPUdef extract(text, model): try: model = LLMGraph(model=model) result = model.extract(text) return rapidjson.loads(result) except Exception as e: raise gr.Error(f"Extraction error: {str(e)}")
def find_token_indices(doc, substring, text): result = [] start_index = text.find(substring) while start_index != -1: end_index = start_index + len(substring) start_token = None end_token = None
for token in doc: if token.idx == start_index: start_token = token.i if token.idx + len(token) == end_index: end_token = token.i + 1
if start_token is not None and end_token is not None: result.append({ "start": start_token, "end": end_token }) # Search for next occurrence start_index = text.find(substring, end_index)
return result
def create_custom_entity_viz(data, full_text): nlp = spacy.blank("xx") doc = nlp(full_text)
spans = [] colors = {} for node in data["nodes"]: entity_spans = find_token_indices(doc, node["id"], full_text) for dataentity in entity_spans: start = dataentity["start"] end = dataentity["end"] if start < len(doc) and end <= len(doc): # Check for overlapping spans overlapping = any(s.start < end and start < s.end for s in spans) if not overlapping: span = Span(doc, start, end, label=node["type"]) spans.append(span) if node["type"] not in colors: colors[node["type"]] = get_random_light_color()
doc.set_ents(spans, default="unmodified") doc.spans["sc"] = spans
options = { "colors": colors, "ents": list(colors.keys()), "style": "ent", "manual": True }
html = displacy.render(doc, style="span", options=options) return html
def create_graph(json_data): G = nx.Graph()
# Add nodes with tooltips for node in json_data['nodes']: G.add_node(node['id'], title=f"{node['type']}: {node['detailed_type']}")
# Add edges with labels for edge in json_data['edges']: G.add_edge(edge['from'], edge['to'], title=edge['label'], label=edge['label'])
# Create network visualization nt = Network( width="720px", height="600px", directed=True, notebook=False, bgcolor="#f8fafc", font_color="#1e293b" ) # Configure network display nt.from_nx(G) nt.barnes_hut( gravity=-3000, central_gravity=0.3, spring_length=50, spring_strength=0.001, damping=0.09, overlap=0, ) # Customize edge appearance for edge in nt.edges: edge['width'] = 2 edge['arrows'] = {'to': {'enabled': True, 'type': 'arrow'}} edge['color'] = {'color': '#6366f1', 'highlight': '#4f46e5'} edge['font'] = {'size': 12, 'color': '#4b5563', 'face': 'Arial'}
# Customize node appearance for node in nt.nodes: node['color'] = {'background': '#e0e7ff', 'border': '#6366f1', 'highlight': {'background': '#c7d2fe', 'border': '#4f46e5'}} node['font'] = {'size': 14, 'color': '#1e293b'} node['shape'] = 'dot' node['size'] = 25
# Generate HTML with iframe to isolate styles html = nt.generate_html() html = html.replace("'", '"')
return f"""<iframe style="width: 100%; height: 620px; margin: 0 auto; border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);" name="result" allow="midi; geolocation; microphone; camera; display-capture; encrypted-media;" sandbox="allow-modals allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation-by-user-activation allow-downloads" allowfullscreen="" allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""
def process_and_visualize(text, model, progress=gr.Progress()): if not text or not model: raise gr.Error("β οΈ Both text and model must be provided.") progress(0, desc="Starting extraction...") json_data = extract(text, model) progress(0.5, desc="Creating entity visualization...") entities_viz = create_custom_entity_viz(json_data, text) progress(0.8, desc="Building knowledge graph...") graph_html = create_graph(json_data) node_count = len(json_data["nodes"]) edge_count = len(json_data["edges"]) stats = f"π Extracted {node_count} entities and {edge_count} relationships" progress(1.0, desc="Complete!") return graph_html, entities_viz, json_data, stats
# Example texts in different languagesEXAMPLES = [ [handle_text("""Legendary rock band Aerosmith has officially announced their retirement from touring after 54 years, citing lead singer Steven Tyler's unrecoverable vocal cord injury. The decision comes after months of unsuccessful treatment for Tyler's fractured larynx, which he suffered in September 2023.""")], [handle_text("""Pop star Justin Timberlake, 43, had his driver's license suspended by a New York judge during a virtual court hearing on August 2, 2024. The suspension follows Timberlake's arrest for driving while intoxicated (DWI) in Sag Harbor on June 18. Timberlake, who is currently on tour in Europe, pleaded not guilty to the charges.""")], [handle_text("""μΈκ³μ μΈ κΈ°μ κΈ°μ
μΌμ±μ μλ μλ‘μ΄ μΈκ³΅μ§λ₯ κΈ°λ° μ€λ§νΈν°μ μ¬ν΄ νλ°κΈ°μ μΆμν μμ μ΄λΌκ³ λ°ννλ€. μ΄ μ€λ§νΈν°μ νμ¬ κ°λ° μ€μΈ κ°€λμ μ리μ¦μ μ΅μ μμΌλ‘, κ°λ ₯ν AI κΈ°λ₯κ³Ό νμ μ μΈ μΉ΄λ©λΌ μμ€ν
μ νμ¬ν κ²μΌλ‘ μλ €μ‘λ€. μΌμ±μ μμ CEOλ μ΄λ² μ μ νμ΄ μ€λ§νΈν° μμ₯μ μλ‘μ΄ νμ μ κ°μ Έμ¬ κ²μ΄λΌκ³ μ λ§νλ€.""")], [handle_text("""νκ΅ μν 'κΈ°μμΆ©'μ 2020λ
μμΉ΄λ°λ―Έ μμμμμ μνμ, κ°λ
μ, κ°λ³Έμ, κ΅μ μνμ λ± 4κ° λΆλ¬Έμ μμνλ©° μμ¬λ₯Ό μλ‘ μΌλ€. λ΄μ€νΈ κ°λ
μ΄ μ°μΆν μ΄ μνλ νκ΅ μν μ΅μ΄λ‘ μΉΈ μνμ ν©κΈμ’
λ €μλ μμνμΌλ©°, μ μΈκ³μ μΌλ‘ μμ²λ ν₯νκ³Ό νλ¨μ νΈνμ λ°μλ€.""")]]
def create_ui(): with gr.Blocks(css=CUSTOM_CSS, title=TITLE) as demo: # Header gr.Markdown(f"# {TITLE}") gr.Markdown(f"{SUBTITLE}") with gr.Row(): gr.Markdown("π **Multilingual Support Available** π€") # Main interface with gr.Row(): # Input column with gr.Column(scale=1): input_model = gr.Dropdown( MODEL_LIST, label="π€ Select Model", info="Choose a model to process your text", value=MODEL_LIST[0] if MODEL_LIST else None ) input_text = gr.TextArea( label="π Input Text", info="Enter text in any language to extract a knowledge graph", placeholder="Enter text here...", lines=10 ) with gr.Row(): submit_button = gr.Button("π Extract & Visualize", variant="primary", scale=2) clear_button = gr.Button("π Clear", variant="secondary", scale=1) gr.Examples( examples=EXAMPLES, inputs=input_text, label="π Example Texts (English & Korean)" ) stats_output = gr.Markdown("", label="π Analysis Results") # Output column with gr.Column(scale=1): with gr.Tab("π§© Knowledge Graph"): output_graph = gr.HTML(label="") with gr.Tab("π·οΈ Entities"): output_entity_viz = gr.HTML(label="") with gr.Tab("π JSON Data"): output_json = gr.JSON(label="") # Functionality submit_button.click( fn=process_and_visualize, inputs=[input_text, input_model], outputs=[output_graph, output_entity_viz, output_json, stats_output] ) clear_button.click( fn=lambda: [None, None, None, ""], inputs=[], outputs=[output_graph, output_entity_viz, output_json, stats_output] ) # Footer gr.Markdown("---") gr.Markdown("π **Instructions:** Enter text in any language, select a model, and click 'Extract & Visualize' to generate a knowledge graph.") gr.Markdown("π οΈ Powered by Phi-3 Instruct Graph | Emergent Methods") return demo
demo = create_ui()demo.launch(share=False)1234567891011121314151617181 unmodified line2021222324252627282930313233341 unmodified line3637383940414242 unmodified lines858687888990914 unmodified lines96979899100101102103104105106107108109110111112import osfrom textwrap import dedentfrom huggingface_hub import InferenceClientfrom dotenv import load_dotenvload_dotenv()api_token = os.environ["HF_TOKEN"]endpoint_url = os.environ["HF_API_ENDPOINT"]# Initialize the client with your endpoint URL and token.client = InferenceClient(model=endpoint_url,token=api_token)MODEL_LIST = ["OpenAI/GPT-4.1-mini",1 unmodified line]class LLMGraph:def __init__(self, model="OpenAI/GPT-4.1-mini"):"""Initialize the Phi3InstructGraph with a specified model."""if model not in MODEL_LIST:raise ValueError(f"Model must be one of {MODEL_LIST}")self.model_path = modeldef _generate(self, messages):"""1 unmodified line"""# Use the chat_completion methodresponse = client.chat_completion(messages=messages,max_tokens=1024,)42 unmodified lines-------Text end-------""")# if self.model_path == "EmergentMethods/Phi-3-medium-128k-instruct-graph":messages = [{"role": "system",4 unmodified lines"content": user_message}]# else:# # TODO: update for other modelsreturn messagesdef extract(self, text):"""Extract knowledge graph from text"""messages = self._get_messages(text)generated_text = self._generate(messages)return generated_text123456789101112131415161718192021222324252627282930311 unmodified line333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031 unmodified line10510610710810911011142 unmodified lines1541551561571581594 unmodified lines164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221import osimport asyncioimport numpy as npfrom textwrap import dedentfrom dotenv import load_dotenvfrom openai import AzureOpenAIfrom huggingface_hub import InferenceClientfrom lightrag import LightRAGfrom lightrag.utils import EmbeddingFuncfrom lightrag.kg.shared_storage import initialize_pipeline_statusload_dotenv()# Load the environment variablesapi_token = os.environ["HF_TOKEN"]endpoint_url = os.environ["HF_API_ENDPOINT"]AZURE_OPENAI_API_VERSION = os.environ["AZURE_OPENAI_API_VERSION"]AZURE_OPENAI_DEPLOYMENT = os.environ["AZURE_OPENAI_DEPLOYMENT"]AZURE_OPENAI_API_KEY = os.environ["AZURE_OPENAI_API_KEY"]AZURE_OPENAI_ENDPOINT = os.environ["AZURE_OPENAI_ENDPOINT"]AZURE_EMBEDDING_DEPLOYMENT = os.environ["AZURE_EMBEDDING_DEPLOYMENT"]AZURE_EMBEDDING_API_VERSION = os.environ["AZURE_EMBEDDING_API_VERSION"]WORKING_DIR = "./cache"MODEL_LIST = ["OpenAI/GPT-4.1-mini",1 unmodified line]class LLMGraph:"""A class to interact with LLMs for knowledge graph extraction."""async def _initialize_rag(self, embedding_dimension=3072):"""Initialize the LightRAG instance with the specified embedding dimension."""rag = LightRAG(working_dir=WORKING_DIR,llm_model_func=self._llm_model_func,embedding_func=EmbeddingFunc(embedding_dim=embedding_dimension,max_token_size=8192,func=self._embedding_func,),)await rag.initialize_storages()await initialize_pipeline_status()return ragasync def _get_rag(self):"""Get or initialize the RAG instance (lazy loading)."""if self.rag is None:self.rag = await self._initialize_rag()return self.ragdef __init__(self, model="OpenAI/GPT-4.1-mini"):"""Initialize the Phi3InstructGraph with a specified model."""if model not in MODEL_LIST:raise ValueError(f"Model must be one of {MODEL_LIST}")self.model_name = modelif model == MODEL_LIST[0]:# Use Azure OpenAI for GPT-4.1-miniself.llm_client = AzureOpenAI(api_key=AZURE_OPENAI_API_KEY,api_version=AZURE_OPENAI_API_VERSION,azure_endpoint=AZURE_OPENAI_ENDPOINT,)self.emb_client = AzureOpenAI(api_key=AZURE_OPENAI_API_KEY,api_version=AZURE_EMBEDDING_API_VERSION,azure_endpoint=AZURE_OPENAI_ENDPOINT,)self.rag = None # Initialize as None for lazy loadingelse:# Use Hugging Face Inference API for Phi-3-mini-128k-instruct-graphself.hf_client = InferenceClient(model=endpoint_url,token=api_token)def _generate(self, messages):"""1 unmodified line"""# Use the chat_completion methodresponse = self.hf_client.chat_completion(messages=messages,max_tokens=1024,)42 unmodified lines-------Text end-------""")messages = [{"role": "system",4 unmodified lines"content": user_message}]return messagesasync def extract(self, text):"""Extract knowledge graph from text"""generated_text = ""if self.model_name == MODEL_LIST[0]:# Use LightRAG with Azure OpenAIrag = await self._get_rag()rag.insert(text)else:# Use Hugging Face Inference API with Phi-3-mini-128k-instruct-graphmessages = self._get_messages(text)generated_text = self._generate(messages)return generated_textasync def _llm_model_func(self, prompt, system_prompt=None, history_messages=[], **kwargs) -> str:"""Call the Azure OpenAI chat completion endpoint with the given prompt and optional system prompt and history messages."""messages = []if system_prompt:messages.append({"role": "system", "content": system_prompt})if history_messages:messages.extend(history_messages)messages.append({"role": "user", "content": prompt})chat_completion = self.llm_client.chat.completions.create(model=AZURE_OPENAI_DEPLOYMENT,messages=messages,temperature=kwargs.get("temperature", 0),top_p=kwargs.get("top_p", 1),n=kwargs.get("n", 1),)return chat_completion.choices[0].message.contentasync def _embedding_func(self, texts: list[str]) -> np.ndarray:"""Call the Azure OpenAI embeddings endpoint with the given texts."""embedding = self.emb_client.embeddings.create(model=AZURE_EMBEDDING_DEPLOYMENT, input=texts)embeddings = [item.embedding for item in embedding.data]return np.array(embeddings)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392# import spacesimport gradio as grfrom llm_graph import MODEL_LIST, LLMGraphimport rapidjsonfrom pyvis.network import Networkimport networkx as nximport spacyfrom spacy import displacyfrom spacy.tokens import Spanimport randomimport time
# Set up the theme and stylingCUSTOM_CSS = """.gradio-container { font-family: 'Inter', 'Segoe UI', Roboto, sans-serif;}.gr-prose h1 { font-size: 2.5rem !important; margin-bottom: 0.5rem !important; background: linear-gradient(90deg, #4338ca, #a855f7); -webkit-background-clip: text; -webkit-text-fill-color: transparent;}.gr-prose h2 { font-size: 1.8rem !important; margin-top: 1rem !important;}.info-box { padding: 1rem; border-radius: 0.5rem; background-color: #f3f4f6; margin-bottom: 1rem; border-left: 4px solid #6366f1;}.language-badge { display: inline-block; padding: 0.25rem 0.5rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; background-color: #e0e7ff; color: #4338ca; margin-right: 0.5rem; margin-bottom: 0.5rem;}.footer { text-align: center; margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #e2e8f0; font-size: 0.875rem; color: #64748b;}"""
# Color utilitiesdef get_random_light_color(): r = random.randint(150, 255) g = random.randint(150, 255) b = random.randint(150, 255) return f"#{r:02x}{g:02x}{b:02x}"
# Text processing helperdef handle_text(text): return " ".join(text.split())
# Core extraction function# @spaces.GPUdef extract(text, model): model = LLMGraph(model=model) try: result = model.extract(text) return rapidjson.loads(result) except Exception as e: raise gr.Error(f"π¨ Extraction failed: {str(e)}")
def find_token_indices(doc, substring, text): result = [] start_index = text.find(substring) while start_index != -1: end_index = start_index + len(substring) start_token = None end_token = None
for token in doc: if token.idx == start_index: start_token = token.i if token.idx + len(token) == end_index: end_token = token.i + 1
if start_token is not None and end_token is not None: result.append({ "start": start_token, "end": end_token }) # Search for next occurrence start_index = text.find(substring, end_index)
return result
def create_custom_entity_viz(data, full_text): nlp = spacy.blank("xx") doc = nlp(full_text)
spans = [] colors = {} for node in data["nodes"]: entity_spans = find_token_indices(doc, node["id"], full_text) for dataentity in entity_spans: start = dataentity["start"] end = dataentity["end"] if start < len(doc) and end <= len(doc): # Check for overlapping spans overlapping = any(s.start < end and start < s.end for s in spans) if not overlapping: span = Span(doc, start, end, label=node["type"]) spans.append(span) if node["type"] not in colors: colors[node["type"]] = get_random_light_color()
doc.set_ents(spans, default="unmodified") doc.spans["sc"] = spans
options = { "colors": colors, "ents": list(colors.keys()), "style": "ent", "manual": True }
html = displacy.render(doc, style="span", options=options) # Add custom styling to the entity visualization styled_html = f""" <div style="border-radius: 0.5rem; padding: 1rem; background-color: white; border: 1px solid #e2e8f0; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);"> <div style="margin-bottom: 0.75rem; font-weight: 500; color: #4b5563;"> Entity types found: {' '.join([f'<span style="display: inline-block; margin-right: 0.5rem; margin-bottom: 0.5rem; padding: 0.25rem 0.5rem; border-radius: 9999px; font-size: 0.75rem; background-color: {colors[entity_type]}; color: #1e293b;">{entity_type}</span>' for entity_type in colors.keys()])} </div> {html} </div> """ return styled_html
def create_graph(json_data): G = nx.DiGraph() # Using DiGraph for directed graph
# Add nodes for node in json_data['nodes']: G.add_node(node['id'], title=f"{node['type']}: {node['detailed_type']}", group=node['type']) # Group nodes by type
# Add edges for edge in json_data['edges']: G.add_edge(edge['from'], edge['to'], title=edge['label'], label=edge['label'])
# Create network visualization nt = Network( width="100%", height="600px", directed=True, notebook=False, bgcolor="#fafafa", font_color="#1e293b" ) # Configure network nt.from_nx(G) nt.barnes_hut( gravity=-3000, central_gravity=0.3, spring_length=150, spring_strength=0.001, damping=0.09, overlap=0, )
# Create color groups for node types node_types = {node['type'] for node in json_data['nodes']} colors = {} for i, node_type in enumerate(node_types): hue = (i * 137) % 360 # Golden ratio to distribute colors colors[node_type] = f"hsl({hue}, 70%, 70%)"
# Customize nodes for node in nt.nodes: node_data = next((n for n in json_data['nodes'] if n['id'] == node['id']), None) if node_data: node_type = node_data['type'] node['color'] = colors.get(node_type, "#bfdbfe") node['shape'] = 'dot' node['size'] = 20 node['borderWidth'] = 2 node['borderWidthSelected'] = 4 node['font'] = {'size': 14, 'color': '#1e293b', 'face': 'Inter, Arial'} # Customize edges for edge in nt.edges: edge['color'] = {'color': '#94a3b8', 'highlight': '#6366f1', 'hover': '#818cf8'} edge['width'] = 1.5 edge['selectionWidth'] = 2 edge['hoverWidth'] = 2 edge['arrows'] = {'to': {'enabled': True, 'type': 'arrow'}} edge['smooth'] = {'type': 'continuous', 'roundness': 0.2} edge['font'] = {'size': 12, 'color': '#4b5563', 'face': 'Inter, Arial', 'strokeWidth': 2, 'strokeColor': '#ffffff'}
# Generate HTML html = nt.generate_html() html = html.replace("'", '"') html = html.replace('height: 600px;', 'height: 600px; border-radius: 8px;')
return f"""<iframe style="width: 100%; height: 620px; margin: 0 auto; border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);" name="result" allow="midi; geolocation; microphone; camera; display-capture; encrypted-media;" sandbox="allow-modals allow-forms allow-scripts allow-same-origin allow-popups allow-top-navigation-by-user-activation allow-downloads" allowfullscreen="" allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""
def process_and_visualize(text, model, progress=gr.Progress()): if not text or not model: raise gr.Error("β οΈ Please provide both text and model") # Progress updates progress(0.1, "Initializing...") time.sleep(0.2) # Small delay for UI feedback # Extract graph progress(0.2, "Extracting knowledge graph...") json_data = extract(text, model) # Entity visualization progress(0.6, "Identifying entities...") entities_viz = create_custom_entity_viz(json_data, text) # Graph visualization progress(0.8, "Building graph visualization...") graph_html = create_graph(json_data) # Statistics entity_types = {} for node in json_data['nodes']: entity_type = node['type'] if entity_type in entity_types: entity_types[entity_type] += 1 else: entity_types[entity_type] = 1 stats_html = f""" <div class="info-box"> <h3 style="margin-top: 0;">π Extraction Results</h3> <p>β
Successfully extracted <b>{len(json_data['nodes'])}</b> entities and <b>{len(json_data['edges'])}</b> relationships.</p> <div> <h4>Entity Types:</h4> <div> {''.join([f'<span class="language-badge">{entity_type}: {count}</span>' for entity_type, count in entity_types.items()])} </div> </div> </div> """ progress(1.0, "Done!") return graph_html, entities_viz, json_data, stats_html
def language_info(): return """ <div class="info-box"> <h3 style="margin-top: 0;">π Multilingual Support</h3> <p>This application supports text analysis in multiple languages, including:</p> <div> <span class="language-badge">English π¬π§</span> <span class="language-badge">Korean π°π·</span> <span class="language-badge">Spanish πͺπΈ</span> <span class="language-badge">French π«π·</span> <span class="language-badge">German π©πͺ</span> <span class="language-badge">Japanese π―π΅</span> <span class="language-badge">Chinese π¨π³</span> <span class="language-badge">And more...</span> </div> </div> """
def tips_html(): return """ <div class="info-box"> <h3 style="margin-top: 0;">π‘ Tips for Best Results</h3> <ul> <li>Use clear, descriptive sentences with well-defined relationships</li> <li>Include specific entities, events, dates, and locations for better extraction</li> <li>Longer texts provide more context for relationship identification</li> <li>Try different models to compare extraction results</li> </ul> </div> """
# Examples in multiple languagesEXAMPLES = [ [handle_text("""Legendary rock band Aerosmith has officially announced their retirement from touring after 54 years, citing lead singer Steven Tyler's unrecoverable vocal cord injury. The decision comes after months of unsuccessful treatment for Tyler's fractured larynx, which he suffered in September 2023.""")], [handle_text("""Pop star Justin Timberlake, 43, had his driver's license suspended by a New York judge during a virtual court hearing on August 2, 2024. The suspension follows Timberlake's arrest for driving while intoxicated (DWI) in Sag Harbor on June 18. Timberlake, who is currently on tour in Europe, pleaded not guilty to the charges.""")],]
# Main UIwith gr.Blocks(css=CUSTOM_CSS, title="π§ Phi-3 Knowledge Graph Explorer") as demo: # Header gr.Markdown("# π§ Phi-3 Knowledge Graph Explorer") gr.Markdown("### β¨ Extract and visualize knowledge graphs from text in any language") with gr.Row(): with gr.Column(scale=2): input_text = gr.TextArea( label="π Enter your text", placeholder="Paste or type your text here...", lines=10 ) with gr.Row(): input_model = gr.Dropdown( MODEL_LIST, label="π€ Model", value=MODEL_LIST[0] if MODEL_LIST else None, info="Select the model to use for extraction" ) with gr.Column(): submit_button = gr.Button("π Extract & Visualize", variant="primary") clear_button = gr.Button("π Clear", variant="secondary") # Multilingual support info gr.HTML(language_info()) # Examples section gr.Examples( examples=EXAMPLES, inputs=input_text, label="π Example Texts (English & Korean)" ) # Tips gr.HTML(tips_html()) with gr.Column(scale=3): # Stats output stats_output = gr.HTML(label="") # Tabs for different visualizations with gr.Tabs(): with gr.TabItem("π Knowledge Graph"): output_graph = gr.HTML() with gr.TabItem("π·οΈ Entity Recognition"): output_entity_viz = gr.HTML() with gr.TabItem("π JSON Data"): output_json = gr.JSON() # Footer gr.HTML(""" <div class="footer"> <p>π Powered by Phi-3 Instruct Graph | Created by Emergent Methods</p> <p>Β© 2025 | Knowledge Graph Explorer</p> </div> """) # Set up event handlers submit_button.click( fn=process_and_visualize, inputs=[input_text, input_model], outputs=[output_graph, output_entity_viz, output_json, stats_output] ) clear_button.click( fn=lambda: [None, None, None, ""], inputs=[], outputs=[output_graph, output_entity_viz, output_json, stats_output] )
# Launch the appdemo.launch(share=False)12345678910python-dotenvgradiotransformers==4.45.2python-dotenvacceleratepython-rapidjsonspacespyvisnetworkxspacy123456789101112python-dotenvgradiotransformersacceleratepython-rapidjsonspacespyvisnetworkxspacynumpylightrag-hkuopenai
CLAUDE.mdAdded+79
app.py+30-15
app_old.pyDeleted-280
llm_graph.py+125-16
main.pyDeleted-392
requirements.txt+4-2