How to convert audio bytes generated by mediaRecorder and transfered using websocket to python to numpy array

I have a simple WebSocket project created by FastAPI like the following code:

import uvicorn
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
import numpy as np
import soundfile as sf


app = FastAPI()

html = """
<!DOCTYPE html>
<html>
    <body>
        <h1>Transcribe Audio With FastAPI</h1>
        <p id="status">Connection status will go here</p>
        <p id="transcript"></p>
        <script>
               navigator.mediaDevices.getUserMedia({ audio: { sampleSize: 16, channelCount: 1, sampleRate: 16000 } }).then((stream) => {
            if (!MediaRecorder.isTypeSupported('audio/webm'))
                return alert('Browser not supported')

            const mediaRecorder = new MediaRecorder(stream, {
                mimeType: 'audio/webm',
            })

            const socket = new WebSocket('ws://localhost:8000/listen')

            socket.onopen = () => {
                document.querySelector('#status').textContent = 'Connected'
                console.log({ event: 'onopen' })
                mediaRecorder.addEventListener('dataavailable', async (event) => {
                    if (event.data.size > 0 && socket.readyState == 1) {
                        socket.send(event.data)
                    }
            })
            mediaRecorder.start(250)
            }

            socket.onmessage = (message) => {
                const received = message.data
                if (received) {
                    console.log(received)
                    document.querySelector('#transcript').textContent += ' ' + received
                }
           }

           socket.onclose = () => {
            console.log({ event: 'onclose' })
        }

            socket.onerror = (error) => {
                console.log({ event: 'onerror', error })
            }

           })
        </script>
    </body>
</html>
"""


@app.get("/")
async def get():
    return HTMLResponse(html)


@app.websocket("/listen")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    try:
        while True:
            data = await websocket.receive_bytes()
            print(data)
            # Convert data to numpy array
            # rest of the process!
    except Exception as e:
        raise Exception(f'Could not process audio: {e}')
    finally:
        await websocket.close()


if __name__ == '__main__':
    uvicorn.run(app)

After running the project, I want to convert data to a numpy array.

What I have tried:
1)

def tensorize(x):
    arr = np.frombuffer(x, dtype=np.float32)
    # copy to avoid warning
    arr = np.copy(arr)
    return arr

@app.websocket("/listen")
async def websocket_endpoint(websocket: WebSocket):
    print("I'm here websocket_endpoint")
    await websocket.accept()

    try:
        # deepgram_socket = await process_audio(websocket)
        whole = []
        counter = 0
        while True:
            data = await websocket.receive_bytes()
            array = tensorize(data)
    except Exception as e:
        raise Exception(f'Could not process audio: {e}')
    finally:
        await websocket.close()

raises error:

arr = np.frombuffer(x, dtype=np.float32)
ValueError: buffer size must be a multiple of element size
@app.websocket("/listen")
async def websocket_endpoint(websocket: WebSocket):
    print("I'm here websocket_endpoint")
    await websocket.accept()

    try:
        # deepgram_socket = await process_audio(websocket)
        whole = []
        counter = 0
        while True:
            data = await websocket.receive_bytes()
            data_s16 = np.frombuffer(data, dtype=np.int16, count=len(data) // 2, offset=0)
            float_data = data_s16 * 0.5 ** 15
            whole.append(float_data)
            print(data)
            counter += 1
            if counter > 20:
                data = np.concatenate(whole)
                sf.write('stereo_file1.wav', data, 16000, 'PCM_24')
                break
            print(counter)
            # await websocket.send_text(f"Message text was: {data}")
            # deepgram_socket.send(data)
    except Exception as e:
        raise Exception(f'Could not process audio: {e}')
    finally:
        await websocket.close()

This sample code does not raise any errors, but the output audio file does not contain any perceivable audio. Just noise is saved.

Is it possible to have a constructor function as a method in a class?

In the following example the constructor function which creates a new node (here named Node) lies outside the class whose method calls it:

class Collection {

  constructor() {
    this.collection = [];
  };

  addNode(value) {
    const node = new Node(value);
    this.collection.push(node);
    console.log(this.collection);
  };
};

function Node(value) {
  this.value = value;
}

const col = new Collection();

col.addNode("foo");

However, I’d like to have the constructor function inside the class (mainly because it’s only used by that class). This will fail (x is not a constructor):

class Collection {

  constructor() {
    this.collection = [];
  };

  Node(value) {
    this.value = value;
  };

  addNode(value) {
    const node = new this.Node(value);
    this.collection.push(node);
    console.log(this.collection);
  };
};

const col = new Collection();

col.addNode("foo");

I’m also aware that Javascript currently does not support nested classes. What I’m currently doing is simply declaring the Node constructor inside the addNode method.

But I’m curious: is it possible to have such constructor function iside the class that calls it?

MockAPI doesn’t receive data as expected

I’m using mockAPI to create an api for my project, but when i use .POST method to send data, mockAPI doesn’t receive it.

Data I send

const product = {
    "address": "commune, district, province",
    "date": "24/10/2022",
    "email": "[email protected]",
    "id": 3879042658,
    "name": "Mr. Cabin",
    "note": "please take care",
    "phone": "1234567890",
    "products": [
        {id: 1, soLuong: 3}
    ]
}]

