help me translate this code into react native for phone:


from fastapi import FastAPI, Request, BackgroundTasks

# import paddleocr
import uvicorn
from fastapi.templating import Jinja2Templates
import numpy as np
import cv2
import random
import pygame
from pydub import AudioSegment
import logging
import os
import requests
import aiohttp
from datetime import datetime, timedelta
import csv
from pynput import keyboard
import concurrent.futures
import asyncio
import threading
from roboflow import Roboflow
from transribe import Transcriber
import re

from aiofiles import open as aioopen

language = "en"
first_boot = True

transcriber = Transcriber()
adress = "http://10.30.226.174:8088"
# adress = "http://192.168.249.182:8088"
rf = Roboflow(api_key="xq0chu47g4AXAFzn4VDl")
project = rf.workspace().project("combined_last_detection")
model = project.version(1).model
stop_recording = threading.Event()

weekdays_name = ["Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"]

templates = Jinja2Templates(directory="templates")
logging.basicConfig(
    filename="app.log",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)


TASK_STATUS = "Not started"

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
console_handler.setFormatter(formatter)
logging.getLogger().addHandler(console_handler)
template = cv2.imread("namn1.png", cv2.IMREAD_GRAYSCALE)

app = FastAPI()
# Paddleocr supports Chinese, English, French, German, Korean and Japanese.
# You can set the parameter `lang` as `ch`, `en`, `fr`, `german`, `korean`, `japan`
# to switch the language model in order.
# ocr = PaddleOCR(
#    use_angle_cls=False,
#    lang="en",
# )  # need to run only once to download and load model into memory


x, y, w, h = 100, 100, 200, 200
threshold = 400


SERVER_RESPONSE = None
long_time_no_seen = False


# async def capture_frame_async(cap):
#    loop = asyncio.get_running_loop()
#    # Run in a separate thread because VideoCapture.read() is a blocking operation
#    with concurrent.futures.ThreadPoolExecutor() as pool:
#        ret, frame = await loop.run_in_executor(pool, cap.read)
#        return ret, frame


class AudioManager:
    def __init__(self):
        self._initialized = False

    def _initialize(self):
        if not self._initialized:
            pygame.mixer.pre_init(44100, -16, 2, 2048)
            pygame.mixer.init()
            self._initialized = True

    def play_audio(self, audio_path):
        pygame.mixer.music.load(audio_path)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            pygame.time.Clock().tick(10)
        pygame.mixer.music.unload()

    async def play_audio_async(self, audio_path):
        loop = asyncio.get_running_loop()
        with concurrent.futures.ThreadPoolExecutor() as pool:
            # Correctly pass the function reference and the argument separately
            await loop.run_in_executor(pool, self.play_audio, audio_path)


audio_manager = AudioManager()
audio_manager._initialize()


async def conditional_sleep(target_interval, last_frame_change_time):
    elapsed = (datetime.now() - last_frame_change_time).total_seconds()
    sleep_time = target_interval - elapsed
    if sleep_time > 0:
        await asyncio.sleep(sleep_time)


# Image processing function
async def process_images(check_weight):
    global adress
    combined_result = []
    try:
        TASK_STATUS = "In progress"
        logging.info("The process started")
        print("started")
        url = f"{adress}/shot.jpg"
        # img_resp = requests.get(url)
        # img_arr = np.frombuffer(img_resp.content, np.uint8)
        # frame = cv2.imdecode(img_arr, -1)
        # cv2.imwrite("image.jpg", frame)
        try:
            with open("image.jpg", "rb") as f:
                # Send the file in the POST request
                files = {
                    "file": ("combined_area.png", f, "image/jpeg"),
                    "direction": (None, check_weight),
                }
                response = requests.post(
                    "http://localhost:8000/api/phone/camera",
                    files=files,
                )
        except Exception as e:
            print(e)
        print(response.text)
        combined_result = response.text
        if "-" in combined_result:
            combined_result = combined_result.replace("-", ".")
        hey_there = await generate_audio(combined_result, check_weight)
        print("wey")
        print(f"{hey_there}")
        await audio_manager.play_audio_async("audio.mp3")
        print(f"combined: {combined_result}")
        await update_csv(combined_result, check_weight, True)

        return combined_result
    except Exception as e:
        return {"error": str(e)}


async def extract_weight(text):
    # Define the regex pattern to match numbers followed by the specified units
    pattern = r"(\d+)\s*(kg|kilo|hg|hekto|gram|g)\b"

    # Find all matches in the text
    matches = re.findall(pattern, text, re.IGNORECASE)

    # Extract the first match if found
    for match in matches:
        number, unit = match
        # Check if the unit is one of the specified units
        return f"{number}"
    return None  # No match with the specified units found


