File size: 12,621 Bytes
5e0ae28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"""
Main Gradio application interface
"""
import gradio as gr
from src.core.reasoner import AdvancedReasoner
from src.core.prompt_engine import PromptEngine
from src.config.settings import AppConfig
from src.config.constants import ReasoningMode, ModelConfig
from src.ui.components import UIComponents
from src.ui.handlers import EventHandlers
from src.ui.styles import SIDEBAR_CSS
from src.utils.logger import logger


def create_ui() -> gr.Blocks:
    """
    🎨 CREATE ENHANCED GRADIO INTERFACE
    """
    
    # Initialize reasoner and components
    reasoner = AdvancedReasoner()
    components = UIComponents()
    handlers = EventHandlers(reasoner)
    
    with gr.Blocks(
        theme=gr.themes.Soft(
            primary_hue=AppConfig.THEME_PRIMARY,
            secondary_hue=AppConfig.THEME_SECONDARY,
            font=gr.themes.GoogleFont("Inter")
        ),
        css=SIDEBAR_CSS,
        title="Advanced AI Reasoning System Pro"
    ) as demo:
        
        # Header
        gr.HTML(components.get_header_html())
        
        # Main Tabs
        with gr.Tabs():
            
            # ==================== TAB 1: REASONING WORKSPACE ====================
            with gr.Tab("🧠 Reasoning Workspace"):
                with gr.Row():
                    
                    # Main Chat Area
                    with gr.Column(scale=4):
                        chatbot = gr.Chatbot(
                            label="πŸ’¬ Reasoning Workspace",
                            height=750,
                            show_copy_button=True,
                            type="messages",
                            avatar_images=(
                                "https://api.dicebear.com/7.x/avataaars/svg?seed=User",
                                "https://api.dicebear.com/7.x/bottts/svg?seed=AI"
                            ),
                            bubble_full_width=False
                        )
                        
                        msg = gr.Textbox(
                            placeholder="πŸ’­ Enter your complex problem or research question... (Max 10,000 characters)",
                            label="Query Input",
                            lines=3,
                            max_lines=10,
                            show_label=False
                        )
                        
                        with gr.Row():
                            submit_btn = gr.Button("πŸš€ Process", variant="primary", scale=2, size="lg")
                            clear_btn = gr.Button("πŸ—‘οΈ Clear", scale=1, size="lg")
                            pdf_btn = gr.Button("πŸ“„ Download PDF", scale=1, size="lg", variant="secondary")
                            toggle_sidebar_btn = gr.Button("βš™οΈ Settings", scale=1, size="lg", variant="secondary")
                    
                    # Collapsible Sidebar
                    with gr.Column(scale=1, visible=True, elem_classes="settings-column") as sidebar:
                        gr.Markdown("### βš™οΈ Configuration")
                        
                        reasoning_mode = gr.Radio(
                            choices=components.get_reasoning_mode_choices(),
                            value=ReasoningMode.TREE_OF_THOUGHTS.value,
                            label="🧠 Reasoning Method",
                            info="Select your preferred reasoning strategy"
                        )
                        
                        prompt_template = gr.Dropdown(
                            choices=components.get_prompt_template_choices(),
                            value="Custom",
                            label="πŸ“ Prompt Template",
                            info="Pre-built prompt templates for common tasks"
                        )
                        
                        enable_critique = gr.Checkbox(
                            label="πŸ” Enable Self-Critique",
                            value=True,
                            info="Add automatic validation and correction phase"
                        )
                        
                        use_cache = gr.Checkbox(
                            label="πŸ’Ύ Use Response Cache",
                            value=True,
                            info="Cache responses for faster repeated queries"
                        )
                        
                        model = gr.Dropdown(
                            choices=components.get_model_choices(),
                            value=ModelConfig.LLAMA_70B.model_id,
                            label="πŸ€– AI Model",
                            info="Select the AI model to use"
                        )
                        
                        with gr.Accordion("πŸŽ›οΈ Advanced Settings", open=False):
                            temperature = gr.Slider(
                                AppConfig.MIN_TEMPERATURE, 
                                AppConfig.MAX_TEMPERATURE, 
                                value=AppConfig.DEFAULT_TEMPERATURE, 
                                step=0.1,
                                label="🌑️ Temperature",
                                info="Higher = more creative, Lower = more focused"
                            )
                            
                            max_tokens = gr.Slider(
                                AppConfig.MIN_TOKENS, 
                                8000, 
                                value=AppConfig.DEFAULT_MAX_TOKENS, 
                                step=500,
                                label="πŸ“Š Max Tokens",
                                info="Maximum response length"
                            )
                        
                        gr.Markdown("### πŸ“Š Live Metrics")
                        metrics_display = gr.Markdown(value=components.get_metrics_html(reasoner))
                        
                        with gr.Accordion("ℹ️ System Info", open=False):
                            gr.Markdown(components.get_system_info_html(reasoner))
                
                # PDF download output
                pdf_file_output = gr.File(
                    label="πŸ“₯ Download Your PDF Report", 
                    visible=True,
                    file_types=[".pdf"]
                )
            
            # ==================== TAB 2: EXPORT & HISTORY ====================
            with gr.Tab("πŸ“€ Export & History"):
                gr.Markdown("### πŸ“€ Export Conversation History")
                gr.Markdown("Export your conversations in multiple formats with optional metadata.")
                
                with gr.Row():
                    export_format = gr.Radio(
                        choices=["json", "markdown", "txt", "pdf"],
                        value="markdown",
                        label="πŸ“„ Export Format",
                        info="Choose your preferred export format"
                    )
                    include_meta = gr.Checkbox(
                        label="πŸ“‹ Include Metadata",
                        value=True,
                        info="Include timestamps, models, and performance metrics"
                    )
                
                export_btn = gr.Button("πŸ“₯ Export Now", variant="primary", size="lg")
                export_output = gr.Code(label="Exported Data Preview", language="markdown", lines=20)
                download_file = gr.File(
                    label="πŸ“₯ Download Export File",
                    file_types=[".json", ".md", ".txt", ".pdf"]
                )
                
                gr.Markdown("---")
                gr.Markdown("### πŸ” Search Conversations")
                gr.Markdown("Search through your conversation history by keywords.")
                
                with gr.Row():
                    search_input = gr.Textbox(
                        placeholder="πŸ”Ž Enter keyword to search...", 
                        scale=3,
                        label="Search Query",
                        show_label=False
                    )
                    search_btn = gr.Button("πŸ” Search", scale=1, size="lg")
                
                search_results = gr.Markdown("πŸ’‘ **Tip:** Enter a keyword and click Search to find relevant conversations.")
                
                gr.Markdown("---")
                gr.Markdown("### πŸ“š Conversation History")
                history_stats = gr.Markdown("Loading statistics...")
            
            # ==================== TAB 3: ANALYTICS & INSIGHTS ====================
            with gr.Tab("πŸ“Š Analytics & Insights"):
                gr.Markdown("### πŸ“Š Performance Analytics Dashboard")
                refresh_btn = gr.Button("πŸ”„ Refresh Analytics", variant="primary", size="lg")
                
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("#### πŸ“ˆ Performance Metrics")
                        analytics_display = gr.Markdown(components.get_empty_analytics_html())
                    
                    with gr.Column():
                        gr.Markdown("#### πŸ’Ύ Cache Statistics")
                        cache_display = gr.Markdown("No cache data available yet. Start a conversation to see cache performance.")
                
                gr.Markdown("---")
                gr.Markdown("### πŸ“Š Usage Distribution")
                
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("#### πŸ€– Model Usage")
                        model_dist = gr.Markdown("**No data yet.** Models will be tracked as you use them.")
                    
                    with gr.Column():
                        gr.Markdown("#### 🧠 Reasoning Mode Usage")
                        mode_dist = gr.Markdown("**No data yet.** Reasoning modes will be tracked as you use them.")
            
            # ==================== TAB 4: SETTINGS ====================
            with gr.Tab("βš™οΈ Settings"):
                gr.Markdown("### βš™οΈ Application Settings")
                gr.Markdown("Current configuration and system controls.")
                
                gr.Markdown(components.get_settings_table_html())
                
                gr.Markdown("---")
                gr.Markdown("### πŸ› οΈ System Actions")
                
                with gr.Row():
                    clear_cache_btn = gr.Button("πŸ—‘οΈ Clear Cache", variant="stop", size="lg")
                    reset_metrics_btn = gr.Button("πŸ”„ Reset Metrics", variant="secondary", size="lg")
                
                cache_status = gr.Markdown("")
        
        # ==================== EVENT HANDLERS ====================
        
        # State management
        sidebar_visible_state = gr.State(value=True)
        
        # Message submission
        submit_btn.click(
            handlers.process_message,
            [msg, chatbot, reasoning_mode, enable_critique, model, 
             temperature, max_tokens, prompt_template, use_cache],
            [chatbot, metrics_display]
        ).then(lambda: "", None, msg)
        
        msg.submit(
            handlers.process_message,
            [msg, chatbot, reasoning_mode, enable_critique, model, 
             temperature, max_tokens, prompt_template, use_cache],
            [chatbot, metrics_display]
        ).then(lambda: "", None, msg)
        
        # Chat controls
        clear_btn.click(handlers.reset_chat, None, [chatbot, metrics_display])
        pdf_btn.click(handlers.download_chat_pdf, None, pdf_file_output)
        
        # Sidebar toggle
        toggle_sidebar_btn.click(
            handlers.toggle_sidebar,
            inputs=[sidebar_visible_state],
            outputs=[sidebar, sidebar_visible_state]
        )
        
        # Export & Search
        export_btn.click(handlers.export_conversation, [export_format, include_meta], [export_output, download_file])
        search_btn.click(handlers.search_conversations, search_input, search_results)
        
        # Analytics
        refresh_btn.click(handlers.refresh_analytics, None, [analytics_display, cache_display, model_dist, mode_dist])
        
        # Settings actions
        clear_cache_btn.click(handlers.clear_cache_action, None, cache_status)
        reset_metrics_btn.click(handlers.reset_metrics_action, None, cache_status)
        
        # Load history stats on page load
        demo.load(handlers.update_history_stats, None, history_stats)
    
    return demo