-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducer.py
executable file
·58 lines (48 loc) · 1.7 KB
/
producer.py
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
import os
import logging
from confluent_kafka import Producer
# Set up logging
logging.basicConfig(level=logging.INFO)
# Local file system base directory
base_directory = "./fma_small"
# Kafka details
bootstrap_servers = "localhost:9092"
topic = "streamed_music_local"
# Create a Kafka producer
producer = Producer(
{
"bootstrap.servers": bootstrap_servers,
"message.max.bytes": 11210584,
"queue.buffering.max.messages": 100000,
}
)
# Counter for messages
message_counter = 0
def get_songs_from_directory(directory):
"""Generator to read song files from a given directory"""
try:
for filename in os.listdir(directory):
if filename.endswith(".mp3"):
filepath = os.path.join(directory, filename)
with open(filepath, "rb") as file:
yield file.read(), filename
except FileNotFoundError:
logging.error(f"Directory not found: {directory}")
return
except Exception as e:
logging.error(f"Failed to read songs from directory {directory}: {e}")
return
for i in range(156):
directory = os.path.join(base_directory, f"{i:03d}")
# Send the blobs (songs) in the directory to the Kafka topic
for song, filename in get_songs_from_directory(directory):
if song is not None and len(song) > 0:
producer.produce(topic, key=filename.encode(), value=song)
message_counter += 1
print(f"Sent song: {filename}")
if message_counter % 50 == 0:
producer.flush()
else:
logging.warning(f"Empty or missing song: {filename}")
producer.flush()
logging.info(f"Total {message_counter} messages sent.")