User Tools

Site Tools


язык_программирования_python

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
язык_программирования_python [2026/07/15 16:03]
val [ari_rec.py]
язык_программирования_python [2026/07/17 06:25] (current)
val [ari_chat.py]
Line 402: Line 402:
  
 ==== wav_and_ogg.py ==== ==== wav_and_ogg.py ====
 +
 +  * [[Перекодировка звука#​Перекодировка в ogg формат]]
 +
 <​code>​ <​code>​
 +$ pip install pydub pip #​audioop-lts
 +</​code><​code>​
 import sys import sys
 from pydub import AudioSegment from pydub import AudioSegment
Line 424: Line 429:
 #    wav_to_ogg(target_file) #    wav_to_ogg(target_file)
 #    ogg_to_wav(target_file) #    ogg_to_wav(target_file)
 +</​code><​code>​
 +$ python wav_and_ogg.py speech
 </​code>​ </​code>​
  
 ==== speech_and_text.py ==== ==== speech_and_text.py ====
 +
 +  * [[Yandex AI]]
 +
 <​code>​ <​code>​
 import os import os
Line 432: Line 442:
 import requests import requests
  
-API_KEY = os.getenv("​API_KEY") +API_KEY = os.getenv("​YANDEX_API_KEY") 
-FOLDER_ID = os.getenv("​FOLDER_ID")+FOLDER_ID = os.getenv("​YANDEX_FOLDER_ID")
  
 def speech_to_text(file_path):​ def speech_to_text(file_path):​
Line 497: Line 507:
  
     sdk = AIStudio(     sdk = AIStudio(
-        folder_id=os.getenv("​FOLDER_ID"), +        folder_id=os.getenv("​YANDEX_FOLDER_ID"), 
-        auth=os.getenv("​API_KEY")+        auth=os.getenv("​YANDEX_API_KEY")
     )     )
     messages = [{"​role":​ "​system",​ "​text":​ system_prompt}]     messages = [{"​role":​ "​system",​ "​text":​ system_prompt}]
Line 544: Line 554:
 ==== ari_rec.py ==== ==== ari_rec.py ====
 <​code>​ <​code>​
-$ pip install websocket-client+root#  
 +mkdir -p /​var/​spool/​asterisk/​recording/​ 
 +chown -R asterisk:​asterisk /​var/​spool/​asterisk/​recording/​ 
 +chmod -R 775 /​var/​spool/​asterisk/​recording/​ 
 + 
 +$ pip install websocket-client ​requests
 </​code><​code>​ </​code><​code>​
 import json import json
Line 691: Line 706:
     "Ты — ассистент.\n"​     "Ты — ассистент.\n"​
     "​Отвечай кратко.\n"​     "​Отвечай кратко.\n"​
 +    "Не спрашивай когда напомнить.\n"​
 ) )
  
 +COMPRESS_PROMPT = (
 +    "Ты — инструмент оптимизации контекста. Проанализируй историю диалога. "
 +    "​Удали выполненные дела, приветствия и воду. Сформулируй ОДНО лаконичное "
 +    "​сообщение от лица пользователя,​ в котором отражена только актуальная суть "
 +    "и невыполненные задачи/​оставшиеся вопросы на текущий момент."​
 +)
  
 # Структура:​ {channel_id:​ [{"​role":​ "​user",​ "​text":​ "​..."​},​ {"​role":​ "​assistant",​ "​text":​ "​..."​}]} # Структура:​ {channel_id:​ [{"​role":​ "​user",​ "​text":​ "​..."​},​ {"​role":​ "​assistant",​ "​text":​ "​..."​}]}
 channel_contexts = {} channel_contexts = {}
 +
 channel_caller_numbers = {} channel_caller_numbers = {}
  
Line 722: Line 745:
  
 def start_recording(channel_id):​ def start_recording(channel_id):​
-    print(f"​Включаем запись для канала {channel_id} на секунд..."​)+    print(f"​Включаем запись для канала {channel_id} на 29 секунд..."​)
     record_url = f"​{BASE_URL}/​channels/​{channel_id}/​record"​     record_url = f"​{BASE_URL}/​channels/​{channel_id}/​record"​
     recording_name = f"​rec_{channel_id}"​     recording_name = f"​rec_{channel_id}"​
