193 lines
7.8 KiB
Python
193 lines
7.8 KiB
Python
from typing import Dict, Any
|
|
|
|
|
|
class DisplayFormatter:
|
|
"""Utility class for formatting display output"""
|
|
|
|
@staticmethod
|
|
def format_sentiment_result(result: Dict[str, Any]) -> str:
|
|
"""Format sentiment analysis result for display"""
|
|
if "error" in result:
|
|
return f"❌ {result['error']}"
|
|
|
|
sentiment = result["sentiment"]
|
|
confidence = result["confidence"]
|
|
emoji = "😊" if sentiment == "positive" else "😞"
|
|
|
|
return f"{emoji} Sentiment: {sentiment}\n📊 Confidence: {confidence:.2%}"
|
|
|
|
@staticmethod
|
|
def show_loading(message: str = "Analysis in progress..."):
|
|
"""Show loading message"""
|
|
print(f"\n🔍 {message}")
|
|
|
|
@staticmethod
|
|
def show_warning(message: str):
|
|
"""Show warning message"""
|
|
print(f"⚠️ {message}")
|
|
|
|
@staticmethod
|
|
def show_error(message: str):
|
|
"""Show error message"""
|
|
print(f"❌ {message}")
|
|
|
|
@staticmethod
|
|
def show_success(message: str):
|
|
"""Show success message"""
|
|
print(f"✅ {message}")
|
|
|
|
@staticmethod
|
|
def format_fillmask_result(result: Dict[str, Any]) -> str:
|
|
"""Format fill-mask prediction result for display"""
|
|
if "error" in result:
|
|
return f"❌ {result['error']}"
|
|
|
|
output = []
|
|
output.append(f"📝 Original: {result['original_text']}")
|
|
output.append(f"🎭 Masks found: {result['masks_count']}")
|
|
output.append("")
|
|
|
|
if result['masks_count'] == 1:
|
|
# Single mask
|
|
output.append("🔮 Predictions:")
|
|
for i, pred in enumerate(result['predictions'], 1):
|
|
confidence_bar = "█" * int(pred['score'] * 10)
|
|
output.append(f" {i}. '{pred['token']}' ({pred['score']:.1%}) {confidence_bar}")
|
|
output.append(f" → {pred['sequence']}")
|
|
else:
|
|
# Multiple masks
|
|
for mask_info in result['predictions']:
|
|
output.append(f"🔮 Mask #{mask_info['mask_position']} predictions:")
|
|
for i, pred in enumerate(mask_info['predictions'], 1):
|
|
confidence_bar = "█" * int(pred['score'] * 10)
|
|
output.append(f" {i}. '{pred['token']}' ({pred['score']:.1%}) {confidence_bar}")
|
|
output.append("")
|
|
|
|
return "\n".join(output)
|
|
|
|
@staticmethod
|
|
def format_textgen_result(result: Dict[str, Any]) -> str:
|
|
"""Format text generation result for display"""
|
|
if "error" in result:
|
|
return f"❌ {result['error']}"
|
|
|
|
output = []
|
|
output.append(f"📝 Prompt: {result['prompt']}")
|
|
output.append(f"⚙️ Parameters: max_length={result['parameters']['max_length']}, "
|
|
f"temperature={result['parameters']['temperature']}")
|
|
output.append("-" * 50)
|
|
|
|
for i, gen in enumerate(result['generations'], 1):
|
|
if len(result['generations']) > 1:
|
|
output.append(f"🎯 Generation {i}:")
|
|
|
|
output.append(f"📄 Full text: {gen['text']}")
|
|
if gen['continuation']:
|
|
output.append(f"✨ Continuation: {gen['continuation']}")
|
|
|
|
if i < len(result['generations']):
|
|
output.append("-" * 30)
|
|
|
|
return "\n".join(output)
|
|
|
|
@staticmethod
|
|
def format_moderation_result(result: Dict[str, Any]) -> str:
|
|
"""Format content moderation result for display"""
|
|
if "error" in result:
|
|
return f"❌ {result['error']}"
|
|
|
|
output = []
|
|
output.append(f"📝 Original: {result['original_text']}")
|
|
|
|
if result['is_modified']:
|
|
output.append(f"🛡️ Moderated: {result['moderated_text']}")
|
|
output.append(f"⚠️ Status: Content modified ({result['words_replaced']} words replaced)")
|
|
status_emoji = "🔴"
|
|
else:
|
|
output.append("✅ Status: Content approved (no modifications needed)")
|
|
status_emoji = "🟢"
|
|
|
|
# Toxicity score bar
|
|
score = result['toxic_score']
|
|
score_bar = "█" * int(score * 10)
|
|
output.append(f"{status_emoji} Toxicity Score: {score:.1%} {score_bar}")
|
|
|
|
return "\n".join(output)
|
|
|
|
@staticmethod
|
|
def format_ner_result(result: Dict[str, Any]) -> str:
|
|
"""Format NER result for display"""
|
|
if "error" in result:
|
|
return f"❌ {result['error']}"
|
|
|
|
output = []
|
|
output.append(f"📝 Original: {result['original_text']}")
|
|
output.append(f"✨ Highlighted: {result['highlighted_text']}")
|
|
output.append(f"🎯 Found {result['total_entities']} entities (threshold: {result['confidence_threshold']:.2f})")
|
|
|
|
if result['entities']:
|
|
output.append("\n📋 Detected Entities:")
|
|
for entity in result['entities']:
|
|
confidence_bar = "█" * int(entity['confidence'] * 10)
|
|
output.append(f" {entity['emoji']} {entity['text']} → {entity['label']} "
|
|
f"({entity['confidence']:.1%}) {confidence_bar}")
|
|
|
|
if result['entity_stats']:
|
|
output.append("\n📊 Entity Statistics:")
|
|
for entity_type, stats in result['entity_stats'].items():
|
|
unique_entities = list(set(stats['entities']))
|
|
emoji = result['entities'][0]['emoji'] if result['entities'] else "🏷️"
|
|
for ent in result['entities']:
|
|
if ent['label'] == entity_type:
|
|
emoji = ent['emoji']
|
|
break
|
|
|
|
output.append(f" {emoji} {entity_type}: {stats['count']} occurrences")
|
|
if len(unique_entities) <= 3:
|
|
output.append(f" → {', '.join(unique_entities)}")
|
|
else:
|
|
output.append(f" → {', '.join(unique_entities[:3])}... (+{len(unique_entities)-3} more)")
|
|
|
|
return "\n".join(output)
|
|
|
|
@staticmethod
|
|
def format_ner_analysis(result: Dict[str, Any]) -> str:
|
|
"""Format comprehensive NER document analysis"""
|
|
if "error" in result:
|
|
return f"❌ {result['error']}"
|
|
|
|
output = []
|
|
output.append("📊 Document Analysis Results")
|
|
output.append("=" * 50)
|
|
|
|
# Document statistics
|
|
stats = result['document_stats']
|
|
output.append(f"📄 Document: {stats['word_count']} words, {stats['char_count']} characters")
|
|
output.append(f"📝 Structure: ~{stats['sentence_count']} sentences")
|
|
output.append(f"🎯 Entity Density: {stats['entity_density']:.2%} (entities per word)")
|
|
|
|
# Most common entity type
|
|
if 'most_common_entity_type' in result:
|
|
common = result['most_common_entity_type']
|
|
output.append(f"🏆 Most Common: {common['emoji']} {common['type']} ({common['count']} occurrences)")
|
|
|
|
output.append(f"\n✨ Highlighted Text:")
|
|
output.append(result['highlighted_text'])
|
|
|
|
if result['entity_stats']:
|
|
output.append(f"\n📈 Detailed Statistics:")
|
|
for entity_type, stats in result['entity_stats'].items():
|
|
unique_entities = list(set(stats['entities']))
|
|
emoji = "🏷️"
|
|
for ent in result['entities']:
|
|
if ent['label'] == entity_type:
|
|
emoji = ent['emoji']
|
|
break
|
|
|
|
output.append(f"\n{emoji} {entity_type} ({stats['count']} total):")
|
|
for entity in unique_entities:
|
|
count = stats['entities'].count(entity)
|
|
output.append(f" • {entity} ({count}x)")
|
|
|
|
return "\n".join(output)
|