Spaces:
Running on Zero
Running on Zero
Multiple updates
Browse filesFiles changed (4)
- README.md+2-2
- app.py+117-68
- app-backup.py → app_old.pyRenamed
- phi3_instruct_graph.py+32-24
123456---title: Graph Mindemoji: 👀colorFrom: purplecolorTo: pinksdk: gradio123456---title: Text2Graphemoji: 🌐colorFrom: purplecolorTo: pinksdk: gradio
123456789101112131415161718199 unmodified lines293031323334353637383940414243444546474849505152535455565758596061626364656667683 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031041051064 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331343 unmodified lines1381391401411421431441451461471481491501511521531541553 unmodified lines1591601611621631641651661671681691701711721731741751761771781793 unmodified lines18318418518618718811 unmodified lines20020120220320420520620720820922 unmodified lines2322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642 unmodified lines2672682692702712722732742752762772782792802812822837 unmodified lines2912922932942952962 unmodified lines29930030130230330430530630773 unmodified lines381382383384385386387388389390# import spacesimport gradio as grfrom phi3_instruct_graph import Phi3InstructGraphimport rapidjsonfrom pyvis.network import Networkimport networkx as nximport spacyfrom spacy import displacyfrom spacy.tokens import Spanimport randomimport osimport pickle# ConstantsTITLE = "🌐 GraphMind: Phi-3 Instruct Graph Explorer"SUBTITLE = "✨ Extract and visualize knowledge graphs from any text in multiple languages"# Basic CSS for stylingCUSTOM_CSS = """9 unmodified lines# Create cache directory if it doesn't existos.makedirs(CACHE_DIR, exist_ok=True)# 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):try:model = Phi3InstructGraph()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 = Noneend_token = Nonefor token in doc:if token.idx == start_index:start_token = token.iif token.idx + len(token) == end_index:end_token = token.i + 1if start_token is not None and end_token is not None:3 unmodified lines})# Search for next occurrencestart_index = text.find(substring, end_index)return resultdef 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 spansoverlapping = any(s.start < end and start < s.end for s in spans)if not overlapping:node_type = node.get("type", "Entity")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"] = spansoptions = {"colors": colors,"ents": list(colors.keys()),4 unmodified lineshtml = displacy.render(doc, style="span", options=options)# Add custom styling to the entity visualizationstyled_html = f"""<div style="padding: 20px; border-radius: 12px; background-color: white; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">{html}</div>"""return styled_htmldef create_graph(json_data):G = nx.Graph()# Add nodes with tooltips - with error handling for missing keysfor node in json_data['nodes']:# Get node type with fallbacknode_type = node.get("type", "Entity")# Get detailed type with fallbackdetailed_type = node.get("detailed_type", node_type)# Use node ID and type info for the tooltipG.add_node(node['id'], title=f"{node_type}: {detailed_type}")# Add edges with labelsfor edge in json_data['edges']:3 unmodified linesG.add_edge(edge['from'], edge['to'], title=label, label=label)# Create network visualizationnt = Network(width="100%",height="700px",directed=True,notebook=False,bgcolor="#f8fafc",font_color="#1e293b")# Configure network displaynt.from_nx(G)nt.barnes_hut(gravity=-3000,central_gravity=0.3,spring_length=50,3 unmodified lines)# Customize edge appearancefor edge in nt.edges:edge['width'] = 2edge['arrows'] = {'to': {'enabled': True, 'type': 'arrow'}}edge['color'] = {'color': '#6366f1', 'highlight': '#4f46e5'}edge['font'] = {'size': 12, 'color': '#4b5563', 'face': 'Arial'}# Customize node appearancefor 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 styleshtml = nt.generate_html()html = html.replace("'", '"')return f"""<iframe style="width: 100%; height: 700px; margin: 0 auto; border-radius: 12px; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);"3 unmodified linesallowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""def process_and_visualize(text, progress=gr.Progress()):if not text:raise gr.Error("⚠️ Text must be provided!")11 unmodified linesreturn 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(text)progress(0.5, desc="Creating entity visualization...")entities_viz = create_custom_entity_viz(json_data, text)22 unmodified linesprogress(1.0, desc="Complete!")return graph_html, entities_viz, json_data, stats# Example texts in different languagesEXAMPLES = [[handle_text("""The family of Azerbaijan President Ilham Aliyev leads a charmed, glamorous life, thanks in part to financial interests in almost every sector of the economy. His wife, Mehriban, comes from the privileged and powerful Pashayev family that owns banks, insurance and construction companies, a television station and a line of cosmetics. She has led the Heydar Aliyev Foundation, Azerbaijan’s pre-eminent charity behind the construction of schools, hospitals and the country’s major sports complex. Their eldest daughter, Leyla, editor of Baku magazine, and her sister, Arzu, have financial stakes in a firm that won rights to mine for gold in the western village of Chovdar and Azerfon, the country’s largest mobile phone business. Arzu is also a significant shareholder in SW Holding, which controls nearly every operation related to Azerbaijan Airlines (“Azal”), from meals to airport taxis. Both sisters and brother Heydar own property in Dubai valued at roughly $75 million in 2010; Heydar is the legal owner of nine luxury mansions in Dubai purchased for some $44 million.""")],[handle_text("""Legendary rock band Aerosmith has officially announced their retirement from touring after 54 years, citinglead 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 virtualcourt 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.""")],]# Function to preprocess the first example when the app startsdef generate_first_example_cache():"""Generate cache for the first example if it doesn't exist"""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# if model:# Extract datajson_data = extract(text, model)entities_viz = create_custom_entity_viz(json_data, text)graph_html = create_graph(json_data)2 unmodified linesstats = f"📊 Extracted {node_count} entities and {edge_count} relationships"# Save to cachecache_data = {"graph_html": graph_html,"entities_viz": entities_viz,"json_data": json_data,"stats": stats}with open(EXAMPLE_CACHE_FILE, 'wb') as f:pickle.dump(cache_data, f)print("First example cache generated successfully")return cache_dataexcept Exception as e:print(f"Error generating first example cache: {str(e)}")else:7 unmodified linesreturn Nonedef create_ui():# Try to generate/load the first example cachefirst_example_cache = generate_first_example_cache()2 unmodified linesgr.Markdown(f"# {TITLE}")gr.Markdown(f"{SUBTITLE}")with gr.Row():gr.Markdown("🌍 **Multilingual Support Available**")# Main content area - redesigned layoutwith gr.Row():# Left panel - Input controls73 unmodified lines# Footergr.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 demodemo = create_ui()demo.launch(share=False)12345678910111213141516171819209 unmodified lines3031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091923 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351364 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691703 unmodified lines1741751761771781791801811821831841851861871881891901913 unmodified lines1951961971981992002012022032042052062072082092102112122132142153 unmodified lines21922022122222322422522622722811 unmodified lines24024124224324424524624724824922 unmodified lines2722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103112 unmodified lines3143153163173183193203213223233243253263273283293303317 unmodified lines3393403413423433443453463473482 unmodified lines35135235335435535673 unmodified lines430431432433434435436437438439# import spacesimport osimport spacyimport pickleimport randomimport rapidjsonimport gradio as grimport networkx as nxfrom phi3_instruct_graph import Phi3InstructGraphfrom pyvis.network import Networkfrom 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!"# Basic CSS for stylingCUSTOM_CSS = """9 unmodified lines# Create cache directory if it doesn't existos.makedirs(CACHE_DIR, exist_ok=True)def get_random_light_color():"""Color utilities"""r = random.randint(140, 255)g = random.randint(140, 255)b = random.randint(140, 255)return f"#{r:02x}{g:02x}{b:02x}"def handle_text(text=""):"""Text preprocessing"""# Catch empty textif not text:return ""return " ".join(text.split())## @spaces.GPUdef extract_kg(text=""):"""Extract knowledge graph from text"""# Catch empty textif not text:raise gr.Error("⚠️ Text must be provided!")try:model = Phi3InstructGraph()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):"""Find token indices for a given substring in the textbased on the provided spaCy doc."""result = []start_idx = text.find(substring)while start_idx != -1:end_idx = start_idx + len(substring)start_token = Noneend_token = Nonefor token in doc:if token.idx == start_idx:start_token = token.iif token.idx + len(token) == end_idx:end_token = token.i + 1if start_token is not None and end_token is not None:3 unmodified lines})# Search for next occurrencestart_idx = text.find(substring, end_idx)return resultdef create_custom_entity_viz(data, full_text):"""Create custom entity visualization using spaCy's displacy"""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 entity in entity_spans:start = entity["start"]end = entity["end"]if start < len(doc) and end <= len(doc):# Check for overlapping spansoverlapping = any(s.start < end and start < s.end for s in spans)if not overlapping:node_type = node.get("type", "Entity")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"] = spansoptions = {"colors": colors,"ents": list(colors.keys()),4 unmodified lineshtml = displacy.render(doc, style="span", options=options)# Add custom styling to the entity visualizationstyled_html = f"""<div style="padding: 20px; border-radius: 12px; background-color: gray; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">{html}</div>"""return styled_htmldef create_graph(json_data):"""Create interactive knowledge graph using pyvis"""G = nx.Graph()# Add nodes with tooltips and error handling for missing keysfor node in json_data['nodes']:# Get node type with fallbacktype = node.get("type", "Entity")# Get detailed type with fallbackdetailed_type = node.get("detailed_type", type)# Use node ID and type info for the tooltipG.add_node(node['id'], title=f"{type}: {detailed_type}")# Add edges with labelsfor edge in json_data['edges']:3 unmodified linesG.add_edge(edge['from'], edge['to'], title=label, label=label)# Create network visualizationnetwork = Network(width="100%",height="700px",directed=False,notebook=False,bgcolor="#f8fafc",font_color="#1e293b")# Configure network displaynetwork.from_nx(G)network.barnes_hut(gravity=-3000,central_gravity=0.3,spring_length=50,3 unmodified lines)# Customize edge appearancefor edge in network.edges:edge['width'] = 2edge['arrows'] = {'to': {'enabled': False, 'type': 'arrow'}}edge['color'] = {'color': '#6366f1', 'highlight': '#4f46e5'}edge['font'] = {'size': 12, 'color': '#4b5563', 'face': 'Arial'}# Customize node appearancefor node in network.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 styleshtml = network.generate_html()html = html.replace("'", '"')return f"""<iframe style="width: 100%; height: 700px; margin: 0 auto; border-radius: 12px; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);"3 unmodified linesallowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""def process_and_visualize(text, progress=gr.Progress()):"""Process text and visualize knowledge graph and entities"""if not text:raise gr.Error("⚠️ Text must be provided!")11 unmodified linesreturn 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)progress(0.5, desc="Creating entity visualization...")entities_viz = create_custom_entity_viz(json_data, text)22 unmodified linesprogress(1.0, desc="Complete!")return graph_html, entities_viz, json_data, stats# Example textsEXAMPLES = [[handle_text("""The family of Azerbaijan President Ilham Aliyev leads a charmed, glamorous life, thanks in part to financial interests in almost every sector of the economy.His wife, Mehriban, comes from the privileged and powerful Pashayev family that owns banks, insurance and construction companies,a television station and a line of cosmetics. She has led the Heydar Aliyev Foundation, Azerbaijan’s pre-eminent charity behind the construction of schools,hospitals and the country’s major sports complex. Their eldest daughter, Leyla, editor of Baku magazine, and her sister, Arzu,have financial stakes in a firm that won rights to mine for gold in the western village of Chovdar and Azerfon, the country’s largest mobile phone business.Arzu is also a significant shareholder in SW Holding, which controls nearly every operation related to Azerbaijan Airlines (“Azal”), from meals to airport taxis.Both sisters and brother Heydar own property in Dubai valued at roughly $75 million in 2010;Heydar is the legal owner of nine luxury mansions in Dubai purchased for some $44 million.""")],[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 virtualcourt 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.""")],]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 = Phi3InstructGraph()# Extract datajson_data = extract_kg(text, model)entities_viz = create_custom_entity_viz(json_data, text)graph_html = create_graph(json_data)2 unmodified linesstats = f"📊 Extracted {node_count} entities and {edge_count} relationships"# Save to cachecached_data = {"graph_html": graph_html,"entities_viz": entities_viz,"json_data": json_data,"stats": stats}with 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:7 unmodified linesreturn Nonedef create_ui():"""Create the Gradio UI"""# Try to generate/load the first example cachefirst_example_cache = generate_first_example_cache()2 unmodified linesgr.Markdown(f"# {TITLE}")gr.Markdown(f"{SUBTITLE}")# Main content area - redesigned layoutwith gr.Row():# Left panel - Input controls73 unmodified lines# Footergr.Markdown("---")gr.Markdown("📋 **Instructions:** Enter text in any language and click 'Extract & Visualize' to generate a knowledge graph.")gr.Markdown("🛠️ Powered by [Phi-3-mini-128k-instruct-graph](https://huggingface.co/EmergentMethods/Phi-3-mini-128k-instruct-graph)")return demodemo = create_ui()demo.launch(share=False)
15 unmodified lines161718192021222324255 unmodified lines31323334353629 unmodified lines6667686970717273747576777879808182838485868788899091929394959615 unmodified linesclass Phi3InstructGraph:def __init__(self, model = "EmergentMethods/Phi-3-mini-4k-instruct-graph"):self.model_path = modeldef _generate(self, messages):# Use the chat_completion methodresponse = client.chat_completion(messages=messages,5 unmodified linesreturn generated_textdef _get_messages(self, text):context = dedent("""\nA chat between a curious user and an artificial intelligence Assistant. The Assistant is an expert at identifying entities and relationships in text. The Assistant responds in JSON output only.29 unmodified lines-------Text end-------""")if self.model_path == "EmergentMethods/Phi-3-medium-128k-instruct-graph":# model without system message -- why??messages = [{"role": "user","content": f"{context}\n Input: {user_message}",}]return messageselse:messages = [{"role": "system","content": context},{"role": "user","content": user_message}]return messagesdef extract(self, text):messages = self._get_messages(text)generated_text = self._generate(messages)# return pipe_output[0]["generated_text"]return generated_text15 unmodified lines16171819202122232425262728293031325 unmodified lines3839404142434445464729 unmodified lines777879808182838485868788899091929394959697989910010110210310415 unmodified linesclass Phi3InstructGraph:def __init__(self, model = "EmergentMethods/Phi-3-mini-4k-instruct-graph"):"""Initialize the Phi3InstructGraph with a specified model."""self.model_path = modeldef _generate(self, messages):"""Generate a response from the model based on the provided messages."""# Use the chat_completion methodresponse = client.chat_completion(messages=messages,5 unmodified linesreturn generated_textdef _get_messages(self, text):"""Construct the message list for the chat model."""context = dedent("""\nA chat between a curious user and an artificial intelligence Assistant. The Assistant is an expert at identifying entities and relationships in text. The Assistant responds in JSON output only.29 unmodified lines-------Text end-------""")# if self.model_path == "EmergentMethods/Phi-3-medium-128k-instruct-graph":messages = [{"role": "system","content": context},{"role": "user","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_text
README.md+2-2
app.py+117-68
app-backup.py → app_old.pyRenamed
phi3_instruct_graph.py+32-24