Python Forum
Problem with code / audio is playing randomly, not matching csv requirements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with code / audio is playing randomly, not matching csv requirements
#1
Hello. Greeting to you all. I'm totally new, today i wrote my very first bunch of code. I got a problem with sounds within my project. As i managed to do a simple app that helps my to classify my WMS data, im helpless with audio. Audio is kind of not related to my csv specified cells, while i organised it well.

CSV contains:
header1;header2;header3 etc
soundlink1;soundlink2;soundlink3
data1;data2;data3

When i input my data (exact EAN product code), app tells my where to put this product. This works well.

Now, i wanted to add some sounds, because i dont need to look on screen to know where to put this ean. Sound are like "put it on shelf 1", "shelf" 2 etc .

Problem is, that even if my EANs seems to work well with header, my audio is playing randomly. While text says "Put it on shelf 3", audio plays "put it on shelf 1". It doesnt relate to exact file that should be played. What's wrong in that case? Would some1 be so nice and help me with that?



PY file:

from flask import Flask, render_template, request, jsonify
import os
import pygame

app = Flask(__name__)

# Pygame
pygame.init()

#  CSV path
csv_path = os.path.join(os.path.dirname(__file__), 'dane.csv')

# get data from CSV
segments = {}
sound_paths = []

with open(csv_path, 'r') as file:
    lines = file.readlines()
    headers = lines[0].strip().split(';')
    sound_paths = lines[1].strip().split(';')
    data = lines[2:]
    for i, header in enumerate(headers):
        segments[header] = []
        for line in data:
            values = line.strip().split(';')
            segments[header].append(values[i])

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/check_segment', methods=['POST'])
def check_segment():
    input_string = request.form['input_string']

    # Index itering to choose segment
    for segment_name, values in segments.items():
        if input_string in values:
            indices = [i for i, v in enumerate(values) if v == input_string]

            if len(indices) == 1:  # if there's exact match
                index = indices[0]
                sound_path = sound_paths[index]

                # play sound
                try:
                    pygame.mixer.music.load(os.path.join('static', sound_path))
                    pygame.mixer.music.play()

                    return jsonify({'result': segment_name})

                except Exception as e:
                    print(f"Error while playing sound {e}")
                    return jsonify({'result': 'Error while playing sound.'})

    return jsonify({'result': 'There's no matching segment.'})

if __name__ == '__main__':
    app.run(debug=False)
deanhystad write Sep-07-2023, 02:02 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

Attached Files

.py   app.py (Size: 1.82 KB / Downloads: 69)
.csv   dane.csv (Size: 725 bytes / Downloads: 82)
Reply
#2
Okay, it seems that my code plays sound from A2 for each column, like it's confused with rows / columns. It should play audio from B2 if i enter code from B3, audio from C2 if i enter C3 into my app etc. Don't really know where to fix it. Any ideas?
Reply
#3
Your code is selecting a sound path based on where the input_value appears in the sequence list. Since your csv file only has 3 rows, (header, sound path, sequence[0]), the sequence lists are length 1 (each sequence list is appended 1 value for each line after lines[1]). This means indices can only be [] or [0].
indices = [i for i, v in enumerate(values) if v == input_string]  # len(values) is 1
That is why you always pick sound_path[0].

You should not care where input_value appears in the sequence list. You only need to know what sequence list contains the input_value, and then use the corresponding sound_path. Something like this:
with open('dane.csv', 'r') as file:
    lines = file.readlines()
    sound_paths = lines[1].strip().split(';')
    segments = [[] for _ in sound_paths]
    for line in lines[2:]:
        for segment, value in zip(segments, line.strip().split(';')):
            segment.append(value)
 
def get_sound(input_string):
    for sound, segment in zip(sounds_paths, segments):
       if input_string in segment:
            return sound
    return None

print(get_sound('5903726639125'))
print(get_sound('5903726639170'))
Output:
dzwiek2.mp3 dzwiek7.mp3
I think your idea of using a dictionary was a good one. You just made the wrong dictionary.
with open('dane.csv', 'r') as file:
    lines = file.readlines()
    sounds = lines[1].strip().split(';')
    segments = {}
    for line in lines[2:]:
        for segment, sound in zip(line.strip().split(';'), sounds):
            segments[segment] = sound

print(segments.get('5903726639125'))
print(segments.get('5903726639170'))
print(segments.get('invalid segment'))
Output:
dzwiek2.mp3 dzwiek7.mp3 None
This uses the segment numbers as a key for the segments dictionary, and the sound_path is the value. Notice the first line is ignored. Are the headers used somewhere else in you code? Would you ever look up a song using a header value?

Everything above assumes the .csv file might have more than 3 lines. If the csv file only has three lines, you can use shorter code.
with open("dane.csv", "r") as file:
    lines = file.readlines()
    segments = dict(zip(lines[2].strip().split(";"), lines[1].strip().split(";")))

print(segments.get("5903726639125"))
print(segments.get("5903726639170"))
print(segments.get("invalid segment"))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pyaudio seems to randomly halt input. elpidiovaldez5 2 391 Jan-22-2024, 09:07 AM
Last Post: elpidiovaldez5
  problem in matching in regex akbarza 1 408 Nov-21-2023, 09:31 AM
Last Post: snippsat
  Problem with playing sounds jderickson 5 1,290 May-25-2023, 09:52 PM
Last Post: jderickson
  when package built, requirements not installed sabuzaki 1 748 Apr-07-2023, 09:01 AM
Last Post: sabuzaki
  What to do when the requirements.txt file does not work Led_Zeppelin 2 6,451 Nov-04-2021, 06:51 PM
Last Post: snippsat
  how to take a screnshot by Pyautogui automatically and randomly rachidel07 0 3,560 Feb-03-2021, 01:16 PM
Last Post: rachidel07
  Examples of Customer requirements ComputerAstronaut 1 1,855 Dec-08-2020, 03:22 AM
Last Post: Larz60+
  requirements file tdwinfre 7 2,799 Nov-06-2020, 06:01 AM
Last Post: tdwinfre
  How to Split Output Audio on Text to Speech Code Base12 2 6,876 Aug-29-2020, 03:23 AM
Last Post: Base12
  How to allow user input only if certain requirements are met vininhosts 3 2,361 May-28-2020, 06:15 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020