I use fetch to send data

function addOrders() {
    fetch('API-MOCKAPI URL', {
        method: 'POST',
        body: JSON.stringify(product)
    .then(res => res.json())
    .then(result => {
        console.log(result)
    })
}

Response I receive

{id: 64, name: 'name 3', email: 'email 3', phone: 'phone 3', address: 'address 3', product: []}

Nuxt same instance of class server and client

I am building a library to be shared across my Nuxt projects the one thing I’m stuck with is for example my library contains the class

class MyLibrary {
  setCredentials(creds) {
    this.creds = creds;
  }
  
  getCredentials() {
    return this.creds;
  }
}

On the server side when I call setCredentials() and getCredentials() it returns fine, but after that when I do getCredentials() on the client side it returns undefined. What I gathered is that there are two instances of MyLibrary (class), one on the server and one on the client…

Is there a simple way to make sure both of them are sharing the same instance? It doesn’t work even if I inject it into nuxt and use it like this.$myLibrary.setCredentials()

Removing items from an array in both directions

I have an array of times (these are not constant) [1:00, 2:00, 3:00, 4:00, 5:00, 6:00, 7:00]. The goal is to calculate times that can be bookable. If there is an existing booking from 4:00 - 5:00 then 3:00 should be unavailable as it would overlap the existing booking. To calculate this, I have a function that tells us the start and end indexes of the booking, I need to find a way to remove x times from behind the start index.

To make it more clear, I drew a diagram.

problem diagram

Doing this calculation will allow to calculate available times no matter how long the existing booking is. I’m trying to figure out how to create a function that does what I described. Below is the code I have to return the available times based on the start/end index provided however I’m stuck on how to approach the calculation I described above.

 // This filters times that are less than the start index
 const filteredTimes1 = availableHours.filter((item, index) => index < (
      (startTimeIndex || availableHours.length - 0)
 ))
 
 // This filters times that greater than the end index
 const filteredTimes2 = availableHours.filter((item, index) => 
     index > (endTimeIndex || availableHours.length) 
 )
 
 // Then combine the results into an array
 const validAvailableHours = [...filteredTimes1 , ...filteredTimes2]

Any help would be appreciated, thanks.

How to update role based on email login

Hello guys i have a MERN project, in this project user will be able to register, login, and do some CRUD operations. After user login they will redirect to homepage.

All the user that register will have a User role, the issue is i want to create role based on their email, if user login with [email protected] that user will have role Admin, if not the role stay the same.

The code below, i tried to find the email with regex, its working if bsi is in the email. But if there is no bsi in the email, its not working. I tried to find if else for this problem but icant find any. Is there a way to solve this ?

Code :

app.post("/register", async (req, res) => {
    bcrypt
    .hash(req.body.password, 10)
    .then((hashedPassword) => {
      // create a new user instance and collect the data
      const user = new UserModel({
        email: req.body.email,
        password: hashedPassword,
        role : "User"
      });
      // save the new user
      user
        .save()
        // return success if the new user is added to the database successfully
        .then((result) => {
          res.status(201).send({
            message: "User Created Successfully",
            result,
          });
        })
        // catch error if the new user wasn't added successfully to the database
        .catch((error) => {
          res.status(500).send({
            message: "Error creating user",
            error,
          });
        });
    })
    // catch error if the password hash isn't successful
    .catch((e) => {
      res.status(500).send({
        message: "Password was not hashed successfully",
        e,
      });
    });
});

app.post("/login", (req, res) => {

  // UserModel.findOneAndUpdate({ email: req.body.email }).then((user)

  UserModel.findOneAndUpdate({ email: { $regex : "bsi"} }, {$set : {"role" : "Admin"}}).then((user) => {
        bcrypt.compare(req.body.password, user.password).then((passwordCheck) => {

            if(!passwordCheck) {
              return res.status(400).send({
                message: "Passwords does not match",
                error,
                result,
              });
            }
            const token = jwt.sign(
                {
                  userId: user._id,
                  userEmail: user.email,
                },
                "RANDOM-TOKEN",
                { expiresIn: "24h" }
              );

            const result = {email : user.email}
            req.session.email = result
            const role = user.role
            req.session.role = role
            res.status(200).send({
                message: "Login Successful",
                email: user.email,
                result,
                role,
                token
            });
            }).catch((error) => {
                res.status(400).send({
                message: "Passwords does not match",
                error
            });
            });
            }).catch((e) => {
                res.status(404).send({
                message: "Email not found",
                e,
        });
    });
});

Vue JS – Can’t access props on the mounted hook

In allImport.vue page I am passing props like that:

<sidebarProductDetails :row="singleRow" />

sidebarProductDetails.vue page I have this code:

<template>
    <div>
        <pre>{{ row }}</pre>
        <!-- I can see all the data in this row object -->
        </b-row>
    </div>
</template>

<script>
import { Swiper, SwiperSlide } from "vue-awesome-swiper";
import { BImg } from "bootstrap-vue";
import "swiper/css/swiper.css";

export default {
    props: ['row'],
    data() {        
    },
    components: {
        Swiper,
        SwiperSlide,
        BImg,
    },    
    mounted() {
       console.log(this.row);
       // Can't get anyting showing me undefined
    },
};
</script>

Here you can see the I just log the row props on the mounted hook but nothing is showing. The interesting things is that I can see all the data inside the wrapper.

Is there anything I am dong wrong?

Updating variables with Discord.JS

I’m trying to work out how to update variables that are declared at runtime.

In my code it’s a simple random number generator. It works but doesn’t update, i.e. if the slash command /rng is used, alpha never updates past the initial number it picked, so it just repeats the same number at each use of /rng and I understand why. At the initial run, alpha is updated to a random number but it’s never updated again unless the script is ran again which isn’t possible in it’s current configuration unless I restart the bot.

I’m not even looking for someone to fix the code, more so a concept I can go look up or read into so I can learn.

const { SlashCommandBuilder } = require('discord.js');

const alpha = Math.floor(Math.random() * 11);
console.log(alpha);

module.exports = {
    data: new SlashCommandBuilder()
        .setName('rng')
        .setDescription('Number between 1 & 10'),
    async execute(interaction) {
        await interaction.reply(`${alpha}`);
    },
};

React calls custom class’s constructor many times and with weird params

hope you’re having a good day 😀

I’m trying to make a Grid data structure based on the Array class, I intended to add custom methods and properties, so I started with a simple Test class:

import { useState } from 'react'

class Grid extends Array {
  constructor(data) {
    console.log('called with', arguments);
    super(...data)
  }
}

function App() {
  const [ count ] = useState(new Grid([1,2,3]))

  return (
    <div className="App">
      {count.map(row => <p key={row.rowId}>
        row {row}
      </p>)}

    </div>
  )
}

export default App

My final goal was to encapsulate all the logic inside the class but when I imported it in the app it started crashing:

These are the logs I got from the chrome console:

App.jsx:5 called with Arguments [Array(3), callee: (...), Symbol(Symbol.iterator): ƒ]
App.jsx:5 called with Arguments [3, callee: (...), Symbol(Symbol.iterator): ƒ]
App.jsx:5 called with Arguments [Array(3), callee: (...), Symbol(Symbol.iterator): ƒ]
App.jsx:5 called with Arguments [3, callee: (...), Symbol(Symbol.iterator): ƒ]

App.jsx:6 Uncaught TypeError: Found non-callable @@iterator
    at new Grid (App.jsx:6:5)
    at Grid.map (<anonymous>)
    at App (App.jsx:15:14)
    at renderWithHooks (react-dom.development.js:14985:18)
    at mountIndeterminateComponent (react-dom.development.js:17811:13)
    at beginWork (react-dom.development.js:19049:16)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:3945:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:16)
    at invokeGuardedCallback (react-dom.development.js:4056:31)
    at beginWork$1 (react-dom.development.js:23964:7)

As you may see, the constructor got called a lot of times, some times using the last item of the provided array…
Is this some React related behavior?

Import statements breaks script setup Nuxtjs 3

it seems that when I’m using the import statement in the <script setup> all code below it stops working.

I installed the @heroicons package and use the import statement to use it as a component in my <template>. But everything below the import statements does not work anymore. My code:

<template>
    <HomeIcon class="w-5 h-5">
    <h1>{{myName}}</h1>
</template>

<script setup>
    import {HomeIcon} from '@heroicons/vue/24/outline'

    const myName = ref('username')
</script>

When running the code above I do not see “username” as a heading as specified in my code. I also see a eslint warning “myName is declared but it’s value is never read”. The moment I comment the import statement, the myName ref seems to work again.

What I use:

  • VS Code
  • Nuxtjs 3
  • Tailwind CSS
  • Heroicons package
  • PNPM as package manager

What is the error “options.map is not a function”?

import React, { useState } from 'react'
export const BreedsSelect = props => {
  const [selectedBreed, setSelectedBreed] = useState(null)

  const options = props.breeds

  return (
    <div>
      <select
        value={selectedBreed}
        onChange={e => setSelectedBreed(e.target.value)}
      >
        {options?.map(breed => {
          ;<option>{breed}</option>
        })}
      </select>
    </div>
  )
}

In the above code I get an error that options.map is not a function. How can this be resolved?
The following code calls the above code.

import React, { useEffect, useState } from 'react' // DO NOT DELETE
import { BreedsSelect } from './BreedsSelect'
export const DogListContainer = () => {
  const [breeds, setBreeds] = useState(null)
  useEffect(() => {
    fetch('https://dog.ceo/api/breeds/list/all')
      .then(res => res.json())
      .then(data => {
        setBreeds(data.message)
      })
  }, [])
  return <BreedsSelect breeds={breeds} />
}

reset interval on countdown

Being new to codes and not knowing how to make a more elaborate code, I would like to know if every time the count restarts there is a clean interval (if there is a reset every time it restarts). I have to do the reading on the i and when the i is 7 it clicks.

let i = 7;
let button = 'clicked'

const myFn = () => {
  i--
  if (i === 0) {
    click()
    i = 7 // restart interval
  }
  console.log(i);
};

function click() {
  console.log(button)
}

let myTimer = setInterval(myFn, 1000);

//...
clearInterval(myTimer);
myTimer = setInterval(myFn, 1000);

Is eval dangerous running code in an online IDE and is it safe to store the code in the database?

I want to build a website that would also include an online IDE where users can run some JavaScript code and run it. It would only run on the client side.

My concerns are:

  1. I would have some of my functions defined on the client-side that I want the users to run. Would it be harmful then if they called eval()? Is there any other solution if I want those functions to be accessible for them?

  2. Is it safe to store their custom code in the database (mongodb)? When they access a page where they wrote some code in the IDE, I want that code to load.

I know there are pages like this, where users write code, the code is saved for them, they can run it and also call custom functions defined on the client-side, but I am not sure what is the best approach to create something similar as I am concerned with the security.