VirtualOasis commited on
Commit
d44d865
·
verified ·
1 Parent(s): b99df01

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +306 -11
app.py CHANGED
@@ -1,23 +1,318 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def letter_counter(word, letter):
4
- """Count the occurrences of a specific letter in a word.
5
 
6
  Args:
7
- word: The word or phrase to analyze
8
- letter: The letter to count occurrences of
9
 
10
  Returns:
11
- The number of times the letter appears in the word
12
  """
13
- return word.lower().count(letter.lower())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  demo = gr.Interface(
16
- fn=letter_counter,
17
- inputs=["text", "text"],
18
- outputs="number",
19
- title="Letter Counter",
20
- description="Count how many times a letter appears in a word"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  )
22
 
23
  demo.launch(mcp_server=True)
 
1
  import gradio as gr
2
+ import os
3
+ import json
4
+ import requests
5
+ from bs4 import BeautifulSoup
6
+ import networkx as nx
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import io
10
+ import base64
11
+ from huggingface_hub import InferenceClient
12
+ import re
13
+ from urllib.parse import urlparse
14
 
15
+ def fetch_content(url_or_text):
16
+ """Fetch content from URL or return text directly.
17
 
18
  Args:
19
+ url_or_text: Either a URL to fetch content from, or direct text input
 
20
 
21
  Returns:
22
+ Extracted text content
23
  """
24
+ # Check if input looks like a URL
25
+ parsed = urlparse(url_or_text)
26
+ if parsed.scheme in ['http', 'https']:
27
+ try:
28
+ headers = {
29
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
30
+ }
31
+ response = requests.get(url_or_text, headers=headers, timeout=10)
32
+ response.raise_for_status()
33
+
34
+ # Parse HTML and extract text
35
+ soup = BeautifulSoup(response.content, 'html.parser')
36
+
37
+ # Remove script and style elements
38
+ for script in soup(["script", "style"]):
39
+ script.decompose()
40
+
41
+ # Get text and clean it up
42
+ text = soup.get_text()
43
+ lines = (line.strip() for line in text.splitlines())
44
+ chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
45
+ text = ' '.join(chunk for chunk in chunks if chunk)
46
+
47
+ return text[:5000] # Limit to first 5000 characters
48
+ except Exception as e:
49
+ return f"Error fetching URL: {str(e)}"
50
+ else:
51
+ # It's direct text input
52
+ return url_or_text
53
 
54
+ def extract_entities(text):
55
+ """Extract entities and relationships using Mistral.
56
+
57
+ Args:
58
+ text: Input text to analyze
59
+
60
+ Returns:
61
+ Dictionary containing entities and relationships
62
+ """
63
+ try:
64
+ client = InferenceClient(
65
+ provider="together",
66
+ api_key=os.environ.get("HF_TOKEN"),
67
+ )
68
+
69
+ prompt = f"""
70
+ Analyze the following text and extract:
71
+ 1. Named entities (people, organizations, locations, concepts)
72
+ 2. Relationships between these entities
73
+
74
+ Return the result as a JSON object with this structure:
75
+ {{
76
+ "entities": [
77
+ {{"name": "entity_name", "type": "PERSON|ORG|LOCATION|CONCEPT", "description": "brief description"}}
78
+ ],
79
+ "relationships": [
80
+ {{"source": "entity1", "target": "entity2", "relation": "relationship_type", "description": "brief description"}}
81
+ ]
82
+ }}
83
+
84
+ Text to analyze:
85
+ {text[:2000]}
86
+
87
+ JSON:"""
88
+
89
+ completion = client.chat.completions.create(
90
+ model="mistralai/Mistral-Small-24B-Instruct-2501",
91
+ messages=[
92
+ {
93
+ "role": "user",
94
+ "content": prompt
95
+ }
96
+ ],
97
+ max_tokens=1500,
98
+ temperature=0.3,
99
+ )
100
+
101
+ response_text = completion.choices[0].message.content
102
+
103
+ # Extract JSON from response
104
+ json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
105
+ if json_match:
106
+ json_str = json_match.group()
107
+ return json.loads(json_str)
108
+ else:
109
+ # Fallback: create simple entities from text
110
+ words = text.split()
111
+ entities = []
112
+ for i, word in enumerate(words[:20]): # Limit to first 20 words
113
+ if word.istitle() and len(word) > 2:
114
+ entities.append({"name": word, "type": "CONCEPT", "description": "Extracted entity"})
115
+
116
+ return {"entities": entities, "relationships": []}
117
+
118
+ except Exception as e:
119
+ return {"entities": [{"name": "Error", "type": "ERROR", "description": str(e)}], "relationships": []}
120
+
121
+ def build_knowledge_graph(entities_data):
122
+ """Build and visualize knowledge graph.
123
+
124
+ Args:
125
+ entities_data: Dictionary containing entities and relationships
126
+
127
+ Returns:
128
+ PIL Image object of the knowledge graph
129
+ """
130
+ try:
131
+ # Create networkx graph
132
+ G = nx.Graph()
133
+
134
+ # Add nodes (entities)
135
+ entities = entities_data.get("entities", [])
136
+ for entity in entities:
137
+ G.add_node(entity["name"],
138
+ type=entity.get("type", "UNKNOWN"),
139
+ description=entity.get("description", ""))
140
+
141
+ # Add edges (relationships)
142
+ relationships = entities_data.get("relationships", [])
143
+ for rel in relationships:
144
+ if rel["source"] in G.nodes and rel["target"] in G.nodes:
145
+ G.add_edge(rel["source"], rel["target"],
146
+ relation=rel.get("relation", "related"),
147
+ description=rel.get("description", ""))
148
+
149
+ # If no relationships found, create some connections between entities
150
+ if len(relationships) == 0 and len(entities) > 1:
151
+ entity_names = [e["name"] for e in entities[:10]] # Limit to 10
152
+ for i in range(len(entity_names) - 1):
153
+ G.add_edge(entity_names[i], entity_names[i + 1], relation="related")
154
+
155
+ # Create visualization
156
+ fig, ax = plt.subplots(figsize=(12, 8))
157
+
158
+ # Position nodes using spring layout
159
+ pos = nx.spring_layout(G, k=2, iterations=50)
160
+
161
+ # Color nodes by type
162
+ node_colors = []
163
+ type_colors = {
164
+ "PERSON": "#FF6B6B",
165
+ "ORG": "#4ECDC4",
166
+ "LOCATION": "#45B7D1",
167
+ "CONCEPT": "#96CEB4",
168
+ "ERROR": "#FF0000",
169
+ "UNKNOWN": "#DDA0DD"
170
+ }
171
+
172
+ for node in G.nodes():
173
+ node_type = G.nodes[node].get('type', 'UNKNOWN')
174
+ node_colors.append(type_colors.get(node_type, "#DDA0DD"))
175
+
176
+ # Draw the graph
177
+ nx.draw(G, pos,
178
+ node_color=node_colors,
179
+ node_size=1000,
180
+ font_size=8,
181
+ font_weight='bold',
182
+ with_labels=True,
183
+ edge_color='gray',
184
+ width=2,
185
+ alpha=0.7,
186
+ ax=ax)
187
+
188
+ # Add title
189
+ ax.set_title("Knowledge Graph", size=16, weight='bold')
190
+
191
+ # Add legend
192
+ legend_elements = []
193
+ for type_name, color in type_colors.items():
194
+ if any(G.nodes[node].get('type') == type_name for node in G.nodes()):
195
+ legend_elements.append(plt.Line2D([0], [0], marker='o', color='w',
196
+ markerfacecolor=color, markersize=10, label=type_name))
197
+
198
+ if legend_elements:
199
+ ax.legend(handles=legend_elements, loc='upper right', bbox_to_anchor=(1.15, 1))
200
+
201
+ # Convert to PIL Image
202
+ fig.canvas.draw()
203
+ img_array = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
204
+ img_array = img_array.reshape(fig.canvas.get_width_height()[::-1] + (3,))
205
+
206
+ from PIL import Image
207
+ pil_image = Image.fromarray(img_array)
208
+ plt.close(fig)
209
+
210
+ return pil_image
211
+
212
+ except Exception as e:
213
+ # Create error image
214
+ fig, ax = plt.subplots(figsize=(8, 6))
215
+ ax.text(0.5, 0.5, f"Error creating graph:\n{str(e)}",
216
+ ha='center', va='center', fontsize=12, transform=ax.transAxes)
217
+ ax.set_title("Knowledge Graph Error")
218
+ ax.axis('off')
219
+
220
+ # Convert to PIL Image
221
+ fig.canvas.draw()
222
+ img_array = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
223
+ img_array = img_array.reshape(fig.canvas.get_width_height()[::-1] + (3,))
224
+
225
+ from PIL import Image
226
+ pil_image = Image.fromarray(img_array)
227
+ plt.close(fig)
228
+
229
+ return pil_image
230
+
231
+ def knowledge_graph_builder(url_or_text):
232
+ """Main function to build knowledge graph from URL or text.
233
+
234
+ Args:
235
+ url_or_text: URL to analyze or direct text input
236
+
237
+ Returns:
238
+ Tuple of (entities_json, graph_image, summary)
239
+ """
240
+ try:
241
+ # Step 1: Fetch content
242
+ content = fetch_content(url_or_text)
243
+
244
+ if content.startswith("Error"):
245
+ return content, None, "Failed to fetch content"
246
+
247
+ # Step 2: Extract entities
248
+ entities_data = extract_entities(content)
249
+
250
+ # Step 3: Build knowledge graph
251
+ graph_image = build_knowledge_graph(entities_data)
252
+
253
+ # Step 4: Create summary
254
+ num_entities = len(entities_data.get("entities", []))
255
+ num_relationships = len(entities_data.get("relationships", []))
256
+
257
+ summary = f"""
258
+ Knowledge Graph Analysis Complete!
259
+
260
+ 📊 **Statistics:**
261
+ - Entities found: {num_entities}
262
+ - Relationships found: {num_relationships}
263
+ - Content length: {len(content)} characters
264
+
265
+ 🔍 **Extracted Entities:**
266
+ """
267
+
268
+ for entity in entities_data.get("entities", [])[:10]: # Show first 10
269
+ summary += f"\n• **{entity['name']}** ({entity.get('type', 'UNKNOWN')}): {entity.get('description', 'No description')}"
270
+
271
+ if len(entities_data.get("entities", [])) > 10:
272
+ summary += f"\n... and {len(entities_data.get('entities', [])) - 10} more entities"
273
+
274
+ return json.dumps(entities_data, indent=2), graph_image, summary
275
+
276
+ except Exception as e:
277
+ return f"Error: {str(e)}", None, "Analysis failed"
278
+
279
+ # Create Gradio interface
280
  demo = gr.Interface(
281
+ fn=knowledge_graph_builder,
282
+ inputs=[
283
+ gr.Textbox(
284
+ label="URL or Text Input",
285
+ placeholder="Enter a URL (https://example.com) or paste text directly...",
286
+ lines=3,
287
+ info="Enter a website URL to analyze, or paste text content directly"
288
+ )
289
+ ],
290
+ outputs=[
291
+ gr.JSON(label="Extracted Entities & Relationships"),
292
+ gr.Image(label="Knowledge Graph Visualization"),
293
+ gr.Markdown(label="Analysis Summary")
294
+ ],
295
+ title="🧠 AI Knowledge Graph Builder",
296
+ description="""
297
+ **Transform any text or webpage into an interactive knowledge graph!**
298
+
299
+ This tool uses AI to:
300
+ 1. 📖 Extract content from URLs or analyze your text
301
+ 2. 🤖 Use Mistral AI to identify entities and relationships
302
+ 3. 🕸️ Build and visualize knowledge graphs
303
+ 4. 📊 Provide detailed analysis summaries
304
+
305
+ **Examples to try:**
306
+ - News articles: `https://www.bbc.com/news`
307
+ - Wikipedia pages: `https://en.wikipedia.org/wiki/Artificial_intelligence`
308
+ - Direct text: Copy and paste any article or document
309
+ """,
310
+ examples=[
311
+ ["https://en.wikipedia.org/wiki/Machine_learning"],
312
+ ["Artificial intelligence is transforming the world. Companies like OpenAI, Google, and Microsoft are leading the development of large language models. These models are being used in applications ranging from chatbots to code generation."],
313
+ ["https://www.nature.com/articles/d41586-023-00057-9"]
314
+ ],
315
+ theme=gr.themes.Soft()
316
  )
317
 
318
  demo.launch(mcp_server=True)