async def record_audio():
    global adress, stop_recording, transcriber, check_weight
    print("Starting recording…")
    voice = None
    url = f"{adress}/audio.wav"

    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            async with aioopen("voice.mp3", "wb") as fd:
                async for chunk in response.content.iter_chunked(1024):
                    await fd.write(chunk)
                    # Check if the stop condition is set
                    if stop_recording.is_set():
                        print("Recording stopped by user.")
                        break

    print("Done recording")
    audio_text = await transcriber.transcribe_audio("voice.mp3")
    in_keywords = [
        "lägg in",
        "lägga in",
        "lagt in",
        "fått in",
        "kommit in",
        "lägg till",
    ]
    if any(keyword in audio_text.lower() for keyword in in_keywords):
        check_weight = "In"
        voice = "In"
    out_keywords = ["ta bort", "ta ur", "kasta", "slänga", "släng", "åka ut", "ta ut"]
    if any(keyword in audio_text.lower() for keyword in out_keywords):
        check_weight = "Out"
        voice = "Out"
    print(audio_text)
    print(voice)
    if voice != "In" and voice != "Out" and voice == None:
        await audio_manager.play_audio_async("Audio/help.mp3")
        return
    extracted_weight = await extract_weight(audio_text)
    print(extracted_weight)
    await generate_audio(extracted_weight, False)
    await audio_manager.play_audio_async("audio.mp3")
    await update_csv(extracted_weight, check_weight, False)

    print(audio_text)


async def start_recording():
    stop_recording.clear()
    await asyncio.gather(record_audio(), schedule_stop())


async def schedule_stop():
    await asyncio.sleep(7)
    if not stop_recording.is_set():
        print("7 seconds passed. Stopping recording.")
        stop_recording.set()


def on_press(key):
    global check_weight, first_boot
    try:
        # pynput.keyboard.KeyCode
        print("hey")
        print(key)
        if key == keyboard.Key.media_play_pause:
            print("heys")
            asyncio.run(process_images("In"))
            print("Media play/pause key pressed")
        if key == keyboard.Key.media_next:
            print("heys")
            asyncio.run(process_images("Out"))
            print("Media play/pause key pressed")
        # if key == keyboard.Key.media_play_pause:
        #    if not stop_recording.is_set():  # If recording has not been stopped yet
        #        print("Stopping recording early…")
        #        stop_recording.set()
        #        first_boot = False
        #    else:
        #        print("Starting new recording…")
        #        # Make an HTTP POST request to FastAPI endpoint to start recording
        #        requests.post("http://localhost:3333/start_recording")
        print("Alphanumeric key {0} pressed".format(key.char))
        # pynput.keyboard.Key (you can find volume keys here)
        print("Special Key {0} pressed".format(key))
        # set sound up only after 1 key press...
    except AttributeError:
        print("special key {0} pressed".format(key))


async def generate_audio(clenedUpResponse, check_weight):
    global TASK_STATUS

    if "." in clenedUpResponse:
        clenedUpResponse = clenedUpResponse.replace(".", " komma ")
    print(clenedUpResponse)
    print(type(clenedUpResponse))
    combined_audio_seg = AudioSegment.empty()
    # Generate and concatenate audio for each word
    audio_seg = AudioSegment.from_mp3(f"Audio/{check_weight}.mp3")
    combined_audio_seg += audio_seg
    clenedUpResponse = clenedUpResponse.replace('"', "")
    try:
        for text in clenedUpResponse.split():
            if text != "komma" and len(text) > 2 and text != "hundra":
                # making sure that text can never be 3 digits so formats it to 2 digits
                text = text[:2]
            if text.startswith("0") and len(text) > 1 and text[1:].isdigit():
                # Loop through each character in "text"
                for extra in text:
                    audio_filename = f"Audio/{extra}.mp3"
                    audio_seg = AudioSegment.from_mp3(audio_filename)
                    combined_audio_seg += audio_seg

            else:
                audio_filename = f"Audio/{text}.mp3"
                audio_seg = AudioSegment.from_mp3(audio_filename)
                combined_audio_seg += audio_seg
    except Exception as e:
        print(e)
    # Export the combined audio file
    audio_seg = AudioSegment.from_mp3("Audio/kilo.mp3")
    combined_audio_seg += audio_seg
    combined_audio_filename = "audio.mp3"
    combined_audio_seg.export(combined_audio_filename, format="mp3")

    return combined_audio_filename


