Generate a CLI app (use Textual and Rich) that takes a selection of Arabic textual witnesses and uses AI to segment them into Narratvie units and then aligns them, giving each aligned set of units across the witness a unique title. The app has to allow for iterative refinement across the process to improve the segmentation and alignment and needs clear evaluation metrics for each step.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a prototype—for a production system, you’d want to expand the AI segmentation/alignment logic, add persistent storage, and possibly integrate with a more robust backend.
1. Install Requirements
bash
pip install textual rich openai
2. Code: arabic_narrative_aligner.py
python
import sys
import asyncio
from typing import List, Dict, Any
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, Button, Static, Input, DataTable
from textual.containers import Horizontal, Vertical
from rich.table import Table
from rich.panel import Panel
from rich.console import Console
import openai
# --- AI Segmentation/Alignment Stubs (Replace with your own or OpenAI API) ---
def ai_segment(text: str) -> List[str]:
"""
Use AI to segment Arabic text into narrative units.
Replace with your own model or OpenAI API call.
"""
# For demo: split by paragraph
return [seg.strip() for seg in text.split('\n\n') if seg.strip()]
def ai_align(segments_list: List[List[str]]) -> List[List[str]]:
"""
Use AI to align narrative units across witnesses.
Returns a list of aligned sets (each set is a list of units, one per witness).
"""
# For demo: naive alignment by index
max_len = max(len(s) for s in segments_list)
aligned = []
for i in range(max_len):
aligned.append([segments[i] if i < len(segments) else "" for segments in segments_list])
return aligned
def ai_title(aligned_set: List[str]) -> str:
"""
Use AI to generate a unique title for an aligned set of narrative units.
"""
# For demo: use first 5 words of first non-empty unit
for unit in aligned_set:
if unit.strip():
return " ".join(unit.split()[:5]) + "..."
return "Untitled"
# --- Evaluation Metrics ---
def evaluate_segmentation(segments: List[str]) -> Dict[str, Any]:
return {
"num_units": len(segments),
"avg_length": sum(len(s) for s in segments) / len(segments) if segments else 0
}
def evaluate_alignment(aligned: List[List[str]]) -> Dict[str, Any]:
completeness = sum(1 for row in aligned for cell in row if cell.strip()) / (len(aligned) * len(aligned[0]))
return {
"num_aligned_sets": len(aligned),
"completeness": f"{completeness*100:.1f}%"
}
# --- Textual App ---
class NarrativeAlignerApp(App):
CSS_PATH = "styles.css"
BINDINGS = [("q", "quit", "Quit")]
def __init__(self):
super().__init__()
self.witnesses: Dict[str, str] = {} # name -> text
self.segments: Dict[str, List[str]] = {}
self.aligned: List[List[str]] = []
self.titles: List[str] = []
self.console = Console()
def compose(self) -> ComposeResult:
yield Header()
yield Footer()
yield Static("Arabic Narrative Aligner", id="title")
yield Input(placeholder="Enter witness name...", id="witness_name")
yield Input(placeholder="Paste Arabic text here...", id="witness_text", multiline=True)
yield Button("Add Witness", id="add_witness")
yield Button("Segment & Align", id="segment_align")
yield Button("Refine Alignment", id="refine")
yield Button("Show Metrics", id="metrics")
yield DataTable(id="alignment_table")
async def on_button_pressed(self, event):
if event.button.id == "add_witness":
name = self.query_one("#witness_name", Input).value.strip()
text = self.query_one("#witness_text", Input).value.strip()
if name and text:
self.witnesses[name] = text
self.console.print(f"[green]Added witness:[/green] {name}")
self.query_one("#witness_name", Input).value = ""
self.query_one("#witness_text", Input).value = ""
elif event.button.id == "segment_align":
await self.segment_and_align()
elif event.button.id == "refine":
await self.refine_alignment()
elif event.button.id == "metrics":
self.show_metrics()
async def segment_and_align(self):
# Segment
self.segments = {name: ai_segment(text) for name, text in self.witnesses.items()}
# Align
segments_list = [self.segments[name] for name in self.witnesses]
self.aligned = ai_align(segments_list)
# Titles
self.titles = [ai_title(row) for row in self.aligned]
self.show_alignment_table()
async def refine_alignment(self):
# For demo: allow user to manually edit alignment in future
self.console.print("[yellow]Refinement not implemented in demo.[/yellow]")
def show_alignment_table(self):
table = self.query_one("#alignment_table", DataTable)
table.clear()
headers = ["Title"] + list(self.witnesses.keys())
table.add_columns(*headers)
for title, row in zip(self.titles, self.aligned):
table.add_row(title, *row)
def show_metrics(self):
# Segmentation metrics
seg_metrics = {name: evaluate_segmentation(segs) for name, segs in self.segments.items()}
align_metrics = evaluate_alignment(self.aligned) if self.aligned else {}
self.console.print(Panel(f"[bold]Segmentation Metrics:[/bold]\n{seg_metrics}\n\n[bold]Alignment Metrics:[/bold]\n{align_metrics}"))
if __name__ == "__main__":
app = NarrativeAlignerApp()
app.run()
3. Usage
Run the app: python arabic_narrative_aligner.py
Add witnesses:
Enter a name and paste Arabic text, then click "Add Witness".
Repeat for each witness.
Segment & Align:
Click "Segment & Align" to run AI segmentation and alignment.
The table will show aligned narrative units with generated titles.
Refine Alignment:
(Stub for now; you can expand this to allow manual editing.)
Show Metrics:
Click "Show Metrics" to see segmentation and alignment evaluation.
4. Notes
AI Integration:
Replace the ai_segment, ai_align, and ai_title stubs with calls to your preferred AI model (e.g., OpenAI GPT, HuggingFace models) for better results.
Iterative Refinement:
You can expand the "Refine Alignment" button to allow users to merge/split units, re-align, or edit titles.
Evaluation Metrics:
The metrics are basic; you can add BLEU, ROUGE, or custom metrics for alignment quality.
Textual UI:
This is a minimal UI. You can enhance it with more widgets, better navigation, and persistent storage.
Let me know if you want a more advanced AI integration, or a more detailed UI for manual refinement!