Line 729: Line 752:
         "​format":​ "​wav",​         "​format":​ "​wav",​
         "​ifExists":​ "​overwrite",​         "​ifExists":​ "​overwrite",​
-        "​maxDuration": ​5,+        "​maxDuration": ​29,
         "​terminateOn":​ "#",​         "​terminateOn":​ "#",​
         "​beep":​ True,         "​beep":​ True,
Line 772: Line 795:
  
         user_request = speech_and_text.speech_to_text(f"​{REC_PATH}{recording_name}.ogg"​)         user_request = speech_and_text.speech_to_text(f"​{REC_PATH}{recording_name}.ogg"​)
-        print(user_request)+        print(f"user_request: {user_request}"​)
  
-        context = get_channel_context(channel_id)+        ​if user_request:​ 
 +            ​context = get_channel_context(channel_id)
  
-        ​import request_to_agent +            ​import request_to_agent 
-        agent_response = request_to_agent.request_to_agent(user_request,​ SYSTEM_PROMPT,​ context) +            agent_response = request_to_agent.request_to_agent(user_request,​ SYSTEM_PROMPT,​ context) 
-        #​agent_response = user_request+            #​agent_response = user_request
  
-        ​print(agent_response)+            ​print(agent_response)
  
-        ​update_channel_context(channel_id,​ user_request,​ agent_response)+            ​update_channel_context(channel_id,​ user_request,​ agent_response)
  
-        ​print("​Текущий контекст:"​) +            ​print("​Текущий контекст:"​) 
-        from pprint import pprint +            from pprint import pprint 
-        pprint(channel_contexts)+            pprint(channel_contexts[channel_id])
  
-        ​speech_and_text.text_to_speech(agent_response,​f"​{REC_PATH}{recording_name}.response.ogg"​) +            ​speech_and_text.text_to_speech(agent_response,​f"​{REC_PATH}{recording_name}.response.ogg"​) 
-        wav_and_ogg.ogg_to_wav(f"​{REC_PATH}{recording_name}.response"​)+            wav_and_ogg.ogg_to_wav(f"​{REC_PATH}{recording_name}.response"​)
  
-        ​print(f"​Запись {recording_name} готова! Проигрываем её обратно в канал {channel_id}..."​) +            ​print(f"​Запись {recording_name} готова! Проигрываем её обратно в канал {channel_id}..."​) 
-        play_url = f"​{BASE_URL}/​channels/​{channel_id}/​play"​ +            play_url = f"​{BASE_URL}/​channels/​{channel_id}/​play"​ 
-        play_payload = { +            play_payload = { 
-            #"​media":​ f"​recording:​{recording_name}"​ +                #"​media":​ f"​recording:​{recording_name}"​ 
-            "​media":​ f"​recording:​{recording_name}.response"​ +                "​media":​ f"​recording:​{recording_name}.response"​ 
-        +            
-        response = requests.post(play_url,​ params=play_payload,​ auth=AUTH) +            response = requests.post(play_url,​ params=play_payload,​ auth=AUTH) 
-        print("​Ответ ARI на воспроизведение:",​ response.status_code)+            print("​Ответ ARI на воспроизведение:",​ response.status_code)
  
     # Сценарий 3: Воспроизведение завершено     # Сценарий 3: Воспроизведение завершено
Line 816: Line 840:
         caller_number = channel_caller_numbers[channel_id]         caller_number = channel_caller_numbers[channel_id]
         print(f"​Номер звонящего в StasisEnd: номер {caller_number} канал {channel_id}"​)         print(f"​Номер звонящего в StasisEnd: номер {caller_number} канал {channel_id}"​)
 +
 +        print(f"​Сжатие контекста"​)
 +
 +        import request_to_agent
 +        agent_response = request_to_agent.request_to_agent("​Сожми контекст",​ COMPRESS_PROMPT,​ context)
 +        print(agent_response)
 +        context = [{"​role":​ "​user",​ "​text":​ agent_response}]
  
         print(f"​Сохранение контекста и удаление медиа файлов"​)         print(f"​Сохранение контекста и удаление медиа файлов"​)
язык_программирования_python.1784120614.txt.gz · Last modified: 2026/07/15 16:03 by val