File size: 8,459 Bytes
0e9bb01
 
 
 
c3b461c
 
7539685
c3b461c
0e9bb01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4383904
0e9bb01
 
 
4383904
0e9bb01
 
 
 
c3b461c
0e9bb01
 
 
 
7539685
c3b461c
7539685
c3b461c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7539685
c3b461c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
"""
Formatting tools for displaying analysis results with rich formatting.
"""

import os
import tempfile
import traceback
from typing import Dict, Any, Tuple
from loguru import logger
from smolagents import Tool
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.table import Table
from rich.theme import Theme
from rich.box import ROUNDED
from rich.console import Group


class FormatAnalysisResultsTool(Tool):
    """Tool for formatting analysis results"""
    
    name = "format_analysis_results"
    description = "Formats the analysis results for better readability"
    inputs = {
        "analysis_json": {"type": "any", "description": "JSON string or dictionary containing the analysis results"}
    }
    output_type = "string"
    
    def forward(self, analysis_json: Dict) -> str:
        """
        Formats the analysis results for better readability.
        
        Args:
            analysis_json: Dictionary containing the analysis results
            
        Returns:
            A formatted string representation of the analysis
        """
            
        analysis = analysis_json
            
        logger.debug(f"Analysis structure keys: {list(analysis.keys()) if isinstance(analysis, dict) else 'Not a dictionary'}")
        
        try:
            return self._format_rich(analysis)
        except Exception as e:
            error_traceback = traceback.format_exc()
            logger.error(f"Error in rich formatting: {str(e)}\nTraceback:\n{error_traceback}")
            self._log_analysis_debug_info(analysis)
            # Return error message instead of falling back to simple formatting
            return f"Error formatting analysis results: {str(e)}"

    
    def _log_analysis_debug_info(self, analysis: Dict) -> None:
        """Log debug information about the analysis dictionary"""
        if isinstance(analysis, dict):
            for key, value in analysis.items():
                logger.debug(f"Key: {key}, Value type: {type(value)}, Value: {str(value)[:100]}{'...' if len(str(value)) > 100 else ''}")
    
    def _create_rich_console(self) -> Tuple[Console, Any]:
        """Create and configure a Rich console with a temporary file"""
        logger.debug("Starting rich formatting")
        temp_file = tempfile.NamedTemporaryFile(mode='w+', encoding='utf-8', delete=False)
        # Reduce console width for better display in Gradio UI
        console = Console(file=temp_file, width=70)
        
        # Create a custom theme for consistent styling
        custom_theme = Theme({
            "heading": "bold cyan underline",
            "highlight": "bold yellow",
            "positive": "green",
            "negative": "red",
            "neutral": "magenta",
            "quote": "italic yellow",
            "metadata": "dim white",
            "conclusion": "bold magenta"
        })
        
        # Apply the theme to our console
        console.theme = custom_theme
        return console, temp_file
    
    def _format_summary(self, console: Console, analysis: Dict) -> None:
        """Format and print the summary section"""
        summary = analysis.get("summary", "No summary available")
        logger.debug(f"Summary content: {summary if summary else 'Not available'}")
        console.print(Panel(
            Text(summary, justify="center"), 
            title="[heading]Song Analysis[/]", 
            subtitle="[metadata]Summary[/]",
            expand=True  # Расширять панель на всю доступную ширину
        ))
    
    def _format_info_table(self, console: Console, analysis: Dict) -> None:
        """Format and print the info table with themes and mood"""
        info_table = Table(show_header=False, box=ROUNDED, expand=True)
        info_table.add_column("Key", style="bold blue")
        info_table.add_column("Value")
        
        # Add the mood
        mood = analysis.get("mood", "Not specified")
        logger.debug(f"Mood content: {mood if mood else 'Not specified'}")
        info_table.add_row("Mood", mood)
        
        # Add the themes as a comma-separated list
        themes = analysis.get("main_themes", [])
        logger.debug(f"Themes: {themes if themes else 'Not available'}")
        if themes:
            themes_text = ", ".join([f"[highlight]{theme}[/]" for theme in themes])
            info_table.add_row("Main Themes", themes_text)
        
        console.print(info_table)
    
    def _format_section(self, console: Console, section: Dict) -> None:
        """Format and print a single section"""
        section_type = section.get("section_type", "Unknown")
        section_number = section.get("section_number", "")
        logger.debug(f"Processing section: {section_type} {section_number}")
        section_title = f"{section_type.title()} {section_number}" if section_number else section_type.title()
        
        section_analysis = section.get("analysis", "No analysis available")
        lines = section.get("lines", [])
        logger.debug(f"Section lines count: {len(lines) if lines else 0}")
        
        # Create a group with the lyrics and analysis
        section_content = []
        
        if lines:
            # Format lyrics in a more readable way
            section_content.append(Text("Lyrics:", style="bold blue"))
            # Format each lyrics line with the quote style
            lyrics_lines = []
            for line in lines:
                lyrics_lines.append(f"[quote]{line}[/]")
            
            lyrics_panel = Panel(
                "\n".join(lyrics_lines),
                border_style="blue",
                padding=(1, 2),
                expand=True  # Расширять панель на всю доступную ширину
            )
            section_content.append(lyrics_panel)
        
        section_content.append(Text("Analysis:", style="bold blue"))
        section_content.append(Text(section_analysis))
        
        # Add the section panel
        console.print(Panel(
            Group(*section_content),
            title=f"[bold cyan]{section_title}[/]",
            border_style="cyan",
            expand=True  # Расширять панель на всю доступную ширину
        ))
    
    def _format_sections(self, console: Console, analysis: Dict) -> None:
        """Format and print all sections"""
        sections = analysis.get("sections_analysis", [])
        logger.debug(f"Sections count: {len(sections) if sections else 0}")
        if sections:
            console.print("\n[heading]Section-by-Section Analysis[/]")
            for section in sections:
                self._format_section(console, section)
    
    def _format_conclusion(self, console: Console, analysis: Dict) -> None:
        """Format and print the conclusion"""
        conclusion = analysis.get("conclusion", "No conclusion available")
        logger.debug(f"Conclusion content: {conclusion if conclusion else 'Not available'}")
        console.print("\n[heading]Conclusion[/]")
        console.print(Panel(
            Text(conclusion, justify="left"), 
            border_style="magenta",
            expand=True  # Расширять панель на всю доступную ширину
        ))
    
    def _format_rich(self, analysis: Dict) -> str:
        """Format the analysis using rich formatting"""
        console, temp_file = self._create_rich_console()
        
        # Format each section
        self._format_summary(console, analysis)
        self._format_info_table(console, analysis)
        self._format_sections(console, analysis)
        self._format_conclusion(console, analysis)
        
        # Save output to file and read back as string
        temp_file.close()
        with open(temp_file.name, 'r', encoding='utf-8') as f:
            result = f.read()
        
        # Градио не поддерживает HTML-теги pre, поэтому просто возвращаем текст как есть
        # Текстовое форматирование Rich уже содержит необходимые отступы и пробелы
        
        # Clean up the temp file
        try:
            os.unlink(temp_file.name)
        except Exception as e:
            logger.warning(f"Could not delete temporary file {temp_file.name}: {str(e)}")
        
        return result