File size: 6,456 Bytes
a6b68d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import gradio as gr
import asyncio
import json
from datetime import datetime
from dialogue.manager import DialogueManager
from dotenv import load_dotenv

# Загружаем переменные окружения
load_dotenv()

def create_interface():
    with gr.Blocks(theme=gr.themes.Soft()) as interface:
        gr.Markdown("# AI Dialogue Lab")
        
        state = gr.State({"is_processing": False})
        
        with gr.Row():
            with gr.Column(scale=3):
                topic = gr.TextArea(
                    label="Тема для обсуждения",
                    placeholder="Опишите тему максимально подробно...",
                    lines=4
                )
            with gr.Column(scale=1):
                iterations = gr.Slider(
                    minimum=1,
                    maximum=5,
                    step=1,
                    value=3,
                    label="Количество итераций"
                )
        
        with gr.Row():
            start_btn = gr.Button("Начать", variant="primary")
            save_btn = gr.Button("Сохранить")
            clear_btn = gr.Button("Очистить")
        
        status = gr.Markdown("")
        chatbot = gr.Chatbot(label="Диалог", height=600)
        dialogue_history = gr.State([])
        
        def save_dialogue(history):
            if not history:
                return "❌ Нет данных для сохранения"
            
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"dialogue_{timestamp}.json"
            
            data = {
                "timestamp": datetime.now().isoformat(),
                "messages": history
            }
            
            with open(filename, "w", encoding="utf-8") as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            
            return f"✅ Диалог сохранен в файл: {filename}"

        def update_ui_state(is_processing: bool):
            return {
                start_btn: gr.Button(interactive=not is_processing),
                topic: gr.TextArea(interactive=not is_processing),
                iterations: gr.Slider(interactive=not is_processing),
                save_btn: gr.Button(interactive=not is_processing and bool(dialogue_history))
            }
        
        async def start_dialogue(topic_text, num_iterations):
            # Деактивируем элементы интерфейса
            start_btn.interactive = False
            topic.interactive = False
            iterations.interactive = False
            save_btn.interactive = False
            
            chat_history = []
            dialogue_history = []

            try:
                manager = DialogueManager(topic_text, num_iterations)
                
                # Оптимизация промпта
                yield "🔄 Оптимизация запроса...", chat_history
                
                optimized = await manager.optimize_prompt(topic_text)
                chat_history = [("🔧 System", f"Оптимизированная тема:\n{optimized}")]
                dialogue_history = chat_history.copy()
                yield "✨ Начинаем диалог...", chat_history
                
                current_prompt = optimized
                for i in range(num_iterations):
                    # Ход Claude
                    yield "🤔 Claude обдумывает ответ...", chat_history
                    
                    claude_response = await manager.claude.generate_response(current_prompt)
                    chat_history.append(("🔵 Claude", claude_response))
                    dialogue_history = chat_history.copy()
                    yield f"✨ Ход {i+1}/{num_iterations}: Claude ответил", chat_history
                    
                    # Ход Grok
                    yield "🤔 Grok обдумывает ответ...", chat_history
                    
                    grok_response = await manager.grok.generate_response(claude_response)
                    chat_history.append(("🟢 Grok", grok_response))
                    dialogue_history = chat_history.copy()
                    yield f"✨ Ход {i+1}/{num_iterations}: Grok ответил", chat_history
                    
                    current_prompt = grok_response
                
                # Активируем элементы интерфейса
                start_btn.interactive = True
                topic.interactive = True
                iterations.interactive = True
                save_btn.interactive = True
                
                yield "✅ Диалог завершен", chat_history
                
            except Exception as e:
                # В случае ошибки тоже активируем элементы
                start_btn.interactive = True
                topic.interactive = True
                iterations.interactive = True
                save_btn.interactive = False
                yield f"❌ Ошибка: {str(e)}", chat_history

        def clear_chat():
            return {
                status: "",
                chatbot: [],
                dialogue_history: [],
                start_btn: gr.Button(interactive=True),
                topic: gr.TextArea(interactive=True),
                iterations: gr.Slider(interactive=True),
                save_btn: gr.Button(interactive=False)
            }

        start_btn.click(
            fn=start_dialogue,
            inputs=[topic, iterations],
            outputs=[status, chatbot],
            api_name="start_dialogue",
            show_progress="full"
        ).then(
            lambda: gr.Button(interactive=True),
            None,
            [start_btn]
        )
        
        save_btn.click(
            fn=save_dialogue,
            inputs=[dialogue_history],
            outputs=[status],
            api_name="save_dialogue"
        )
        
        clear_btn.click(
            fn=clear_chat,
            outputs=[status, chatbot, dialogue_history, start_btn, topic, iterations, save_btn],
            api_name="clear_chat"
        )

    return interface

if __name__ == "__main__":
    interface = create_interface()
    interface.queue().launch()