# FastAPI endpoint to trigger async start_recording
@app.post("/start_recording")
async def api_start_recording():
    await audio_manager.play_audio_async("Audio/beep.mp3")

    asyncio.create_task(start_recording())
    return {"message": "Started recording asynchronously"}


@app.get("/audio")
async def play_audio():
    await audio_manager.play_audio_async("audio.mp3")
    return {"message": "Audio playback started on server"}


@app.get("/video")
async def video_endpoint(request: Request):
    await audio_manager.play_audio_async("audio.mp3")

    return templates.TemplateResponse("video.html", {"request": request})


async def check_picture():
    # Convert the Numpy array to an image file-like object
    try:
        result = model.predict("combined_area.png", confidence=40, overlap=30).json()

        # Sort the predictions by the "x" value
        sorted_predictions = sorted(result["predictions"], key=lambda k: k["x"])

        # Update the original result with the sorted predictions
        result["predictions"] = sorted_predictions

        classes = []

        # Loop through each sorted prediction and add the "class" to the classes list
        for prediction in sorted_predictions:
            classes.append(prediction["class"])

        # Join the classes into a single string
        classes_string = "".join(classes)
        # remove everything that's not a number from the string
        classes_string = re.sub("[^0-9.]", "", classes_string)

        number = float(classes_string)
        print(number)
        while number > 3:
            number /= 10
            decimal_places = str(number).split(".")[1] if "." in str(number) else "0"
            if len(decimal_places) >= 3:
                print("Found more than 3 decimal places.")
                number = round(number, 3)

        print(number)
        # Now times it by 10 if the numbers behind the decimal point is more than 3
        decimal_places = str(number).split(".")[1] if "." in str(number) else "0"
        if len(decimal_places) >= 3:
            print("Found more than 3 decimal places.")
            number *= 10
        number = round(number, 2)

        print(number)

    except:
        number = []
        print("no visable numbers")
        new_result = []
    return str(number)


async def update_csv(result, in_or_out, scale):
    global weekdays_name
    if in_or_out == "None":
        await audio_manager.play_audio_async("Audio/support.mp3")
        print("Kan icke vara None")
        return
    if result is None:
        print("No result to update CSV.")
        return
    week = datetime.now().isocalendar().week
    weekday = datetime.now().isocalendar().weekday
    weekday = weekdays_name[weekday - 1]
    file_name = f"{in_or_out}/{in_or_out}_Elektronik_{week}.csv"
    file_exists = os.path.isfile(f"WeeklyUpdates/{file_name}")
    #    If the file doesn't exist, create a new one with the header row
    if not file_exists:
        with open(f"WeeklyUpdates/{file_name}", "w", newline="") as csvfile:
            writer = csv.writer(csvfile, delimiter=",", quotechar='"')
            writer.writerow(["Vikt", "Datum", "Total Vikt"])
            csvfile.close()
    #    Read the existing CSV file
    with open(f"WeeklyUpdates/{file_name}", "r") as csvfile:
        reader = csv.reader(csvfile, delimiter=",", quotechar='"')
        rows = list(reader)
    #    Check if the date already exists
    #    Add the weights for the current date
    total_weight = 0
    for row in rows:
        if any(keyword in weekdays_name for keyword in weekday):
            total_weight += float(row[0])
    try:
        while float(result) > 30.0 and scale:
            result = float(result) / 10
    except ValueError as ve:
        print(f"Error converting result to float: {ve}")
        # Handle the error or return from the function
    # Round the result to 2 decimal places
    result = round(float(result), 2)
    total_weight += float(result)
    rows.append([str(result), weekday, round(total_weight, 2)])
    #    Write the updated rows to the CSV file
    with open(f"WeeklyUpdates/{file_name}", "w", newline="") as csvfile:
        writer = csv.writer(csvfile, delimiter=",", quotechar='"')
        writer.writerows(rows)
    return "Done"


def start_pynput_listener():
    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()


# When the FastAPI application starts, run the pynput listener in an executor
@app.on_event("startup")
def start_listener_on_startup():
    loop = asyncio.get_running_loop()
    stop_recording.set()

    listener_thread = loop.run_in_executor(None, start_pynput_listener)



const WalkthroughAppConfig = {
  onboardingConfig: {
    walkthroughScreens: [
      {
        icon: require("../assets/plane.png"),
        title: "Example",
        description: "Weight:",
      },
    ],
  },
};

export default WalkthroughAppConfig;