<gh_stars>0
import requests
import os
import time
import json
import logging
import http.client
import cProfile
import pstats
from requests.sessions import session
import socket
import requests.packages.urllib3.util.connection as urllib3_cn
import httpx
import asyncio
import glob
from inference import InputY

# http.client.HTTPConnection.debuglevel = 1
# logging.basicConfig()
# logging.getLogger().setLevel(logging.DEBUG)
# requests_log = logging.getLogger('requsets.packages.urllib3')
# requests_log.setLevel(logging.WARNING)
# requests_log.propagate = True

class requestInference:

    def __init__(self):
        self._set_ipv4()
        self.url_eol_wav = 'http://localhost:8000/eol/wav'
        self.url_hello = 'http://localhost:8000/hello'


    def _set_ipv4(self):
        def allowed_gai_family():
            """
                https://github.com/shazow/urllib3/blob/master/urllib3/util/connection.py
            """
            return socket.AF_INET       #* this to force use ipv4 (issue with ipv6, get 2s delay)
        urllib3_cn.allowed_gai_family = allowed_gai_family


    def call_api_from_wav_file(self, file_path):
        files = {'wav': open(file_path, 'rb')}
        try:
            r = requests.post(self.url_eol_wav, files=files)
        except requests.exceptions.Timeout:
            r = requests.post(self.url_eol_wav, files=files)
            print(f'this is 2nd time retry to connect to API')
        except requests.exceptions.TooManyRedirects:
            print(f'The URL was bad and try a different one')
        except requests.exceptions.RequestException as e:
            # catastrophic error. bail.
            raise SystemExit(e)
        return r.json()


    def call_api_from_wav_with_profiling(self, file_path,  profiling_fp:str):
        with cProfile.Profile() as pr_:
            response = self.call_api_from_wav_file(file_path)

        stats = pstats.Stats(pr_)
        stats.sort_stats(pstats.SortKey.TIME)
        stats.dump_stats(filename=profiling_fp)
        return response


    def call_api_from_y(self, y, time, sn, load, direction, product, start_cut, end_cut):
        input_y = InputY(
                        y=y,time = time, sn=sn, load = load, direction=direction,
                        product=product, start_cut=start_cut,end_cut=end_cut,
                        )
        files = {'input_y': input_y}
        try:
            r = requests.post(self.url_eol_wav, files=files)
        except requests.exceptions.Timeout:
            r = requests.post(self.url_eol_wav, files=files)
            print(f'this is 2nd time retry to connect to API')
        except requests.exceptions.TooManyRedirects:
            print(f'The URL was bad and try a different one')
        except requests.exceptions.RequestException as e:
            # catastrophic error. bail.
            raise SystemExit(e)
        return r.json()


    def call_api_from_wav_with_log(self,file_path, log_file_path):
        t1 = time.time()
        response = self.call_api_from_wav_file(file_path)
        t2 = time.time()
        self._update_log_file(log_file_path, str(round((t2-t1),3)))
        

    def process_one_wav_folder(self, wav_folder, log_file_path):
        file_lists = glob.glob(wav_folder + '\*.wav')
        logging.info(f'processing {len(file_lists)} wav files..')
        for file_path in file_lists:
            self.call_api_from_wav_with_log(file_path, log_file_path)


    def _update_log_file(self, log_file, infor:str):
        with open(log_file, "a") as f:
            f.write(infor) 
            f.write("\n")


    def hello_request(self):
        t1 = time.time()
        r = requests.get(self.url_hello)
        t2 = time.time()
        return (r.json(), (t2 - t1))


if __name__ == "__main__":
    # wav_folder = r'.\data\01 fev\Waves'
    wav_folder = r'D:\Github\FaurSound\data\01 fev\Waves'
    now = round(time.time(),2)
    log_file = f'./log/api_log_{now}.txt'
    all_sub_folders = [ os.path.join(wav_folder,name) for name in os.listdir(wav_folder) if os.path.isdir(os.path.join(wav_folder, name)) ]

    profiling_folder = r'./speed_profiling'
    if not os.path.isdir(profiling_folder):
        os.mkdir(profiling_folder)

    ri = requestInference()
    for folder in all_sub_folders:
        ri.process_one_wav_folder(wav_folder = folder, log_file_path = log_file)

