Python va Openai yordamida inson nutqini idrok etuvchi sun'iy intellekt dasturi


Download 19.92 Kb.
Sana18.06.2023
Hajmi19.92 Kb.
#1590939
Bog'liq
AI


Python va OpenAI yordamida inson nutqini idrok etuvchi sun'iy intellekt dasturi
Bu dastur nima qiladi

  • Foydalanuvchi savol berishga tayyor bo'lganda fayl buyruq qatori orqali ishga tushiriladi.

  • PyAudio kompyuter mikrofoniga nutq ma'lumotlarini olish imkonini beradi.

  • Ovozli ma'lumotlar oqim deb nomlangan o'zgaruvchida saqlanadi, keyin kodlanadi va JSON ma'lumotlariga aylantiriladi.

  • JSON ma'lumotlari matnga aylantirish uchun AssemblyAI API ga uzatiladi, shundan so'ng matn ma'lumotlari qaytarib yuboriladi.

  • Matn ma'lumotlari OpenAI API-ga yuboriladi va keyin qayta ishlash uchun text-davinci-002 dvigateliga yuboriladi.

  • Savolga javob olinadi va so'ralgan savol ostidagi konsolda ko'rsatiladi.


Birinchidan, biz dastur tomonidan ishlatiladigan barcha kutubxonalarni import qilamiz. Ulardan ba'zilari Pipni o'rnatishni talab qilishi mumkin (ulardan foydalanganligingizga qarab). Quyidagi kod bo'yicha sharhlarga e'tibor bering:
#PyAudio PortAudio v19 uchun Python ulanishini ta'minlaydi, bu o'zaro platforma audio I/U kutubxonasi. Kompyuterning mikrofoniga Python bilan muloqot qilish imkonini beradi
pyaudio import

Websocket serverini yaratish uchun #Python kutubxonasi - foydalanuvchi brauzeri va server o'rtasidagi ikki tomonlama interaktiv aloqa seansi


veb-soketlarni import qilish

#asyncio - async/await sintaksisidan foydalangan holda parallel kod yozish uchun kutubxona


import asyncio

#Ushbu modul ikkilik maʼlumotlarni bosib chiqarish mumkin boʻlgan ASCII belgilarga kodlash va bunday kodlashlarni ikkilik maʼlumotlarga dekodlash funksiyalarini taqdim etadi.


import bazasi 64

#Python-da JSON ma'lumotlari bilan ishlash uchun ishlatilishi mumkin bo'lgan o'rnatilgan json paketi mavjud


json import

# Boshqa fayldan "Pull" funksiyasi


openai_helper import ask_computer dan
Файл: Main.py

import pyaudio


import websockets
import asyncio
import base64
import json
from openai_helper import ask_computer

FRAMES_PER_BUFFER = 3200


FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000

p = pyaudio.PyAudio()

# starts recording
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=FRAMES_PER_BUFFER
)

print(p.get_default_input_device_info())

# the AssemblyAI endpoint we're going to hit
URL = "wss://api.assemblyai.com/v2/realtime/ws?sample_rate=16000"
auth_key = "enter here"

async def send_receive():


print(f'Connecting websocket to url ${URL}')
async with websockets.connect(
URL,
extra_headers=(("Authorization", auth_key),),
ping_interval=5,
ping_timeout=20
) as _ws:
await asyncio.sleep(0.1)
print("Receiving SessionBegins ...")
session_begins = await _ws.recv()
print(session_begins)
print("Sending messages ...")
async def send():
while True:
try:
data = stream.read(FRAMES_PER_BUFFER, exception_on_overflow=False)
data = base64.b64encode(data).decode("utf-8")
json_data = json.dumps({"audio_data":str(data)})
await _ws.send(json_data)
except websockets.exceptions.ConnectionClosedError as e:
print(e)
assert e.code == 4008
break
except Exception as e:
assert False, "Not a websocket 4008 error"
await asyncio.sleep(0.01)

return True

async def receive():
while True:
try:
result_str = await _ws.recv()
result = json.loads(result_str)
prompt = result['text']
if prompt and result['message_type'] == 'FinalTranscript':
print("Me:", prompt)
answer = ask_computer(prompt)
print("Bot", answer)
except websockets.exceptions.ConnectionClosedError as e:
print(e)
assert e.code == 4008
break
except Exception as e:
assert False, "Not a websocket 4008 error"

send_result, receive_result = await asyncio.gather(send(), receive())


asyncio.run(send_receive())



Файл: openai_helper.py
import openai

openai.api_key = "enter here"



def ask_computer(prompt):
#return "This is my answer"
# prompt = "What is your favorite color?"
res = openai.Completion.create(
engine="text-davinci-002",
prompt=prompt,
)
# print(res)
return res["choices"][0]["text"]
Download 19.92 Kb.

Do'stlaringiz bilan baham:




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling