operations / services /text /formatters.py
jbbove's picture
Updated the adapter and the agent workflow (node, state, registry etc.). Updated web app, currently supporting omirl scraping
b6145cd
# services/text/formatters.py
"""
Text Formatting Utilities
This module provides text formatting utilities for operational data,
including filter descriptions, metadata formatting, and standardized
text representations.
Purpose:
- Format filter information for display and logging
- Standardize text representations of operational data
- Provide consistent formatting across services
- Support localization (future)
Dependencies:
- typing: For type hints
Called by:
- tools/*/adapter.py: Main tool adapters for text formatting
- services/*: Other services needing text formatting
- Direct usage: UI components and reports
"""
from typing import Dict, Any, List, Optional
def format_applied_filters(filters: Dict[str, Any], language: str = "it") -> str:
"""
Format applied filters for metadata and display
Args:
filters: Dictionary of applied filters
language: Language for formatting ("it" for Italian, "en" for English)
Returns:
Formatted string describing applied filters
Example:
filters = {"tipo_sensore": "Precipitazione", "provincia": "GENOVA"}
result = format_applied_filters(filters)
# Returns: "tipo_sensore=Precipitazione, provincia=GENOVA"
"""
if not filters:
return "Nessun filtro applicato" if language == "it" else "No filters applied"
filter_parts = []
for key, value in filters.items():
if value is not None and str(value).strip():
filter_parts.append(f"{key}={value}")
if not filter_parts:
return "Nessun filtro applicato" if language == "it" else "No filters applied"
return ", ".join(filter_parts)
def format_filter_summary(filters: Dict[str, Any], language: str = "it") -> str:
"""
Format filters into a human-readable summary
Args:
filters: Dictionary of applied filters
language: Language for formatting
Returns:
Human-readable filter summary
Example:
filters = {"tipo_sensore": "Precipitazione", "provincia": "GENOVA"}
result = format_filter_summary(filters)
# Returns: "Filtri: Sensore Precipitazione, Provincia GENOVA"
"""
if not filters:
return ""
parts = []
if filters.get("tipo_sensore"):
if language == "it":
parts.append(f"Sensore {filters['tipo_sensore']}")
else:
parts.append(f"Sensor {filters['tipo_sensore']}")
if filters.get("provincia"):
if language == "it":
parts.append(f"Provincia {filters['provincia']}")
else:
parts.append(f"Province {filters['provincia']}")
if filters.get("comune"):
if language == "it":
parts.append(f"Comune {filters['comune']}")
else:
parts.append(f"Municipality {filters['comune']}")
if parts:
prefix = "Filtri: " if language == "it" else "Filters: "
return prefix + ", ".join(parts)
return ""
def format_data_summary(
count: int,
data_type: str = "records",
language: str = "it"
) -> str:
"""
Format a summary of data count and type
Args:
count: Number of records/items
data_type: Type of data (e.g., "stations", "alerts", "records")
language: Language for formatting
Returns:
Formatted data summary
"""
if language == "it":
type_translations = {
"stations": "stazioni",
"records": "record",
"alerts": "allerte",
"measurements": "misurazioni"
}
translated_type = type_translations.get(data_type, data_type)
if count == 0:
return f"Nessuna {translated_type} trovata"
elif count == 1:
return f"1 {translated_type} trovata"
else:
return f"{count} {translated_type} trovate"
else:
if count == 0:
return f"No {data_type} found"
elif count == 1:
return f"1 {data_type} found"
else:
return f"{count} {data_type} found"
def format_timestamp(
timestamp: Optional[str] = None,
format_type: str = "time_only",
language: str = "it"
) -> str:
"""
Format timestamp for display
Args:
timestamp: ISO timestamp string (defaults to current time)
format_type: "time_only", "date_time", "date_only"
language: Language for formatting
Returns:
Formatted timestamp string
"""
from datetime import datetime
if timestamp:
try:
dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
except:
dt = datetime.now()
else:
dt = datetime.now()
if format_type == "time_only":
return dt.strftime("%H:%M:%S")
elif format_type == "date_only":
return dt.strftime("%d/%m/%Y")
else: # date_time
return dt.strftime("%d/%m/%Y %H:%M:%S")