-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
4775 lines (4124 loc) · 248 KB
/
main.py
File metadata and controls
4775 lines (4124 loc) · 248 KB
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import requests
import base64
import json
import re
import subprocess
import winreg
import shutil
import urllib.parse
import venv
import webbrowser
import platform
import mimetypes
import psutil
import io
import datetime
import time
from tqdm import tqdm
from loguru import logger
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from tkinter import messagebox
from packaging import version
from dotenv import set_key
from lang import get_text, get_language_settings, save_language_settings, show_language_selection, translate_prompt_for_ai
# Импорты для работы с различными форматами файлов
try:
from PIL import Image, ImageDraw, ImageFont
PILLOW_AVAILABLE = True
except ImportError:
PILLOW_AVAILABLE = False
try:
import pytesseract
TESSERACT_AVAILABLE = True
except ImportError:
TESSERACT_AVAILABLE = False
try:
from docx import Document
from docx.shared import Inches
DOCX_AVAILABLE = True
except ImportError:
DOCX_AVAILABLE = False
try:
import openpyxl
EXCEL_AVAILABLE = True
except ImportError:
EXCEL_AVAILABLE = False
try:
from pptx import Presentation
PPTX_AVAILABLE = True
except ImportError:
PPTX_AVAILABLE = False
try:
import PyPDF2
PDF_AVAILABLE = True
except ImportError:
PDF_AVAILABLE = False
CURRENT_VERSION = "1.4"
def open_file_with_default_program(file_path):
try:
if platform.system() == 'Windows':
os.startfile(file_path)
elif platform.system() == 'Darwin': # macOS
subprocess.call(['open', file_path])
else: # linux
subprocess.call(['xdg-open', file_path])
except Exception as e:
logger.error(f"Ошибка открытия файла {file_path}: {e}")
# Настройка логирования
def setup_logging():
"""Настраивает логирование в зависимости от настроек"""
# Загружаем переменные окружения для проверки настроек
load_dotenv()
file_logging = os.getenv('FILE_LOGGING', 'true').lower() == 'true'
debug_mode = os.getenv('DEBUG_MODE', 'false').lower() == 'true'
if file_logging:
# Создаем файл логов только если логирование включено
log_file = "pollinations_agent.log"
logger.add(log_file, rotation="50 MB", level="DEBUG" if debug_mode else "INFO")
print(f"📝 Логирование в файл включено: {log_file}")
else:
print("📝 Логирование в файл отключено")
# Вызываем настройку логирования
setup_logging()
# Имитация флага перевода
class MainApp:
def __init__(self):
self.isTranslate = False # Русский/Английский
main_app = MainApp()
# Функция получения сообщения об ошибке
def get_error_message(translate=False):
if translate:
return "Ошибка"
else:
return "Error"
# Удаление эмодзи из строки
def remove_emojis(text):
emoji_pattern = re.compile(
"["
"\U0001F600-\U0001F64F" # emoticons
"\U0001F300-\U0001F5FF" # symbols & pictographs
"\U0001F680-\U0001F6FF" # transport & map symbols
"\U0001F700-\U0001F77F" # alchemical symbols
"\U0001F780-\U0001F7FF" # Geometric Shapes Extended
"\U0001F800-\U0001F8FF" # Supplemental Symbols and Pictographs
"\U0001F900-\U0001F9FF" # Emoticons Supplement
"\U0001FA00-\U0001FA6F" # Chess Symbols
"\U0001FA70-\U0001FAFF" # Symbols and Pictographs Extended-A
"\U00002702-\U000027B0" # Dingbats
"]+",
flags=re.UNICODE,
)
return emoji_pattern.sub(r"", text)
def update_app(update_url):
webbrowser.open(update_url)
def check_for_updates():
try:
# Получение информации о последнем релизе на GitHub
response = requests.get("https://api.github.com/repos/Processori7/Poli_AI/releases/latest")
response.raise_for_status()
latest_release = response.json()
# Получение ссылки на файл llm.exe последней версии
download_url = None
assets = latest_release["assets"]
for asset in assets:
if asset["name"] == "poliai.exe": # Ищем только llm.exe
download_url = asset["browser_download_url"]
break
if download_url is None:
messagebox.showerror("Ошибка обновления", "Не удалось найти файл poliai.exe для последней версии.")
return
# Сравнение текущей версии с последней версией
latest_version_str = latest_release["tag_name"]
match = re.search(r'\d+\.\d+', latest_version_str)
if match:
latest_version = match.group()
else:
latest_version = latest_version_str
if version.parse(latest_version) > version.parse(CURRENT_VERSION):
if platform.system() == "Windows":
# Предложение пользователю обновление
if messagebox.showwarning("Доступно обновление",
f"Доступна новая версия {latest_version}. Хотите обновить?", icon='warning',
type='yesno') == 'yes':
update_app(download_url)
else:
if messagebox.showwarning("Доступно обновление",
f"Доступна новая версия {latest_version}. Хотите обновить?", icon='warning',
type='yesno') == 'yes':
os.system("git pull")
except requests.exceptions.RequestException as e:
messagebox.showerror("Error", str(e))
# Генерация изображения
def gen_img(prompt, model_name="flux", width=1024, height=1024):
try:
encoded_prompt = requests.utils.quote(prompt)
url = f"https://image.pollinations.ai/prompt/{encoded_prompt}?model={model_name}&width={width}&height={height}"
response = requests.get(url)
if response.status_code == 200:
output_dir = "output"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
filepath = os.path.join(output_dir, f"{prompt.replace(' ', '_')}.jpg")
with open(filepath, "wb") as f:
f.write(response.content)
return filepath
else:
return f"Ошибка генерации: {response.status_code}"
except Exception as e:
return str(e)
# Общение с Pollinations (текстовая модель)
def communicate_with_Pollinations_chat(model_name, messages, tools=None, tool_choice="auto", api_token=None):
"""
Отправляет структурированный запрос к Pollinations API с поддержкой инструментов.
:param model_name: Имя модели (например, 'openai')
:param messages: Список сообщений в формате [{'role': 'user', 'content': '...'}, ...]
:param tools: Список инструментов в формате OpenAI
:param tool_choice: auto или конкретное имя инструмента
:param api_token: API токен (опционально)
:return: JSON-ответ от сервера или ошибка
"""
url = "https://text.pollinations.ai/openai"
payload = {
"model": model_name,
"messages": messages,
"private": True # Не показывать в публичном feed
}
# Добавляем tools и tool_choice только если tools переданы
if tools:
payload["tools"] = tools
payload["tool_choice"] = tool_choice
# Подготавливаем заголовки
headers = {"Content-Type": "application/json"}
# Добавляем токен если он есть
if api_token:
headers["Authorization"] = f"Bearer {api_token}"
try:
response = requests.post(
url,
headers=headers,
json=payload
)
# Убрали вывод HTTP статуса и ответа
if response.status_code == 200:
return response.json()
else:
return {"error": f"HTTP {response.status_code}: {response.text}"}
except Exception as e:
return {"error": str(e)}
# Получить модели для генерации изображений
def get_Polinations_img_models():
model_functions = {}
try:
url = "https://image.pollinations.ai/models"
resp = requests.get(url)
if resp.ok:
models = resp.json() # Получаем список строк
for name in models: # Проходим по каждой строке
key = f"(Polinations) {name}_img"
model_functions[key] = lambda user_input, model_name=name: gen_img(user_input, model_name)
return model_functions
else:
return f"{get_error_message(main_app.isTranslate)}: {resp.status_code}"
except Exception as e:
return f"{get_error_message(main_app.isTranslate)}: {str(e)}"
# Получить модели для чат-генерации текста (с описанием)
def get_Polinations_chat_models():
models_list = []
try:
url = "https://text.pollinations.ai/models"
resp = requests.get(url)
if resp.ok:
models = resp.json()
for model in models:
if isinstance(model, dict) and "name" in model:
model_name = model["name"]
model_description = model.get("description", "Без описания")
# Получаем модальности из API или определяем вручную
input_modalities = model.get("input_modalities", [])
# Если API не возвращает модальности, задаем их вручную для известных моделей
if not input_modalities:
# Модели OpenAI поддерживают текст и изображения
if "openai" in model_name.lower():
input_modalities = ["text", "image"]
# Модели с audio в названии поддерживают аудио
elif "audio" in model_name.lower():
input_modalities = ["text", "audio"]
# Остальные модели поддерживают только текст
else:
input_modalities = ["text"]
models_list.append({
"name": model_name,
"description": model_description,
"input_modalities": input_modalities
})
return models_list
else:
print(f"Ошибка получения списка моделей: {resp.status_code}")
return [{"name": "o3-mini", "description": "Быстрая и эффективная модель", "input_modalities": ["text"]}]
except Exception as e:
print(f"Ошибка при получении списка моделей: {e}")
return [{"name": "o3-mini", "description": "Быстрая и эффективная модель", "input_modalities": ["text"]}]
# Класс агента
def create_env_file(env_file_path):
"""Creates .env file if it does not exist and initializes it with default settings"""
if not os.path.exists(env_file_path):
# Создаем файл только с обязательными настройками, оставляя выбор языка для первого запуска
set_key(env_file_path, 'POLLINATIONS_TOKEN', '')
set_key(env_file_path, 'FIRST_STARTUP_LANGUAGE_SELECTION', 'true')
set_key(env_file_path, 'DEFAULT_MODEL', 'openai')
set_key(env_file_path, 'MAX_ATTEMPTS', '5')
set_key(env_file_path, 'AUTO_MODEL_SELECTION', 'false')
set_key(env_file_path, 'DEFAULT_VOICE', 'alloy')
set_key(env_file_path, 'REQUIRE_CONFIRMATION', 'true')
set_key(env_file_path, 'DEBUG_MODE', 'false')
set_key(env_file_path, 'FILE_LOGGING', 'true')
print(f"🔧 .env файл создан: {env_file_path}")
return True # Возвращаем True если файл был создан
else:
print(f"🔧 .env файл уже существует: {env_file_path}")
return False # Возвращаем False если файл уже существовал
class PollinationsAgent:
def __init__(self):
# Создаем .env файл если его нет (с настройками по умолчанию)
file_was_created = create_env_file('.env')
# Загружаем переменные окружения из .env файла
load_dotenv()
self.base_text_url = "https://text.pollinations.ai"
self.base_image_url = "https://image.pollinations.ai"
self.output_dir = "output"
# Загружаем настройки из .env файла
self.api_token = os.getenv('POLLINATIONS_TOKEN')
# Если файл был только что создан, принудительно устанавливаем первый запуск
if file_was_created:
self.first_startup_language_selection = True
self.interface_language = 'ru' # Временно по умолчанию
self.output_language = 'ru' # Временно по умолчанию
else:
lang_settings = get_language_settings()
self.interface_language = lang_settings['interface']
self.output_language = lang_settings['output']
self.first_startup_language_selection = lang_settings['first_startup']
self.default_model = os.getenv('DEFAULT_MODEL', 'openai')
self.max_attempts = int(os.getenv('MAX_ATTEMPTS', '5'))
self.default_voice = os.getenv('DEFAULT_VOICE', 'alloy')
self.require_confirmation = os.getenv('REQUIRE_CONFIRMATION', 'true').lower() == 'true'
self.debug_mode = os.getenv('DEBUG_MODE', 'false').lower() == 'true'
# Сообщения в зависимости от языка интерфейса
self.messages = self._get_interface_messages()
if self.api_token:
print(f"🔑 {self.messages['api_token_loaded']}")
else:
print(f"⚠️ {self.messages['api_token_missing']}")
if self.debug_mode:
print(f"🔧 Debug mode: Interface={self.interface_language}, Output={self.output_language}, Model={self.default_model}")
# MCP инструменты
self.mcp_tools = {
"generateImageUrl": self.generate_image_url,
"generateImage": self.generate_image,
"respondAudio": self.generate_audio,
"sayText": self.generate_audio,
"listImageModels": self.list_image_models,
"listAudioVoices": self.list_audio_voices,
# 🔧 Файловая система
"createFile": self.create_file,
"readFile": self.read_file,
"writeFile": self.write_file,
"deleteFile": self.delete_file,
"moveFile": self.move_file,
"listDirectory": self.list_directory,
"createDirectory": self.create_directory,
"deleteDirectory": self.delete_directory,
# 🌐 Интернет и загрузки
"downloadFile": self.download_file,
"downloadImage": self.download_image,
"searchInternet": self.search_internet,
# 💻 Системные команды
"executeCommand": self.execute_command,
"runPythonCode": self.run_python_code,
# ⚙️ Системные настройки
"changeRegistryValue": self.change_registry_value,
"getSystemInfo": self.get_system_info,
"manageServices": self.manage_services,
"clearBin":self.clearBin,
"listStartupPrograms": self.list_startup_programs,
"manageStartupProgram": self.manage_startup_program,
# 🔍 Поиск изображений
"searchAndDownloadImages": self.search_and_download_images,
# 🐍 Python проекты
"createPythonProject": self.create_python_project,
# 💻 Разработка ПО
"developSoftware": self.develop_software,
# 📄 Чтение файлов различных форматов
"readAdvancedFile": self.read_advanced_file,
"readDocx": self.read_docx_file,
"readPdf": self.read_pdf_file,
"readExcel": self.read_excel_file,
"readPowerPoint": self.read_powerpoint_file,
# 🖼️ Анализ изображений
"analyzeImage": self.analyze_image,
"recognizeText": self.recognize_text_from_image,
"getImageInfo": self.get_image_info,
"findAndAnalyzeFile": self.find_and_analyze_file,
# 📂 Открытие и запуск файлов
"openFileWithDefaultProgram": self.open_file_with_default_program,
"runExecutable": self.run_executable,
"smartOpenFile": self.smart_open_file,
}
# Получаем доступные модели
self.img_models = get_Polinations_img_models()
self.chat_models = get_Polinations_chat_models() # Теперь это список словарей
self.current_model = None
# Сохраняем только имена моделей
self.model_list = [model['name'] for model in self.chat_models]
# Создаем словарь для быстрого поиска модели по имени
self.models_by_name = {model['name']: model for model in self.chat_models}
def get_models_with_modality(self, required_modality):
"""Получает список моделей, поддерживающих определенную модальность"""
compatible_models = []
for model in self.chat_models:
input_modalities = model.get('input_modalities', [])
if required_modality in input_modalities:
compatible_models.append(model['name'])
return compatible_models
def get_vision_models(self):
"""Получает список моделей, поддерживающих анализ изображений"""
if self.debug_mode:
print(f"🔍 DEBUG: Запрос моделей с модальностью 'image'")
# Отладка: покажем информацию о всех моделях
print(f"🔍 DEBUG: Всего моделей: {len(self.chat_models)}")
for i, model in enumerate(self.chat_models[:5]): # Показываем первые 5 для примера
modalities = model.get('input_modalities', [])
vision_flag = model.get('vision', False)
print(f"🔍 DEBUG: Модель {i+1}: {model['name']}, modalities: {modalities}, vision: {vision_flag}")
result = self.get_models_with_modality('image')
if self.debug_mode:
print(f"🔍 DEBUG: Результат get_models_with_modality('image'): {result}")
return result
def get_audio_models(self):
"""Получает список моделей, поддерживающих анализ аудио"""
return self.get_models_with_modality('audio')
def get_text_only_models(self):
"""Получает список моделей, поддерживающих только текст"""
text_only_models = []
for model in self.chat_models:
input_modalities = model.get('input_modalities', [])
# Модель поддерживает только текст, если в input_modalities только "text"
if input_modalities == ['text']:
text_only_models.append(model['name'])
return text_only_models
def show_incompatible_models_warning(self, required_modality, action_name):
"""Показывает предупреждение о несовместимых моделях и список поддерживаемых"""
current_model_info = self.models_by_name.get(self.current_model, {})
current_modalities = current_model_info.get('input_modalities', [])
if required_modality not in current_modalities:
compatible_models = self.get_models_with_modality(required_modality)
if compatible_models:
print(f"\n⚠️ Модель '{self.current_model}' не поддерживает {action_name}!")
print(f"🎯 Поддерживаемые модальности: {', '.join(current_modalities)}")
print(f"\n✅ Модели, поддерживающие {action_name}:")
for i, model_name in enumerate(compatible_models, 1):
model_info = self.models_by_name.get(model_name, {})
description = model_info.get('description', 'Без описания')
print(f"{i}. {model_name} — {description}")
try:
choice = input(f"\nПереключиться на совместимую модель? (1-{len(compatible_models)} или Enter для пропуска): ").strip()
if choice and choice.isdigit():
choice_idx = int(choice) - 1
if 0 <= choice_idx < len(compatible_models):
new_model = compatible_models[choice_idx]
self.current_model = new_model
print(f"✅ Переключились на модель: {new_model}")
return True
except (ValueError, IndexError):
pass
else:
print(f"\n❌ Нет доступных моделей для {action_name}!")
return False
return True
def create_file(self, path, content=""):
"""Создает файл по указанному пути"""
try:
# Создаем директорию, если она не существует
directory = os.path.dirname(path)
if directory and not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)
logger.info(f"Создана папка: {directory}")
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
logger.info(f"Файл создан: {path}")
return f"Файл создан: {path}"
except Exception as e:
return f"Ошибка создания файла: {str(e)}"
def read_file(self, path):
"""Читает содержимое файла"""
try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
logger.info(f"Файл прочитан: {path}")
return content
except Exception as e:
return f"Ошибка чтения файла: {str(e)}"
def write_file(self, path, content):
"""Записывает данные в существующий файл"""
try:
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
logger.info(f"Файл обновлен: {path}")
return f"Файл обновлен: {path}"
except Exception as e:
return f"Ошибка записи в файл: {str(e)}"
def delete_file(self, path):
"""Удаляет файл"""
try:
os.remove(path)
logger.info(f"Файл удален: {path}")
return f"Файл удален: {path}"
except Exception as e:
return f"Ошибка удаления файла: {str(e)}"
def move_file(self, source_path, destination_path):
"""Перемещает файл из одной папки в другую"""
try:
# Создаем папку назначения если она не существует
destination_dir = os.path.dirname(destination_path)
if destination_dir and not os.path.exists(destination_dir):
os.makedirs(destination_dir, exist_ok=True)
logger.info(f"Создана папка: {destination_dir}")
# Если путь назначения - это папка, добавляем имя файла
if os.path.isdir(destination_path):
filename = os.path.basename(source_path)
destination_path = os.path.join(destination_path, filename)
# Перемещаем файл
shutil.move(source_path, destination_path)
logger.info(f"Файл перемещен: {source_path} -> {destination_path}")
return f"Файл перемещен: {source_path} -> {destination_path}"
except Exception as e:
return f"Ошибка перемещения файла: {str(e)}"
def list_directory(self, path="."):
"""Возвращает список файлов и папок в директории"""
try:
items = os.listdir(path)
logger.info(f"Директория просканирована: {path}")
return json.dumps(items, ensure_ascii=False)
except Exception as e:
return f"Ошибка сканирования директории: {str(e)}"
def create_directory(self, path):
"""Создает новую папку"""
try:
os.makedirs(path, exist_ok=True)
logger.info(f"Папка создана: {path}")
return f"Папка создана: {path}"
except Exception as e:
return f"Ошибка создания папки: {str(e)}"
def delete_directory(self, path):
"""Удаляет папку и её содержимое"""
try:
# Используем shutil.rmtree для рекурсивного удаления
if os.path.exists(path):
shutil.rmtree(path)
logger.info(f"Папка удалена: {path}")
return f"Папка удалена: {path}"
else:
return f"Папка не существует: {path}"
except Exception as e:
return f"Ошибка удаления папки: {str(e)}"
def swap_files(self, path1, path2):
"""Меняет два файла местами"""
try:
# Проверяем что оба файла существуют
if not os.path.exists(path1):
return f"Файл не существует: {path1}"
if not os.path.exists(path2):
return f"Файл не существует: {path2}"
# Создаем временный файл
temp_file = path1 + ".temp_swap"
# Меняем файлы местами через временный файл
shutil.move(path1, temp_file)
shutil.move(path2, path1)
shutil.move(temp_file, path2)
logger.info(f"Файлы обменены местами: {path1} ↔ {path2}")
return f"Файлы обменены местами: {path1} ↔ {path2}"
except Exception as e:
return f"Ошибка обмена файлов: {str(e)}"
def list_image_models(self):
"""Список доступных моделей изображений"""
response = requests.get(f"{self.base_image_url}/models")
response.raise_for_status()
return response.json()
def list_audio_voices(self):
"""Список доступных голосов"""
try:
response = requests.get(f"{self.base_text_url}/models")
response.raise_for_status()
models_data = response.json()
# Попытаемся извлечь голоса из структуры данных
if isinstance(models_data, dict) and 'openai-audio' in models_data:
voices = models_data.get('openai-audio', {}).get('voices', [])
if voices:
return voices
# Если не удалось получить из API, возвращаем известные голоса
return ["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
except Exception as e:
logger.warning(f"Не удалось получить список голосов: {e}")
# Возвращаем стандартные голоса OpenAI
return ["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
def clearBin(self):
"""Очищает корзину Windows"""
try:
# Пробуем несколько способов очистки корзины
methods = [
# Способ 1: PowerShell Clear-RecycleBin с подавлением ошибок
{
"command": ["powershell", "-Command", "try { Clear-RecycleBin -Force -ErrorAction SilentlyContinue; Write-Output 'Success' } catch { Write-Output 'Success' }"],
"name": "PowerShell Clear-RecycleBin"
},
# Способ 2: Альтернативный PowerShell скрипт
{
"command": ["powershell", "-Command", "$shell = New-Object -ComObject Shell.Application; $recycleBin = $shell.Namespace(10); $recycleBin.Items() | ForEach-Object { $_.InvokeVerb('delete') }; Write-Output 'Success'"],
"name": "PowerShell COM объект"
},
# Способ 3: CMD команда
{
"command": ["cmd", "/c", "rd /s /q %systemdrive%\\$Recycle.Bin 2>nul && echo Success || echo Success"],
"name": "CMD rd команда"
}
]
for method in methods:
try:
print(f"🔄 Попытка очистки корзины методом: {method['name']}")
result = subprocess.run(
method["command"],
capture_output=True,
text=True,
check=False,
encoding='utf-8',
errors='ignore' # Игнорируем ошибки кодировки
)
# Если команда выполнилась (независимо от return code)
# и нет критических ошибок в выводе
output = result.stdout.strip() if result.stdout else ""
error_output = result.stderr.strip() if result.stderr else ""
# Проверяем на успешное выполнение
success_indicators = ["Success", "success", "SUCCESS"]
is_success = any(indicator in output for indicator in success_indicators)
# Или если нет критических ошибок
critical_errors = [
"Access is denied",
"Доступ запрещен",
"Cannot find",
"Не удается найти",
"Invalid",
"Недопустимый"
]
has_critical_error = any(error in error_output.lower() for error in [e.lower() for e in critical_errors])
if is_success or (result.returncode == 0 and not has_critical_error):
logger.info(f"Корзина очищена методом: {method['name']}")
return "✅ Корзина успешно очищена"
# Если этот метод не сработал, пробуем следующий
print(f"⚠️ Метод {method['name']} не сработал, пробуем следующий...")
continue
except Exception as method_error:
print(f"⚠️ Ошибка с методом {method['name']}: {str(method_error)}")
continue
# Если все методы не сработали, делаем финальную попытку проверки
# Проверяем, действительно ли корзина пустая
try:
check_result = subprocess.run(
["powershell", "-Command", "(Get-ChildItem -Path '$env:systemdrive\\$Recycle.Bin' -Force -ErrorAction SilentlyContinue | Measure-Object).Count"],
capture_output=True,
text=True,
check=False,
encoding='utf-8',
errors='ignore'
)
if check_result.stdout.strip() == "0":
logger.info("Корзина очищена (подтверждено проверкой)")
return "✅ Корзина успешно очищена (подтверждено проверкой)"
except Exception:
pass
# Если ничего не помогло, возвращаем более мягкое сообщение
logger.warning("Не удалось однозначно определить результат очистки корзины")
return "⚠️ Команда очистки корзины выполнена. Возможно, корзина была уже пуста или очищена успешно."
except Exception as e:
return f"❌ Критическая ошибка очистки корзины: {str(e)}"
def check_answear(self):
if not self.api_token:
print(f"\n⚠️ Pollinations API токен не найден")
print(f"🔗 Получите токен на: https://auth.pollinations.ai/")
# Предлагаем открыть страницу для получения токена
try:
open_choice = input("\nОткрыть страницу для получения токена? (y/n): ").strip().lower()
if open_choice == 'y':
webbrowser.open('https://auth.pollinations.ai/')
return True
else:
return False
except Exception:
pass
def generate_audio(self, text, voice="alloy"):
"""Генерация аудио через Pollinations API"""
try:
print(f"🎵 Генерация аудио...")
print(f"📝 Исходный текст: {text}")
# Проверяем наличие API токена
if not self.api_token:
print(f"\n⚠️ Pollinations API токен не найден")
print(f"🔗 Получите токен на: https://auth.pollinations.ai/")
# Предлагаем открыть страницу для получения токена
try:
open_choice = input("\nОткрыть страницу для получения токена? (y/n): ").strip().lower()
if open_choice == 'y':
webbrowser.open('https://auth.pollinations.ai/')
print("🌐 Страница открыта в браузере")
else:
print("Отмена открытия страницы")
except Exception:
pass
# Показываем доступные голоса для выбора
available_voices = self.list_audio_voices()
print(f"\n🎙️ Доступные голоса:")
for i, voice_name in enumerate(available_voices, 1):
current_marker = " (текущий)" if voice_name == voice else ""
print(f"{i}. {voice_name}{current_marker}")
try:
choice = input(f"\nВыберите голос (1-{len(available_voices)}) или нажмите Enter для {voice}: ").strip()
if choice and choice.isdigit():
choice_idx = int(choice) - 1
if 0 <= choice_idx < len(available_voices):
voice = available_voices[choice_idx]
print(f"✅ Выбран голос: {voice}")
else:
print(f"⚠️ Неверный номер, используется голос по умолчанию: {voice}")
else:
print(f"⚠️ Используется голос по умолчанию: {voice}")
except (ValueError, IndexError):
print(f"⚠️ Ошибка ввода, используется голос по умолчанию: {voice}")
# Подготавливаем payload с токеном
payload = {
"model": "openai-audio",
"messages": [{"role": "user", "content": text}],
"voice": voice,
"private": True # Не показывать в публичном feed
}
# Подготавливаем заголовки с Authorization Bearer токеном
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_token}"
}
print(f"🔄 Отправка запроса на генерацию аудио с токеном...")
response = requests.post(
f"{self.base_text_url}/openai",
json=payload,
headers=headers
)
response.raise_for_status()
result = response.json()
if 'choices' in result and len(result['choices']) > 0:
message = result['choices'][0]['message']
if 'audio' in message and 'data' in message['audio']:
audio_data = message['audio']['data']
filename = text.replace(" ", "_")[:50] # Ограничиваем длину имени файла
filepath = self.save_audio(audio_data, filename)
print(f"✅ Аудио сгенерировано: {filepath}")
return f"Аудио сгенерировано и сохранено: {filepath}"
else:
return "Ошибка: В ответе нет аудио данных"
else:
return "Ошибка: Неверный формат ответа от API"
except requests.RequestException as e:
error_msg = str(e)
if "402" in error_msg or "Payment Required" in error_msg:
return "❌ Требуется оплата или валидный токен для генерации аудио. Получите токен на https://auth.pollinations.ai/"
return f"Ошибка сети при генерации аудио: {error_msg}"
except Exception as e:
return f"Ошибка генерации аудио: {str(e)}"
def analyze_audio(self, audio_path):
"""Анализирует аудио файл и преобразует речь в текст"""
try:
# Проверяем существование файла
if not os.path.exists(audio_path):
return f"Аудио файл не найден: {audio_path}"
print(f"🎤 Анализ аудио файла: {audio_path}")
# Получаем модели с поддержкой анализа аудио
audio_models = self.get_audio_models()
if not audio_models:
return "❌ Нет доступных моделей с поддержкой анализа аудио! Убедитесь, что у вас есть совместимые модели."
print(f"🔍 Доступные модели с поддержкой audio: {', '.join(audio_models)}")
# Читаем аудио файл и конвертируем в base64
with open(audio_path, "rb") as audio_file:
audio_data = base64.b64encode(audio_file.read()).decode('utf-8')
# Определяем формат аудио по расширению
_, ext = os.path.splitext(audio_path.lower())
audio_format = ext[1:] if ext else 'wav' # убираем точку
# Поддерживаемые форматы
if audio_format not in ['wav', 'mp3', 'ogg', 'flac', 'm4a', 'aac']:
audio_format = 'wav' # используем wav по умолчанию
if self.debug_mode:
print(f"📋 Формат аудио: {audio_format}")
print(f"📏 Размер данных: {len(audio_data)} символов base64")
print(f"💾 Размер файла: {os.path.getsize(audio_path)} байт")
# Пробуем разные модели по очереди
for model_name in audio_models:
print(f"🤖 Пробуем модель: {model_name}")
# Подготавливаем payload для Pollinations API
payload = {
"model": model_name,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "Transcribe this audio and return only the transcribed text:"},
{
"type": "input_audio",
"input_audio": {
"data": audio_data,
"format": audio_format
}
}
]
}
],
"private": True
}
# Подготавливаем заголовки
headers = {
"Content-Type": "application/json"
}
# Добавляем токен авторизации если есть
if self.api_token:
headers["Authorization"] = f"Bearer {self.api_token}"
print(f"🔄 Отправка аудио на транскрипцию с моделью {model_name}...")
try:
# Отправляем запрос
response = requests.post(
f"{self.base_text_url}/openai",
json=payload,
headers=headers,
timeout=60 # Увеличиваем таймаут для аудио
)
if self.debug_mode:
print(f"📊 HTTP статус ({model_name}): {response.status_code}")
if response.status_code == 200:
result = response.json()
print(f"📋 Получен ответ от API ({model_name})")
if "choices" in result and len(result["choices"]) > 0:
transcription = result["choices"][0]["message"].get("content", "")
# Проверяем качество транскрипции
print(f"📝 Транскрипция от {model_name}: {transcription[:100]}...")
# Проверяем на ошибки транскрипции
failed_responses = [
"не удалось", "не могу", "ошибка", "failed", "error", "couldn't",
"не получилось", "нет аудио", "no audio", "пустой файл", "empty file",
"не поддерживается", "not supported", "invalid format"
]
has_error = any(fail_word in transcription.lower() for fail_word in failed_responses)
is_too_short = len(transcription.strip()) < 10
if transcription and not has_error and not is_too_short:
logger.info(f"Аудио транскрибировано моделью {model_name}: {audio_path}")
return f"Транскрипция аудио файла {os.path.basename(audio_path)} (модель {model_name}):\n\n{transcription}"
else:
if has_error:
print(f"⚠️ Модель {model_name} сообщила об ошибке: {transcription[:100]}...")
elif is_too_short:
print(f"⚠️ Модель {model_name} дала слишком короткий ответ: {transcription}")
else:
print(f"⚠️ Модель {model_name} дала пустой ответ")
continue
else:
print(f"❌ Неожиданный формат ответа от {model_name}: {result}")
continue
else:
print(f"❌ Ошибка API ({model_name}): {response.status_code}")
print(f"📝 Ответ сервера: {response.text[:500]}...")
continue
except requests.RequestException as e:
print(f"❌ Ошибка сети с моделью {model_name}: {str(e)}")
continue
# Если все модели не сработали
return f"❌ Не удалось транскрибировать аудио ни одной из моделей: {', '.join(audio_models)}. Возможно, формат аудио не поддерживается или требуется другой API токен."
except Exception as e:
return f"Ошибка анализа аудио: {str(e)}"
def save_audio(self, audio_data, filename):
"""Сохраняет аудио в файл с отладочной информацией"""
try:
print(f"🔍 Отладка: Получены аудио данные, длина base64 строки: {len(audio_data)}")
print(f"🔍 Отладка: Первые 100 символов: {audio_data[:100]}...")
# Декодируем base64
audio_bytes = base64.b64decode(audio_data)
print(f"🔍 Отладка: Размер декодированных данных: {len(audio_bytes)} байт")