Python'dan mikrofonla kaydedilen dosyayı. WAV olarak kaydedip assemblyai a gönderip yazı olarak alan bir kod yazdım ama Arduino'ya yazıyı gönderip LCD'ye yazdıramıyorum aynı anda iki şey com3'ü kullanamaz diyor
İmport PyAudio
İmport wave
İmport requests
İmport JSON
İmport time
İmport UUID # For generating unique filenames
İmport OS
İmport Serial
Ser = Serial. Serial('COM3', 9600, timeout = 1) # Adjust COM port as needed
# AssemblyAI API Config
ASSEMBLYAI_API_KEY = 'F23aEA7876D845bba0C9a3F282E8Dfef' # <-- Put your AssemblyAI API key here
UPLOAD_ENDPOINT = 'https://api.assemblyai.com/v2/upload'
TRANSCRIPT_ENDPOINT = 'https://api.assemblyai.com/v2/transcript'
Headers_auth = {
'Authorization': ASSEMBLYAI_API_KEY,
'Content-type': 'application/json'
}
# Function to generate a random filename
Def generate_random_filename(extension="WAV"):
Random_name = str(uuid.uuid4()) # Use UUID for uniqueness
Global nameoffile
Nameoffile = F"{random_name}.{extension}"
Return nameoffile
# Function to record Audio from the microphone
Def record_audio(filename, duration = 5):
FORMAT = PyAudio. PaInt16
CHANNELS = 1
RATE = 16000
CHUNK = 1024
RECORD_SECONDS = duration
WAVE_OUTPUT_FILENAME = filename
P = pyaudio.PyAudio()
Stream = p. Open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = CHUNK)
Print("Recording...")
Frames = []
For _ in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
Data = stream. Read(CHUNK)
Frames. Append(data)
Print("Recording finished.")
stream.stop_stream()
stream.close()
p.terminate()
With wave. Open(WAVE_OUTPUT_FILENAME, 'wb') as wf:
Wf. Setnchannels(CHANNELS)
Wf. Setsampwidth(p. Get_sample_size(FORMAT))
Wf. Setframerate(RATE)
Wf. Writeframes(b".join(frames))
# Function to upload Audio file to AssemblyAI
Def upload_audio(filename):
With open(filename, 'RB') as F:
Print("Uploading Audio...")
Response = requests. Post(UPLOAD_ENDPOINT, headers={'authorization': ASSEMBLYAI_API_KEY}, data = F)
İf response. Status_code == 200:
Upload_url = response.json()['upload_url']
Print("Upload successful.")
Return upload_url
Else:
Print(F"Upload failed: {response. Status_code} {response. Text}")
Return None
# Function to request transcription from AssemblyAI
Def request_transcription(upload_url):
Json_data = {
'Audio_url': Upload_url
}
Response = requests. Post(TRANSCRIPT_ENDPOINT, JSON = json_data, headers = headers_auth)
İf response. Status_code == 200:
Transcript_id = response.json()['id']
Print(F"Transcription requested. ID: {transcript_id}")
Return transcript_id
Else:
Print(F"Transcription request failed: {response. Status_code} {response. Text}")
Return None
# Function to poll transcription result
Def poll_transcription(transcript_id, timeout = 60, poll_interval = 3):
Polling_endpoint = F"{TRANSCRIPT_ENDPOINT}/{transcript_id}"
Print("Polling for transcription result...")
Start_time = time.time()
While True:
Response = requests. Get(polling_endpoint, headers = headers_auth)
İf response. Status_code!= 200:
Print(F"Polling error: {response. Status_code} {response. Text}")
Return None
Result = response.json()
Status = result['status']
İf status == 'completed':
Print("Transcription completed.")
Return result. Get('text', ")
Elif status == 'error':
Print(F"Transcription error: {result. Get('error', 'Unknown error')}")
Return None
Else:
# Still processing
İf time.time() - start_time > timeout:
Print("Transcription polling timed out.")
Return None
Time. Sleep(poll_interval)
# Function to print the transcript
Def print_transcript(transcript):
İf transcript:
Print(transcript)
Else:
Print("No transcription available.")
OS. Remove(nameoffile) # Clean up the Audio file after transcription
Def main():
Audio_filename = generate_random_filename("WAV")
Record_audio(audio_filename, duration = 5)
Upload_url = upload_audio(audio_filename)
İf not upload_url:
Return
Transcript_id = request_transcription(upload_url)
İf not transcript_id:
Return
Transcript = poll_transcription(transcript_id)
Print_transcript(transcript)
Ser. Write((transcript + '\n').encode('utf-8'))
ser.flush()
Time. Sleep(1) # Give some time for the Arduino to process the data
İf name == "main":
While True:
main()
#İnclude <Wire.h>
#İnclude <LiquidCrystal_I2C.h>
LiquidCrystal_I2C LCD(0x20, 16, 2); // Your LCD address might be 0x27 — double check!
String buffer = "";
Void setup() {
Serial. Begin(9600);
Delay(1000);
LCD. Begin(16, 2);
lcd.backlight(); // Turn on LCD backlight
}
Void loop() {
While (Serial.available()) {
Char C = Serial.read();
İf (C == '\n') {
lcd.clear();
LCD. SetCursor(0, 0);
// If text is longer than 16 characters, split across lines
LCD. Print(buffer. Substring(0, 16));
İf (buffer.length() > 16) {
LCD. SetCursor(0, 1);
LCD. Print(buffer. Substring(16, 32));
}
Buffer = ""; // Reset buffer after displaying
} Else {
Buffer += C;
}
}
}
İmport PyAudio
İmport wave
İmport requests
İmport JSON
İmport time
İmport UUID # For generating unique filenames
İmport OS
İmport Serial
Ser = Serial. Serial('COM3', 9600, timeout = 1) # Adjust COM port as needed
# AssemblyAI API Config
ASSEMBLYAI_API_KEY = 'F23aEA7876D845bba0C9a3F282E8Dfef' # <-- Put your AssemblyAI API key here
UPLOAD_ENDPOINT = 'https://api.assemblyai.com/v2/upload'
TRANSCRIPT_ENDPOINT = 'https://api.assemblyai.com/v2/transcript'
Headers_auth = {
'Authorization': ASSEMBLYAI_API_KEY,
'Content-type': 'application/json'
}
# Function to generate a random filename
Def generate_random_filename(extension="WAV"):
Random_name = str(uuid.uuid4()) # Use UUID for uniqueness
Global nameoffile
Nameoffile = F"{random_name}.{extension}"
Return nameoffile
# Function to record Audio from the microphone
Def record_audio(filename, duration = 5):
FORMAT = PyAudio. PaInt16
CHANNELS = 1
RATE = 16000
CHUNK = 1024
RECORD_SECONDS = duration
WAVE_OUTPUT_FILENAME = filename
P = pyaudio.PyAudio()
Stream = p. Open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = CHUNK)
Print("Recording...")
Frames = []
For _ in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
Data = stream. Read(CHUNK)
Frames. Append(data)
Print("Recording finished.")
stream.stop_stream()
stream.close()
p.terminate()
With wave. Open(WAVE_OUTPUT_FILENAME, 'wb') as wf:
Wf. Setnchannels(CHANNELS)
Wf. Setsampwidth(p. Get_sample_size(FORMAT))
Wf. Setframerate(RATE)
Wf. Writeframes(b".join(frames))
# Function to upload Audio file to AssemblyAI
Def upload_audio(filename):
With open(filename, 'RB') as F:
Print("Uploading Audio...")
Response = requests. Post(UPLOAD_ENDPOINT, headers={'authorization': ASSEMBLYAI_API_KEY}, data = F)
İf response. Status_code == 200:
Upload_url = response.json()['upload_url']
Print("Upload successful.")
Return upload_url
Else:
Print(F"Upload failed: {response. Status_code} {response. Text}")
Return None
# Function to request transcription from AssemblyAI
Def request_transcription(upload_url):
Json_data = {
'Audio_url': Upload_url
}
Response = requests. Post(TRANSCRIPT_ENDPOINT, JSON = json_data, headers = headers_auth)
İf response. Status_code == 200:
Transcript_id = response.json()['id']
Print(F"Transcription requested. ID: {transcript_id}")
Return transcript_id
Else:
Print(F"Transcription request failed: {response. Status_code} {response. Text}")
Return None
# Function to poll transcription result
Def poll_transcription(transcript_id, timeout = 60, poll_interval = 3):
Polling_endpoint = F"{TRANSCRIPT_ENDPOINT}/{transcript_id}"
Print("Polling for transcription result...")
Start_time = time.time()
While True:
Response = requests. Get(polling_endpoint, headers = headers_auth)
İf response. Status_code!= 200:
Print(F"Polling error: {response. Status_code} {response. Text}")
Return None
Result = response.json()
Status = result['status']
İf status == 'completed':
Print("Transcription completed.")
Return result. Get('text', ")
Elif status == 'error':
Print(F"Transcription error: {result. Get('error', 'Unknown error')}")
Return None
Else:
# Still processing
İf time.time() - start_time > timeout:
Print("Transcription polling timed out.")
Return None
Time. Sleep(poll_interval)
# Function to print the transcript
Def print_transcript(transcript):
İf transcript:
Print(transcript)
Else:
Print("No transcription available.")
OS. Remove(nameoffile) # Clean up the Audio file after transcription
Def main():
Audio_filename = generate_random_filename("WAV")
Record_audio(audio_filename, duration = 5)
Upload_url = upload_audio(audio_filename)
İf not upload_url:
Return
Transcript_id = request_transcription(upload_url)
İf not transcript_id:
Return
Transcript = poll_transcription(transcript_id)
Print_transcript(transcript)
Ser. Write((transcript + '\n').encode('utf-8'))
ser.flush()
Time. Sleep(1) # Give some time for the Arduino to process the data
İf name == "main":
While True:
main()
#İnclude <Wire.h>
#İnclude <LiquidCrystal_I2C.h>
LiquidCrystal_I2C LCD(0x20, 16, 2); // Your LCD address might be 0x27 — double check!
String buffer = "";
Void setup() {
Serial. Begin(9600);
Delay(1000);
LCD. Begin(16, 2);
lcd.backlight(); // Turn on LCD backlight
}
Void loop() {
While (Serial.available()) {
Char C = Serial.read();
İf (C == '\n') {
lcd.clear();
LCD. SetCursor(0, 0);
// If text is longer than 16 characters, split across lines
LCD. Print(buffer. Substring(0, 16));
İf (buffer.length() > 16) {
LCD. SetCursor(0, 1);
LCD. Print(buffer. Substring(16, 32));
}
Buffer = ""; // Reset buffer after displaying
} Else {
Buffer += C;
}
}
}
Son düzenleyen: Moderatör: