Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# 📚 Install dependencies
|
| 2 |
# Make sure to run this in your environment if you haven't already
|
| 3 |
-
# !pip install openai anthropic google-generativeai gradio transformers torch gliner --quiet
|
| 4 |
|
| 5 |
# ⚙️ Imports
|
| 6 |
import openai
|
|
@@ -8,9 +8,8 @@ import anthropic
|
|
| 8 |
import google.generativeai as genai
|
| 9 |
import gradio as gr
|
| 10 |
from gliner import GLiNER
|
| 11 |
-
import traceback
|
| 12 |
from collections import defaultdict, Counter
|
| 13 |
-
import numpy as np
|
| 14 |
import os
|
| 15 |
|
| 16 |
# 🧠 Supported models and their providers
|
|
@@ -25,32 +24,32 @@ GLINER_MODEL_NAME = "urchade/gliner_large-v2.1"
|
|
| 25 |
|
| 26 |
# --- Load the model only once at startup ---
|
| 27 |
try:
|
| 28 |
-
print("Loading AI
|
| 29 |
gliner_model = GLiNER.from_pretrained(GLINER_MODEL_NAME)
|
| 30 |
-
print("AI
|
| 31 |
except Exception as e:
|
| 32 |
print(f"FATAL ERROR: Could not load GLiNER model. The app will not be able to find entities. Error: {e}")
|
| 33 |
gliner_model = None
|
| 34 |
|
| 35 |
-
# 🧠 Prompt for the
|
| 36 |
-
|
| 37 |
-
You are
|
| 38 |
|
| 39 |
**Instructions:**
|
| 40 |
-
1.
|
| 41 |
-
2. For each category, list specific **
|
| 42 |
-
3. **Crucial Rule for Labels:** Use
|
| 43 |
|
| 44 |
**Output Format:**
|
| 45 |
-
Use Markdown. Each category must be a Level 3 Header (###), followed by a comma-separated list of its
|
| 46 |
|
| 47 |
-
### Example Category
|
| 48 |
-
-
|
| 49 |
-
### Example Category
|
| 50 |
-
-
|
| 51 |
"""
|
| 52 |
|
| 53 |
-
# 🧠 Generator Function (The "
|
| 54 |
def generate_from_prompt(prompt, provider, key_dict):
|
| 55 |
provider_id = MODEL_OPTIONS.get(provider)
|
| 56 |
api_key = key_dict.get(f"{provider_id}_key")
|
|
@@ -74,7 +73,6 @@ def generate_from_prompt(prompt, provider, key_dict):
|
|
| 74 |
|
| 75 |
# --- UI Definitions ---
|
| 76 |
|
| 77 |
-
# A list of standard, common labels the user can always choose from
|
| 78 |
STANDARD_LABELS = [
|
| 79 |
"PERSON", "ORGANIZATION", "LOCATION", "COUNTRY", "CITY", "STATE",
|
| 80 |
"NATIONALITY", "GROUP", "DATE", "EVENT", "LAW", "LEGAL_DOCUMENT",
|
|
@@ -82,81 +80,76 @@ STANDARD_LABELS = [
|
|
| 82 |
"MONEY", "CURRENCY", "QUANTITY", "ORDINAL_NUMBER", "CARDINAL_NUMBER"
|
| 83 |
]
|
| 84 |
|
| 85 |
-
MAX_CATEGORIES = 8
|
| 86 |
|
| 87 |
-
with gr.Blocks(title="
|
| 88 |
-
gr.Markdown("#
|
| 89 |
gr.Markdown(
|
| 90 |
"""
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
|
| 100 |
-
This AI is a precise detective. Once you give it a list of labels, it meticulously scans the text and *pulls out* (extracts) the exact words that match. It's fantastic at finding specific information with high accuracy.
|
| 101 |
"""
|
| 102 |
)
|
| 103 |
|
| 104 |
-
gr.Markdown("--- \n## Step 1:
|
|
|
|
| 105 |
with gr.Row():
|
| 106 |
-
topic = gr.Textbox(label="Enter a Topic", placeholder="e.g., The Chartist Movement, The Protestant Reformation")
|
| 107 |
-
provider = gr.Dropdown(choices=list(MODEL_OPTIONS.keys()), label="Choose
|
| 108 |
with gr.Row():
|
| 109 |
openai_key = gr.Textbox(label="OpenAI API Key", type="password")
|
| 110 |
anthropic_key = gr.Textbox(label="Anthropic API Key", type="password")
|
| 111 |
google_key = gr.Textbox(label="Google API Key", type="password")
|
| 112 |
|
| 113 |
-
generate_btn = gr.Button("Generate
|
| 114 |
|
| 115 |
-
gr.Markdown("--- \n## Step 2:
|
| 116 |
-
gr.Markdown(
|
| 117 |
-
"""
|
| 118 |
-
### What are Entities or Labels?
|
| 119 |
-
Think of them as special highlighters! They find and color-code specific types of information in your text, like `PERSON`, `DATE`, `LOCATION`, or custom things you define.
|
| 120 |
-
"""
|
| 121 |
-
)
|
| 122 |
|
| 123 |
-
gr.Markdown("#### 1.
|
| 124 |
-
gr.Markdown("
|
| 125 |
|
| 126 |
dynamic_components = []
|
| 127 |
with gr.Column():
|
| 128 |
for i in range(MAX_CATEGORIES):
|
| 129 |
-
with gr.Accordion(f"Suggested
|
|
|
|
| 130 |
with gr.Row():
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
dynamic_components.append((acc, cg, deselect_btn))
|
| 135 |
|
| 136 |
-
gr.Markdown("#### 2.
|
| 137 |
with gr.Group():
|
| 138 |
standard_labels_checkbox = gr.CheckboxGroup(choices=STANDARD_LABELS, value=STANDARD_LABELS, label="Standard Entity Labels", info="Common categories like people, places, and dates.")
|
| 139 |
with gr.Row():
|
| 140 |
select_all_std_btn = gr.Button("Select All", size="sm")
|
| 141 |
deselect_all_std_btn = gr.Button("Deselect All", size="sm")
|
| 142 |
|
| 143 |
-
|
| 144 |
-
gr.Markdown("#### 3. Add Your Own Custom Labels (Optional)")
|
| 145 |
with gr.Group():
|
| 146 |
custom_labels_textbox = gr.Textbox(label="Enter Custom Labels (comma-separated)", placeholder="e.g., Technology, Weapon, Secret Society...")
|
| 147 |
|
| 148 |
-
gr.Markdown("--- \n## Step 3:
|
| 149 |
-
threshold_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.4, step=0.05, label="Confidence Threshold", info="Controls
|
| 150 |
-
text_input = gr.Textbox(label="Paste Your
|
| 151 |
-
analyze_btn = gr.Button("Analyze Text
|
| 152 |
|
| 153 |
-
analysis_status = gr.Markdown(visible=False)
|
| 154 |
|
| 155 |
-
gr.Markdown("--- \n## Step 4: Review
|
| 156 |
gr.Markdown(
|
| 157 |
"""
|
| 158 |
-
✨ **Pro Tip:
|
| 159 |
-
|
| 160 |
"""
|
| 161 |
)
|
| 162 |
|
|
@@ -164,32 +157,26 @@ with gr.Blocks(title="Smart Text Analyzer", css=".prose { word-break: break-word
|
|
| 164 |
with gr.TabItem("Highlighted Text"):
|
| 165 |
highlighted_text_output = gr.HighlightedText(label="Found Entities", interactive=True)
|
| 166 |
with gr.TabItem("Detailed Results"):
|
| 167 |
-
detailed_results_output = gr.Markdown(label="List of Found Entities
|
| 168 |
-
with gr.TabItem("Debug
|
| 169 |
-
debug_output = gr.Textbox(label="Extraction Log", interactive=False, lines=8)
|
| 170 |
|
| 171 |
# --- Backend Functions ---
|
| 172 |
|
| 173 |
def handle_generate(topic, provider, openai_k, anthropic_k, google_k):
|
| 174 |
yield {
|
| 175 |
-
generate_btn: gr.update(value="
|
| 176 |
}
|
| 177 |
|
| 178 |
try:
|
| 179 |
-
key_dict = {
|
| 180 |
-
"openai_key": os.environ.get("OPENAI_API_KEY", openai_k),
|
| 181 |
-
"anthropic_key": os.environ.get("ANTHROPIC_API_KEY", anthropic_k),
|
| 182 |
-
"google_key": os.environ.get("GOOGLE_API_KEY", google_k)
|
| 183 |
-
}
|
| 184 |
-
|
| 185 |
provider_id = MODEL_OPTIONS.get(provider)
|
| 186 |
if not topic or not provider or not key_dict.get(f"{provider_id}_key"):
|
| 187 |
-
raise gr.Error("
|
| 188 |
|
| 189 |
-
prompt =
|
| 190 |
raw_framework = generate_from_prompt(prompt, provider, key_dict)
|
| 191 |
|
| 192 |
-
# This parsing is simplified for the new structure
|
| 193 |
framework = defaultdict(list)
|
| 194 |
current_category = None
|
| 195 |
for line in raw_framework.split('\n'):
|
|
@@ -201,137 +188,113 @@ with gr.Blocks(title="Smart Text Analyzer", css=".prose { word-break: break-word
|
|
| 201 |
framework[current_category].extend([e.strip() for e in entities.split(',') if e.strip()])
|
| 202 |
|
| 203 |
if not framework:
|
| 204 |
-
raise gr.Error("AI failed to generate categories. Please try again or rephrase your topic.")
|
| 205 |
|
| 206 |
updates = {}
|
| 207 |
categories = list(framework.items())
|
| 208 |
for i in range(MAX_CATEGORIES):
|
| 209 |
-
accordion_comp, checkbox_comp,
|
| 210 |
if i < len(categories):
|
| 211 |
category_name, entities = categories[i]
|
| 212 |
-
# The labels are the entities themselves, grouped by the category name
|
| 213 |
sorted_entities = sorted(list(set(entities)))
|
| 214 |
updates[accordion_comp] = gr.update(label=f"Category: {category_name}", visible=True)
|
| 215 |
updates[checkbox_comp] = gr.update(choices=sorted_entities, value=sorted_entities, label="Suggested Labels", visible=True)
|
| 216 |
-
updates[
|
|
|
|
| 217 |
else:
|
| 218 |
updates[accordion_comp] = gr.update(visible=False)
|
| 219 |
-
updates[checkbox_comp] = gr.update(visible=False)
|
| 220 |
-
updates[
|
|
|
|
| 221 |
|
| 222 |
-
updates[generate_btn] = gr.update(value="Generate
|
| 223 |
yield updates
|
| 224 |
except Exception as e:
|
| 225 |
-
yield {generate_btn: gr.update(value="Generate
|
| 226 |
raise gr.Error(str(e))
|
| 227 |
|
| 228 |
-
def
|
| 229 |
-
# --- 1. Show Progress to User ---
|
| 230 |
yield {
|
| 231 |
-
analyze_btn: gr.update(value="
|
| 232 |
-
analysis_status: gr.update(value="
|
| 233 |
-
highlighted_text_output: None,
|
| 234 |
-
detailed_results_output: None,
|
| 235 |
-
debug_output: "Starting analysis..."
|
| 236 |
}
|
| 237 |
|
| 238 |
debug_info = []
|
| 239 |
if gliner_model is None:
|
| 240 |
-
raise gr.Error("GLiNER model
|
| 241 |
|
| 242 |
-
# --- 2. Collect All Labels from UI ---
|
| 243 |
labels_to_use = set()
|
| 244 |
-
# Add labels from the dynamically generated suggestion groups
|
| 245 |
for group in suggested_labels_from_groups:
|
| 246 |
if group: labels_to_use.update(group)
|
| 247 |
-
# Add labels from the standard list
|
| 248 |
if standard_labels: labels_to_use.update(standard_labels)
|
| 249 |
-
# Add labels from the custom textbox
|
| 250 |
custom = {l.strip() for l in custom_label_text.split(',') if l.strip()}
|
| 251 |
if custom: labels_to_use.update(custom)
|
| 252 |
|
| 253 |
final_labels = sorted(list(labels_to_use))
|
| 254 |
-
debug_info.append(f"
|
| 255 |
-
debug_info.append(f"
|
| 256 |
|
| 257 |
if not text or not final_labels:
|
| 258 |
yield {
|
| 259 |
-
analyze_btn: gr.update(value="Analyze Text
|
| 260 |
analysis_status: gr.update(visible=False),
|
| 261 |
highlighted_text_output: {"text": text, "entities": []},
|
| 262 |
-
detailed_results_output: "Please provide text and select at least one label to search for.",
|
| 263 |
debug_output: "Analysis stopped: No text or no labels provided."
|
| 264 |
}
|
| 265 |
return
|
| 266 |
|
| 267 |
-
# --- 3. Run the GLiNER Model (The "Detective") ---
|
| 268 |
all_entities = []
|
| 269 |
-
# Process text in chunks to handle very long documents
|
| 270 |
chunk_size, overlap = 1024, 100
|
| 271 |
for i in range(0, len(text), chunk_size - overlap):
|
| 272 |
chunk = text[i : i + chunk_size]
|
| 273 |
chunk_entities = gliner_model.predict_entities(chunk, final_labels, threshold=threshold)
|
| 274 |
for ent in chunk_entities:
|
| 275 |
-
ent['start'] += i
|
| 276 |
-
ent['end'] += i
|
| 277 |
all_entities.append(ent)
|
| 278 |
|
| 279 |
-
# Deduplicate entities that might span across chunk overlaps
|
| 280 |
unique_entities = [dict(t) for t in {tuple(d.items()) for d in all_entities}]
|
| 281 |
-
debug_info.append(f"
|
| 282 |
|
| 283 |
-
# ---
|
| 284 |
highlighted_output_data = {
|
| 285 |
"text": text,
|
| 286 |
-
"entities": [{"start": ent["start"], "end": ent["end"], "
|
| 287 |
}
|
| 288 |
|
| 289 |
-
# --- 5. Prepare Detailed Table-Based Results ---
|
| 290 |
aggregated_matches = defaultdict(lambda: {'count': 0, 'scores': [], 'original_casing': ''})
|
| 291 |
-
|
| 292 |
for ent in unique_entities:
|
| 293 |
match_text = text[ent['start']:ent['end']]
|
| 294 |
-
# Use a key of (label, lowercase_text) to group similar items
|
| 295 |
key = (ent['label'], match_text.lower())
|
| 296 |
-
|
| 297 |
aggregated_matches[key]['count'] += 1
|
| 298 |
aggregated_matches[key]['scores'].append(ent['score'])
|
| 299 |
-
# Store the first-seen casing of the text
|
| 300 |
if not aggregated_matches[key]['original_casing']:
|
| 301 |
aggregated_matches[key]['original_casing'] = match_text
|
| 302 |
|
| 303 |
-
# Group aggregated results by label for final display
|
| 304 |
results_by_label = defaultdict(list)
|
| 305 |
for (label, _), data in aggregated_matches.items():
|
| 306 |
avg_score = np.mean(data['scores'])
|
| 307 |
-
results_by_label[label].append({
|
| 308 |
-
'text': data['original_casing'],
|
| 309 |
-
'count': data['count'],
|
| 310 |
-
'avg_score': avg_score
|
| 311 |
-
})
|
| 312 |
|
| 313 |
-
# --- 6. Build the Markdown String for the Detailed Table ---
|
| 314 |
markdown_string = ""
|
| 315 |
for label, items in sorted(results_by_label.items()):
|
| 316 |
markdown_string += f"### {label}\n"
|
| 317 |
-
markdown_string += "| Text Found | Instances
|
| 318 |
-
markdown_string += "|------------|-----------
|
| 319 |
-
|
| 320 |
-
# Sort items by count (most frequent first)
|
| 321 |
for item in sorted(items, key=lambda x: x['count'], reverse=True):
|
| 322 |
markdown_string += f"| {item['text']} | {item['count']} | {item['avg_score']:.2f} |\n"
|
| 323 |
markdown_string += "\n"
|
| 324 |
|
| 325 |
if not markdown_string:
|
| 326 |
-
markdown_string = "No entities found.
|
| 327 |
else:
|
| 328 |
-
markdown_string += "\n---\n<small><i>*<b>Confidence Score:</b> How sure the AI
|
| 329 |
|
| 330 |
-
debug_info.append("
|
| 331 |
|
| 332 |
-
# --- 7. Yield Final Results to UI ---
|
| 333 |
yield {
|
| 334 |
-
analyze_btn: gr.update(value="Analyze Text
|
| 335 |
analysis_status: gr.update(visible=False),
|
| 336 |
highlighted_text_output: highlighted_output_data,
|
| 337 |
detailed_results_output: markdown_string,
|
|
@@ -345,7 +308,6 @@ with gr.Blocks(title="Smart Text Analyzer", css=".prose { word-break: break-word
|
|
| 345 |
outputs=[generate_btn] + [comp for pair in dynamic_components for comp in pair]
|
| 346 |
)
|
| 347 |
|
| 348 |
-
# Functions for Select/Deselect All buttons
|
| 349 |
def deselect_all():
|
| 350 |
return gr.update(value=[])
|
| 351 |
def select_all(choices):
|
|
@@ -354,12 +316,14 @@ with gr.Blocks(title="Smart Text Analyzer", css=".prose { word-break: break-word
|
|
| 354 |
deselect_all_std_btn.click(fn=deselect_all, inputs=None, outputs=[standard_labels_checkbox])
|
| 355 |
select_all_std_btn.click(lambda: select_all(STANDARD_LABELS), inputs=None, outputs=[standard_labels_checkbox])
|
| 356 |
|
| 357 |
-
|
| 358 |
-
|
|
|
|
|
|
|
| 359 |
|
| 360 |
analyze_btn.click(
|
| 361 |
-
fn=
|
| 362 |
-
inputs=[text_input, standard_labels_checkbox, custom_labels_textbox, threshold_slider] + [cg for acc, cg,
|
| 363 |
outputs=[analyze_btn, analysis_status, highlighted_text_output, detailed_results_output, debug_output]
|
| 364 |
)
|
| 365 |
|
|
|
|
| 1 |
# 📚 Install dependencies
|
| 2 |
# Make sure to run this in your environment if you haven't already
|
| 3 |
+
# !pip install openai anthropic google-generativeai gradio transformers torch gliner numpy --quiet
|
| 4 |
|
| 5 |
# ⚙️ Imports
|
| 6 |
import openai
|
|
|
|
| 8 |
import google.generativeai as genai
|
| 9 |
import gradio as gr
|
| 10 |
from gliner import GLiNER
|
|
|
|
| 11 |
from collections import defaultdict, Counter
|
| 12 |
+
import numpy as np
|
| 13 |
import os
|
| 14 |
|
| 15 |
# 🧠 Supported models and their providers
|
|
|
|
| 24 |
|
| 25 |
# --- Load the model only once at startup ---
|
| 26 |
try:
|
| 27 |
+
print("Loading Extraction AI (GLiNER model)... This may take a moment.")
|
| 28 |
gliner_model = GLiNER.from_pretrained(GLINER_MODEL_NAME)
|
| 29 |
+
print("Extraction AI loaded successfully.")
|
| 30 |
except Exception as e:
|
| 31 |
print(f"FATAL ERROR: Could not load GLiNER model. The app will not be able to find entities. Error: {e}")
|
| 32 |
gliner_model = None
|
| 33 |
|
| 34 |
+
# 🧠 Prompt for the Conceptual AI to generate a research framework
|
| 35 |
+
FRAMEWORK_PROMPT_TEMPLATE = """
|
| 36 |
+
You are an expert research assistant specializing in history. For the provided topic: **"{topic}"**, your task is to generate a conceptual research framework.
|
| 37 |
|
| 38 |
**Instructions:**
|
| 39 |
+
1. Identify 4-6 high-level **Conceptual Categories** relevant to analyzing this historical topic (e.g., 'Key Figures', 'Core Ideologies', 'Significant Events').
|
| 40 |
+
2. For each category, list specific, searchable **Labels** that would appear in a primary or secondary source document.
|
| 41 |
+
3. **Crucial Rule for Labels:** Use concise, singular, and fundamental terms (e.g., use `Treaty` not `Diplomatic Treaties`).
|
| 42 |
|
| 43 |
**Output Format:**
|
| 44 |
+
Use Markdown. Each category must be a Level 3 Header (###), followed by a comma-separated list of its labels.
|
| 45 |
|
| 46 |
+
### Example Category: Political Actions
|
| 47 |
+
- Petition, Charter, Protest, Rally, Legislation
|
| 48 |
+
### Example Category: Social Groups
|
| 49 |
+
- Working Class, Aristocracy, Clergy
|
| 50 |
"""
|
| 51 |
|
| 52 |
+
# 🧠 Generator Function (The "Conceptual AI")
|
| 53 |
def generate_from_prompt(prompt, provider, key_dict):
|
| 54 |
provider_id = MODEL_OPTIONS.get(provider)
|
| 55 |
api_key = key_dict.get(f"{provider_id}_key")
|
|
|
|
| 73 |
|
| 74 |
# --- UI Definitions ---
|
| 75 |
|
|
|
|
| 76 |
STANDARD_LABELS = [
|
| 77 |
"PERSON", "ORGANIZATION", "LOCATION", "COUNTRY", "CITY", "STATE",
|
| 78 |
"NATIONALITY", "GROUP", "DATE", "EVENT", "LAW", "LEGAL_DOCUMENT",
|
|
|
|
| 80 |
"MONEY", "CURRENCY", "QUANTITY", "ORDINAL_NUMBER", "CARDINAL_NUMBER"
|
| 81 |
]
|
| 82 |
|
| 83 |
+
MAX_CATEGORIES = 8
|
| 84 |
|
| 85 |
+
with gr.Blocks(title="Historical Text Analysis Tool", css=".prose { word-break: break-word; }") as demo:
|
| 86 |
+
gr.Markdown("# Historical Text Analysis Tool")
|
| 87 |
gr.Markdown(
|
| 88 |
"""
|
| 89 |
+
This tool uses two forms of AI to accelerate historical research. First, a **Conceptual AI** generates a research framework with relevant search terms for your topic. Second, an **Extraction AI** scans your source text to find and highlight those terms with high precision.
|
| 90 |
+
"""
|
| 91 |
+
)
|
| 92 |
+
gr.Markdown(
|
| 93 |
+
"""
|
| 94 |
+
### Understanding "Entities" and "Labels"
|
| 95 |
+
In text analysis, this process is often called "Named Entity Recognition" (NER).
|
| 96 |
+
- An **Entity** is a specific piece of text in your document, like a name, a place, or a date (e.g., `Queen Victoria`, `1848`, `London`).
|
| 97 |
+
- A **Label** is the category that entity belongs to (e.g., `PERSON`, `DATE`, `LOCATION`).
|
| 98 |
|
| 99 |
+
This tool helps you define your labels and then automatically finds the corresponding entities in your text.
|
|
|
|
| 100 |
"""
|
| 101 |
)
|
| 102 |
|
| 103 |
+
gr.Markdown("--- \n## Step 1: Generate a Research Framework")
|
| 104 |
+
gr.Markdown("Enter a historical topic to get AI-suggested categories and labels for your analysis.")
|
| 105 |
with gr.Row():
|
| 106 |
+
topic = gr.Textbox(label="Enter a Historical Topic", placeholder="e.g., The Chartist Movement, The Protestant Reformation")
|
| 107 |
+
provider = gr.Dropdown(choices=list(MODEL_OPTIONS.keys()), label="Choose Conceptual AI Model")
|
| 108 |
with gr.Row():
|
| 109 |
openai_key = gr.Textbox(label="OpenAI API Key", type="password")
|
| 110 |
anthropic_key = gr.Textbox(label="Anthropic API Key", type="password")
|
| 111 |
google_key = gr.Textbox(label="Google API Key", type="password")
|
| 112 |
|
| 113 |
+
generate_btn = gr.Button("Generate Framework", variant="primary")
|
| 114 |
|
| 115 |
+
gr.Markdown("--- \n## Step 2: Define Labels and Analyze Source Text")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
+
gr.Markdown("#### 1. AI-Suggested Labels")
|
| 118 |
+
gr.Markdown("Review the suggested labels below. Select or deselect them as needed for your specific research goals.")
|
| 119 |
|
| 120 |
dynamic_components = []
|
| 121 |
with gr.Column():
|
| 122 |
for i in range(MAX_CATEGORIES):
|
| 123 |
+
with gr.Accordion(f"Suggested Category {i+1}", visible=False) as acc:
|
| 124 |
+
cg = gr.CheckboxGroup(label="Labels in this category", interactive=True)
|
| 125 |
with gr.Row():
|
| 126 |
+
select_btn = gr.Button("Select All", size="sm")
|
| 127 |
+
deselect_btn = gr.Button("Deselect All", size="sm")
|
| 128 |
+
dynamic_components.append((acc, cg, select_btn, deselect_btn))
|
|
|
|
| 129 |
|
| 130 |
+
gr.Markdown("#### 2. Standard Labels (Optional)")
|
| 131 |
with gr.Group():
|
| 132 |
standard_labels_checkbox = gr.CheckboxGroup(choices=STANDARD_LABELS, value=STANDARD_LABELS, label="Standard Entity Labels", info="Common categories like people, places, and dates.")
|
| 133 |
with gr.Row():
|
| 134 |
select_all_std_btn = gr.Button("Select All", size="sm")
|
| 135 |
deselect_all_std_btn = gr.Button("Deselect All", size="sm")
|
| 136 |
|
| 137 |
+
gr.Markdown("#### 3. Custom Labels (Optional)")
|
|
|
|
| 138 |
with gr.Group():
|
| 139 |
custom_labels_textbox = gr.Textbox(label="Enter Custom Labels (comma-separated)", placeholder="e.g., Technology, Weapon, Secret Society...")
|
| 140 |
|
| 141 |
+
gr.Markdown("--- \n## Step 3: Run Analysis")
|
| 142 |
+
threshold_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.4, step=0.05, label="Confidence Threshold", info="Controls the strictness of the Extraction AI. Lower values find more potential matches (less strict). Higher values return fewer, more precise matches (more strict).")
|
| 143 |
+
text_input = gr.Textbox(label="Paste Your Source Text Here for Analysis", lines=15, placeholder="Paste a historical document, an article, or a chapter...")
|
| 144 |
+
analyze_btn = gr.Button("Analyze Text", variant="primary")
|
| 145 |
|
| 146 |
+
analysis_status = gr.Markdown(visible=False)
|
| 147 |
|
| 148 |
+
gr.Markdown("--- \n## Step 4: Review Results")
|
| 149 |
gr.Markdown(
|
| 150 |
"""
|
| 151 |
+
✨ **Pro Tip: Add Labels Manually.**
|
| 152 |
+
If the AI missed an entity, you can add it yourself. In the **"Highlighted Text"** view, simply **click and drag to highlight any piece of text**. A dialog will appear, allowing you to assign it a new or existing label.
|
| 153 |
"""
|
| 154 |
)
|
| 155 |
|
|
|
|
| 157 |
with gr.TabItem("Highlighted Text"):
|
| 158 |
highlighted_text_output = gr.HighlightedText(label="Found Entities", interactive=True)
|
| 159 |
with gr.TabItem("Detailed Results"):
|
| 160 |
+
detailed_results_output = gr.Markdown(label="Aggregated List of Found Entities")
|
| 161 |
+
with gr.TabItem("Debug Log"):
|
| 162 |
+
debug_output = gr.Textbox(label="Extraction Process Log", interactive=False, lines=8)
|
| 163 |
|
| 164 |
# --- Backend Functions ---
|
| 165 |
|
| 166 |
def handle_generate(topic, provider, openai_k, anthropic_k, google_k):
|
| 167 |
yield {
|
| 168 |
+
generate_btn: gr.update(value="Generating...", interactive=False)
|
| 169 |
}
|
| 170 |
|
| 171 |
try:
|
| 172 |
+
key_dict = {"openai_key": os.environ.get("OPENAI_API_KEY", openai_k), "anthropic_key": os.environ.get("ANTHROPIC_API_KEY", anthropic_k), "google_key": os.environ.get("GOOGLE_API_KEY", google_k)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
provider_id = MODEL_OPTIONS.get(provider)
|
| 174 |
if not topic or not provider or not key_dict.get(f"{provider_id}_key"):
|
| 175 |
+
raise gr.Error("A topic, provider, and valid API Key for that provider are required.")
|
| 176 |
|
| 177 |
+
prompt = FRAMEWORK_PROMPT_TEMPLATE.format(topic=topic)
|
| 178 |
raw_framework = generate_from_prompt(prompt, provider, key_dict)
|
| 179 |
|
|
|
|
| 180 |
framework = defaultdict(list)
|
| 181 |
current_category = None
|
| 182 |
for line in raw_framework.split('\n'):
|
|
|
|
| 188 |
framework[current_category].extend([e.strip() for e in entities.split(',') if e.strip()])
|
| 189 |
|
| 190 |
if not framework:
|
| 191 |
+
raise gr.Error("The AI failed to generate categories. Please try again or rephrase your topic.")
|
| 192 |
|
| 193 |
updates = {}
|
| 194 |
categories = list(framework.items())
|
| 195 |
for i in range(MAX_CATEGORIES):
|
| 196 |
+
accordion_comp, checkbox_comp, sel_btn, desel_btn = dynamic_components[i]
|
| 197 |
if i < len(categories):
|
| 198 |
category_name, entities = categories[i]
|
|
|
|
| 199 |
sorted_entities = sorted(list(set(entities)))
|
| 200 |
updates[accordion_comp] = gr.update(label=f"Category: {category_name}", visible=True)
|
| 201 |
updates[checkbox_comp] = gr.update(choices=sorted_entities, value=sorted_entities, label="Suggested Labels", visible=True)
|
| 202 |
+
updates[sel_btn] = gr.update(visible=True)
|
| 203 |
+
updates[desel_btn] = gr.update(visible=True)
|
| 204 |
else:
|
| 205 |
updates[accordion_comp] = gr.update(visible=False)
|
| 206 |
+
updates[checkbox_comp] = gr.update(choices=[], value=[], visible=False)
|
| 207 |
+
updates[sel_btn] = gr.update(visible=False)
|
| 208 |
+
updates[desel_btn] = gr.update(visible=False)
|
| 209 |
|
| 210 |
+
updates[generate_btn] = gr.update(value="Generate Framework", interactive=True)
|
| 211 |
yield updates
|
| 212 |
except Exception as e:
|
| 213 |
+
yield {generate_btn: gr.update(value="Generate Framework", interactive=True)}
|
| 214 |
raise gr.Error(str(e))
|
| 215 |
|
| 216 |
+
def analyze_text(text, standard_labels, custom_label_text, threshold, *suggested_labels_from_groups):
|
|
|
|
| 217 |
yield {
|
| 218 |
+
analyze_btn: gr.update(value="Analyzing...", interactive=False),
|
| 219 |
+
analysis_status: gr.update(value="The Extraction AI is scanning your text. This may take a moment...", visible=True),
|
| 220 |
+
highlighted_text_output: None, detailed_results_output: None, debug_output: "Starting analysis..."
|
|
|
|
|
|
|
| 221 |
}
|
| 222 |
|
| 223 |
debug_info = []
|
| 224 |
if gliner_model is None:
|
| 225 |
+
raise gr.Error("Extraction AI (GLiNER model) is not loaded. Cannot analyze text. Please check logs and restart.")
|
| 226 |
|
|
|
|
| 227 |
labels_to_use = set()
|
|
|
|
| 228 |
for group in suggested_labels_from_groups:
|
| 229 |
if group: labels_to_use.update(group)
|
|
|
|
| 230 |
if standard_labels: labels_to_use.update(standard_labels)
|
|
|
|
| 231 |
custom = {l.strip() for l in custom_label_text.split(',') if l.strip()}
|
| 232 |
if custom: labels_to_use.update(custom)
|
| 233 |
|
| 234 |
final_labels = sorted(list(labels_to_use))
|
| 235 |
+
debug_info.append(f"Searching for {len(final_labels)} unique labels.")
|
| 236 |
+
debug_info.append(f"Confidence Threshold set to: {threshold}")
|
| 237 |
|
| 238 |
if not text or not final_labels:
|
| 239 |
yield {
|
| 240 |
+
analyze_btn: gr.update(value="Analyze Text", interactive=True),
|
| 241 |
analysis_status: gr.update(visible=False),
|
| 242 |
highlighted_text_output: {"text": text, "entities": []},
|
| 243 |
+
detailed_results_output: "Analysis stopped: Please provide text and select at least one label to search for.",
|
| 244 |
debug_output: "Analysis stopped: No text or no labels provided."
|
| 245 |
}
|
| 246 |
return
|
| 247 |
|
|
|
|
| 248 |
all_entities = []
|
|
|
|
| 249 |
chunk_size, overlap = 1024, 100
|
| 250 |
for i in range(0, len(text), chunk_size - overlap):
|
| 251 |
chunk = text[i : i + chunk_size]
|
| 252 |
chunk_entities = gliner_model.predict_entities(chunk, final_labels, threshold=threshold)
|
| 253 |
for ent in chunk_entities:
|
| 254 |
+
ent['start'] += i; ent['end'] += i
|
|
|
|
| 255 |
all_entities.append(ent)
|
| 256 |
|
|
|
|
| 257 |
unique_entities = [dict(t) for t in {tuple(d.items()) for d in all_entities}]
|
| 258 |
+
debug_info.append(f"Found {len(unique_entities)} raw entity mentions.")
|
| 259 |
|
| 260 |
+
# --- BUG FIX: Map 'label' to 'entity' for Gradio's HighlightedText component ---
|
| 261 |
highlighted_output_data = {
|
| 262 |
"text": text,
|
| 263 |
+
"entities": [{"start": ent["start"], "end": ent["end"], "entity": ent["label"]} for ent in unique_entities]
|
| 264 |
}
|
| 265 |
|
|
|
|
| 266 |
aggregated_matches = defaultdict(lambda: {'count': 0, 'scores': [], 'original_casing': ''})
|
|
|
|
| 267 |
for ent in unique_entities:
|
| 268 |
match_text = text[ent['start']:ent['end']]
|
|
|
|
| 269 |
key = (ent['label'], match_text.lower())
|
|
|
|
| 270 |
aggregated_matches[key]['count'] += 1
|
| 271 |
aggregated_matches[key]['scores'].append(ent['score'])
|
|
|
|
| 272 |
if not aggregated_matches[key]['original_casing']:
|
| 273 |
aggregated_matches[key]['original_casing'] = match_text
|
| 274 |
|
|
|
|
| 275 |
results_by_label = defaultdict(list)
|
| 276 |
for (label, _), data in aggregated_matches.items():
|
| 277 |
avg_score = np.mean(data['scores'])
|
| 278 |
+
results_by_label[label].append({'text': data['original_casing'], 'count': data['count'], 'avg_score': avg_score})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
|
|
|
| 280 |
markdown_string = ""
|
| 281 |
for label, items in sorted(results_by_label.items()):
|
| 282 |
markdown_string += f"### {label}\n"
|
| 283 |
+
markdown_string += "| Text Found | Instances | Avg. Confidence Score* |\n"
|
| 284 |
+
markdown_string += "|------------|-----------|--------------------------|\n"
|
|
|
|
|
|
|
| 285 |
for item in sorted(items, key=lambda x: x['count'], reverse=True):
|
| 286 |
markdown_string += f"| {item['text']} | {item['count']} | {item['avg_score']:.2f} |\n"
|
| 287 |
markdown_string += "\n"
|
| 288 |
|
| 289 |
if not markdown_string:
|
| 290 |
+
markdown_string = "No entities found. Consider lowering the confidence threshold or refining your labels."
|
| 291 |
else:
|
| 292 |
+
markdown_string += "\n---\n<small><i>*<b>Confidence Score:</b> How sure the Extraction AI is that it found the correct label (1.00 = 100% certain). The score is an average across all instances of that text.</i></small>"
|
| 293 |
|
| 294 |
+
debug_info.append("Analysis complete.")
|
| 295 |
|
|
|
|
| 296 |
yield {
|
| 297 |
+
analyze_btn: gr.update(value="Analyze Text", interactive=True),
|
| 298 |
analysis_status: gr.update(visible=False),
|
| 299 |
highlighted_text_output: highlighted_output_data,
|
| 300 |
detailed_results_output: markdown_string,
|
|
|
|
| 308 |
outputs=[generate_btn] + [comp for pair in dynamic_components for comp in pair]
|
| 309 |
)
|
| 310 |
|
|
|
|
| 311 |
def deselect_all():
|
| 312 |
return gr.update(value=[])
|
| 313 |
def select_all(choices):
|
|
|
|
| 316 |
deselect_all_std_btn.click(fn=deselect_all, inputs=None, outputs=[standard_labels_checkbox])
|
| 317 |
select_all_std_btn.click(lambda: select_all(STANDARD_LABELS), inputs=None, outputs=[standard_labels_checkbox])
|
| 318 |
|
| 319 |
+
# Wire up the dynamic select/deselect buttons
|
| 320 |
+
for _, cg, sel_btn, desel_btn in dynamic_components:
|
| 321 |
+
sel_btn.click(fn=select_all, inputs=[cg], outputs=[cg])
|
| 322 |
+
desel_btn.click(fn=deselect_all, inputs=None, outputs=[cg])
|
| 323 |
|
| 324 |
analyze_btn.click(
|
| 325 |
+
fn=analyze_text,
|
| 326 |
+
inputs=[text_input, standard_labels_checkbox, custom_labels_textbox, threshold_slider] + [cg for acc, cg, sel, desel in dynamic_components],
|
| 327 |
outputs=[analyze_btn, analysis_status, highlighted_text_output, detailed_results_output, debug_output]
|
| 328 |
)
|
| 329 |
|