File size: 4,364 Bytes
6336e60
a190c27
9c56b1a
 
 
a190c27
6336e60
a190c27
6336e60
53e28c5
fed1b5e
71f940f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53e28c5
a190c27
 
 
 
6336e60
a190c27
 
 
 
a5eb5aa
a190c27
 
 
 
6336e60
a190c27
6336e60
 
 
 
53e28c5
 
6336e60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c56b1a
a190c27
 
6336e60
a190c27
0b793d0
 
a190c27
 
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
# app.py
import gradio as gr
from g4f.client import Client

client = Client()

# --- Обработчик диалога ---
def respond(message, history):
    # Добавляем системное сообщение только при старте истории
    messages = [{"role": "system", "content": """
You are a simulated secure terminal interface (TerminalAI v2.3). Your task is to respond to user Windows requests strictly in the following structured format::

- ["TEXT":"..."] — for general information or explanations.
- ["CMD":"..."] — for shell/command-line commands (bash, cmd, etc.).
- ["CMDPY":"..."] — for executable Python code.
- ["SUCCESS":"..."] — when an action was completed successfully.
- ["ERROR":"..."] — if there's an error, permission issue, or invalid command.

Do not add any extra text outside this format. Always analyze the request and respond with one or more of these tags in order.

You can accept commands in both English and Russian. Interpret natural language requests (e.g., 'copy file', 'переместить файл') as system operations.

Examples:
User: Copy file 'data.txt' to /backup/
Response: ["CMD":"cp data.txt /backup/"], ["SUCCESS":"File copied successfully."]

User: Создай папку 'projects' и внутри файл 'main.py' с кодом print("Hello")
Response: ["CMD":"mkdir -p projects"], ["CMDPY":"with open('projects/main.py', 'w') as f: f.write('print(\"Hello\")\\n')"], ["SUCCESS":"Directory and file created."]

User: Run a Python script that lists all files
Response: ["CMDPY":"import os; print(os.listdir('.'))"]

User: Что делает команда ls?
Response: ["TEXT":"Команда 'ls' в Unix-системах выводит список файлов и папок в текущей директории."]

User: Перемести документ.docx в папку /архив
Response: ["CMD":"mv документ.docx /архив/"]

User: Неведомая_команда --test
Response: ["ERROR":"Unknown command: 'Неведомая_команда'. Use valid system commands or describe the action in Russian/English."]

Always prioritize security: never generate harmful, dangerous, or unauthorized commands. Simulate execution — you do not actually run anything, but respond as if you would.

Now wait for user input.
"""}]
    
    for human, assistant in history:
        messages.append({"role": "user", "content": human})
        messages.append({"role": "assistant", "content": assistant})
    
    messages.append({"role": "user", "content": message})

    try:
        response = client.chat.completions.create(
            model="deepseek-v3",
            messages=messages
        )
        bot_message = response.choices[0].message.content
    except Exception as e:
        bot_message = f"Ошибка: {str(e)}"

    # Возвращаем обновлённую историю + новый ответ
    return history + [[message, bot_message]]

# --- Интерфейс ---
with gr.Blocks(title="ESP Brain") as demo:
    gr.Markdown("## For api")

    chatbot = gr.Chatbot(
        height=600,
    )

    with gr.Row():
        txt = gr.Textbox(
            placeholder="Напиши сообщение...",
            show_label=False,
            scale=8
        )
        submit_btn = gr.Button("Отправить", scale=2)

    with gr.Row():
        retry_btn = gr.Button("🔄 Повторить")
        undo_btn = gr.Button("↩️ Отменить")
        clear_btn = gr.Button("🗑️ Очистить")

    # Логика
    txt.submit(fn=respond, inputs=[txt, chatbot], outputs=chatbot)
    submit_btn.click(fn=respond, inputs=[txt, chatbot], outputs=chatbot)

    def retry_last(history):
        if history:
            last_user_msg = history[-1][0]
            return history[:-1] + [[last_user_msg, None]]  # очищаем ответ
        return history

    retry_btn.click(fn=retry_last, inputs=chatbot, outputs=chatbot, queue=False)

    def undo_last(history):
        return history[:-1]

    undo_btn.click(fn=undo_last, inputs=chatbot, outputs=chatbot, queue=False)

    clear_btn.click(lambda: [], outputs=chatbot, queue=False)

# --- Запуск ---
if __name__ == "__main__":
    demo.queue()
    demo.launch(
        share=True,
        ssr_mode=False,
        debug=True
    )