{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ffbd75a0-2134-4342-a898-94df2529dfaa",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import pathlib\n",
    "from pathlib import Path\n",
    "from glob import glob\n",
    "import csv\n",
    "import IPython\n",
    "\n",
    "import librosa\n",
    "import pandas as pd\n",
    "import torchaudio\n",
    "\n",
    "dubbingPath = \"HLKv21/애드온/한국어 더빙/\"\n",
    "dubbingDetailTxt = \"HLKv21/애드온/한국어 더빙/sentences.txt\"\n",
    "subtitleDetailTxt = \"HLKv21/valve/captionmod/dictionary_koreana.txt\"\n",
    "dubSubDictionaryPath = \"HLKv21/valve/captionmod/dictionary.csv\"\n",
    "\n",
    "save_dir = \"resample\"\n",
    "working_dir = \"halfLife\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4bbbef67-7826-462a-a6cd-1ef98a909fdc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[0K\n",
      "ERROR: Download failed for 'https://mega.nz/#!QthmmB6L!Nr5zK9iMTtLlVLvFP5w-tLwJIQzpS-eezGMY0Y7AGDc': Can't open local file /home/user/code/jupyter/tts/HLKv21.zip for writing: Error opening file “/home/user/code/jupyter/tts/HLKv21.zip”: File exists\n",
      "Archive:  HLKv21.zip\n",
      "replace HLKv21/metahook.exe? [y]es, [n]o, [A]ll, [N]one, [r]ename: ^C\n",
      "unzip:  cannot find or open HLKv21/애드온/한국어 더빙.zip, HLKv21/애드온/한국어 더빙.zip.zip or HLKv21/애드온/한국어 더빙.zip.ZIP.\n"
     ]
    }
   ],
   "source": [
    "# download half life data\n",
    "# https://bbs.ruliweb.com/news/board/1003/read/1962882\n",
    "!sudo apt-get install megatools\n",
    "!megadl 'https://mega.nz/#!QthmmB6L!Nr5zK9iMTtLlVLvFP5w-tLwJIQzpS-eezGMY0Y7AGDc'\n",
    "!unzip -O cp949 \"HLKv21.zip\" -d \"HLKv21/\"\n",
    "!unzip -O cp949 \"HLKv21/애드온/한국어 더빙.zip\" -d \"HLKv212/애드온/한국어 더빙\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1b76f8aa-33fa-4586-be7f-d409fbfdb296",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "986\n"
     ]
    }
   ],
   "source": [
    "# read subtitle\n",
    "with open(subtitleDetailTxt, encoding=\"utf-16\") as f:\n",
    "    lines = f.readlines()\n",
    "\n",
    "lines = [line for line in lines if line.count('\"') == 4]  # line include four '\"'\n",
    "subtitleDict = dict()\n",
    "for line in lines:\n",
    "    item = line.split('\"')\n",
    "    itemId = item[1].strip().lower()\n",
    "\n",
    "    sub = item[3]\n",
    "    sub = sub.replace(\"\\\\n\", \" \")\n",
    "    sub = sub.replace(\"…\", \".\")\n",
    "    sub = \" \".join(sub.split())  # remove duplicate space\n",
    "    sub = sub.strip()\n",
    "    if sub == \"\":\n",
    "        continue  # skip empty\n",
    "\n",
    "    subtitleDict[itemId] = sub\n",
    "\n",
    "len(subtitleDict)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "850ca26c-4889-4a6f-aab6-931aa5592c29",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# read dub\n",
    "dubPathDict = dict()\n",
    "\n",
    "# make dict using dubbing sentences.txt\n",
    "with open(dubbingDetailTxt) as f:\n",
    "    lines = f.readlines()\n",
    "    lines = [line for line in lines if line.count(\"/\") == 1]\n",
    "\n",
    "    for line in lines:\n",
    "        line = line.strip().lower()\n",
    "        item = line.split(\" \", 1)\n",
    "        itemID = item[0]\n",
    "        path = item[1] + \".wav\"\n",
    "        if os.path.exists(dubbingPath + path):\n",
    "            dubPathDict[itemID] = dubbingPath + path\n",
    "\n",
    "\n",
    "# make dict using file name\n",
    "dubPathList = glob(dubbingPath + \"**/*.wav\", recursive=True)\n",
    "for item in dubPathList:\n",
    "    dubPathDict[pathlib.Path(item).stem] = item  # only file name\n",
    "for item in dubPathList:\n",
    "    dubPathDict[item.replace(dubbingPath, \"\")] = item  # without basepath"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b5e4e539-cefd-4850-8780-4991c5ba5644",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/user/anaconda3/envs/tts/lib/python3.7/site-packages/ipykernel_launcher.py:15: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.\n",
      "  from ipykernel import kernelapp as app\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>dubID</th>\n",
       "      <th>subID</th>\n",
       "      <th>subText</th>\n",
       "      <th>dubPath</th>\n",
       "      <th>dubPathShort</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>holo/tr_holo_intro.wav</td>\n",
       "      <td>halflife_holo_intro</td>\n",
       "      <td>안녕하십니까, 블랙 메사 재난 예방 훈련에 오신 것을 환영합니다. 이 곳에서 보호복...</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/holo/tr_holo_intro.wav</td>\n",
       "      <td>holo/tr_holo_intro.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>holo/tr_holo_button.wav</td>\n",
       "      <td>halflife_holo_button</td>\n",
       "      <td>이런 버튼이 나타나면 눌러보십시오, 그럼 제가 나와서 동작 시범을 보이겠습니다.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/holo/tr_holo_button.wav</td>\n",
       "      <td>holo/tr_holo_button.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>holo/tr_holo_move.wav</td>\n",
       "      <td>halflife_holo_move</td>\n",
       "      <td>HEV 보호복을 입고 이동하면, 처음에는 약간 방향감각을 잃을 수도 있습니다. 잠시...</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/holo/tr_holo_move.wav</td>\n",
       "      <td>holo/tr_holo_move.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>tride/c0a0_tr_gmorn.wav</td>\n",
       "      <td>halflife_c0a0_tr_goodmorn</td>\n",
       "      <td>안녕하십니까, 블랙 메사 운송 시스템을 사용해 주셔서 감사합니다. 이 자동 기차는 ...</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/tride/c0a0_tr_gmorn.wav</td>\n",
       "      <td>tride/c0a0_tr_gmorn.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>tride/c0a0_tr_time.wav</td>\n",
       "      <td>halflife_c0a0_tr_time</td>\n",
       "      <td>현재 시간은 오전 8시 47분입니다. 현재 상층 온도는 섭씨 34도입니다. 예상 최...</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/tride/c0a0_tr_time.wav</td>\n",
       "      <td>tride/c0a0_tr_time.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>966</th>\n",
       "      <td>tr_b</td>\n",
       "      <td>tr_b</td>\n",
       "      <td>타겟 시스템 작동 중지됨.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/sentences/tr_b.wav</td>\n",
       "      <td>sentences/tr_b.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>967</th>\n",
       "      <td>we0</td>\n",
       "      <td>we0</td>\n",
       "      <td>경고. 고압 케이블.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/sentences/we0.wav</td>\n",
       "      <td>sentences/we0.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>968</th>\n",
       "      <td>we1</td>\n",
       "      <td>we1</td>\n",
       "      <td>경고. 고압 전원 케이블.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/sentences/we1.wav</td>\n",
       "      <td>sentences/we1.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>969</th>\n",
       "      <td>we2</td>\n",
       "      <td>we2</td>\n",
       "      <td>경고. 감전 위험.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/sentences/we2.wav</td>\n",
       "      <td>sentences/we2.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>970</th>\n",
       "      <td>we3</td>\n",
       "      <td>we3</td>\n",
       "      <td>경고. 고압 감전 위험.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/sentences/we3.wav</td>\n",
       "      <td>sentences/we3.wav</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>884 rows × 5 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                       dubID                      subID  \\\n",
       "2     holo/tr_holo_intro.wav        halflife_holo_intro   \n",
       "3    holo/tr_holo_button.wav       halflife_holo_button   \n",
       "4      holo/tr_holo_move.wav         halflife_holo_move   \n",
       "11   tride/c0a0_tr_gmorn.wav  halflife_c0a0_tr_goodmorn   \n",
       "12    tride/c0a0_tr_time.wav      halflife_c0a0_tr_time   \n",
       "..                       ...                        ...   \n",
       "966                     tr_b                       tr_b   \n",
       "967                      we0                        we0   \n",
       "968                      we1                        we1   \n",
       "969                      we2                        we2   \n",
       "970                      we3                        we3   \n",
       "\n",
       "                                               subText  \\\n",
       "2    안녕하십니까, 블랙 메사 재난 예방 훈련에 오신 것을 환영합니다. 이 곳에서 보호복...   \n",
       "3         이런 버튼이 나타나면 눌러보십시오, 그럼 제가 나와서 동작 시범을 보이겠습니다.   \n",
       "4    HEV 보호복을 입고 이동하면, 처음에는 약간 방향감각을 잃을 수도 있습니다. 잠시...   \n",
       "11   안녕하십니까, 블랙 메사 운송 시스템을 사용해 주셔서 감사합니다. 이 자동 기차는 ...   \n",
       "12   현재 시간은 오전 8시 47분입니다. 현재 상층 온도는 섭씨 34도입니다. 예상 최...   \n",
       "..                                                 ...   \n",
       "966                                     타겟 시스템 작동 중지됨.   \n",
       "967                                        경고. 고압 케이블.   \n",
       "968                                     경고. 고압 전원 케이블.   \n",
       "969                                         경고. 감전 위험.   \n",
       "970                                      경고. 고압 감전 위험.   \n",
       "\n",
       "                                       dubPath             dubPathShort  \n",
       "2     HLKv21/애드온/한국어 더빙/holo/tr_holo_intro.wav   holo/tr_holo_intro.wav  \n",
       "3    HLKv21/애드온/한국어 더빙/holo/tr_holo_button.wav  holo/tr_holo_button.wav  \n",
       "4      HLKv21/애드온/한국어 더빙/holo/tr_holo_move.wav    holo/tr_holo_move.wav  \n",
       "11   HLKv21/애드온/한국어 더빙/tride/c0a0_tr_gmorn.wav  tride/c0a0_tr_gmorn.wav  \n",
       "12    HLKv21/애드온/한국어 더빙/tride/c0a0_tr_time.wav   tride/c0a0_tr_time.wav  \n",
       "..                                         ...                      ...  \n",
       "966       HLKv21/애드온/한국어 더빙/sentences/tr_b.wav       sentences/tr_b.wav  \n",
       "967        HLKv21/애드온/한국어 더빙/sentences/we0.wav        sentences/we0.wav  \n",
       "968        HLKv21/애드온/한국어 더빙/sentences/we1.wav        sentences/we1.wav  \n",
       "969        HLKv21/애드온/한국어 더빙/sentences/we2.wav        sentences/we2.wav  \n",
       "970        HLKv21/애드온/한국어 더빙/sentences/we3.wav        sentences/we3.wav  \n",
       "\n",
       "[884 rows x 5 columns]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# read dictionary\n",
    "df = pd.read_csv(\n",
    "    dubSubDictionaryPath,\n",
    "    encoding=\"unicode_escape\",\n",
    "    usecols=[0, 1],\n",
    "    names=[\"dubID\", \"subID\"],\n",
    ")\n",
    "df = df.dropna()  # drop nan\n",
    "df = df.applymap(str.lower)  # all lowercase\n",
    "df = df[df[\"subID\"].str.contains(\"#\")]  # filter only include #\n",
    "df[\"subID\"] = df[\"subID\"].str.replace(\"#\", \"\")  # remove #\n",
    "\n",
    "# add subText\n",
    "df[\"subText\"] = df[\"subID\"].map(subtitleDict)\n",
    "df = df.dropna()  # drop nan\n",
    "\n",
    "# add dubPath\n",
    "df[\"dubID\"] = df[\"dubID\"].str.replace(\"*\", \"\")  # remove #\n",
    "df[\"dubPath\"] = df[\"dubID\"].map(dubPathDict)\n",
    "df[\"dubPathShort\"] = df[\"dubPath\"].str.replace(dubbingPath, \"\")  # remove #\n",
    "\n",
    "df = df.dropna()  # drop nan\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9c943df3-d5a3-4252-a0bb-ca96d5af2353",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>dubID</th>\n",
       "      <th>subID</th>\n",
       "      <th>subText</th>\n",
       "      <th>dubPath</th>\n",
       "      <th>dubPathShort</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>186</th>\n",
       "      <td>scientist/c1a0_sci_bigday.wav</td>\n",
       "      <td>c1a0_sci_bigday</td>\n",
       "      <td>오늘은 중요한 날이야, 프리맨.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/scientist/c1a0_sci_bigday.wav</td>\n",
       "      <td>scientist/c1a0_sci_bigday.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>187</th>\n",
       "      <td>scientist/c1a0_sci_getaway.wav</td>\n",
       "      <td>c1a0_sci_getaway</td>\n",
       "      <td>저리 비켜주게 프리맨. 곧 중요한 메시지가 올 거야.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/scientist/c1a0_sci_getaway.wav</td>\n",
       "      <td>scientist/c1a0_sci_getaway.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>188</th>\n",
       "      <td>scientist/c1a0_sci_gm.wav</td>\n",
       "      <td>c1a0_sci_gm</td>\n",
       "      <td>안녕, 고든.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/scientist/c1a0_sci_gm.wav</td>\n",
       "      <td>scientist/c1a0_sci_gm.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>189</th>\n",
       "      <td>scientist/c1a0_sci_gm1.wav</td>\n",
       "      <td>c1a0_sci_gm1</td>\n",
       "      <td>안녕, 고든.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/scientist/c1a0_sci_gm1.wav</td>\n",
       "      <td>scientist/c1a0_sci_gm1.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>190</th>\n",
       "      <td>scientist/c1a0_sci_itsyou.wav</td>\n",
       "      <td>c1a0_sci_itsyou</td>\n",
       "      <td>아! 자네군. 난 또 행정부서 직원인 줄 알았지. 오늘 아침에는 온통 행정 직원들만...</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/scientist/c1a0_sci_itsyou.wav</td>\n",
       "      <td>scientist/c1a0_sci_itsyou.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>704</th>\n",
       "      <td>sc_scared0</td>\n",
       "      <td>sc_scared0</td>\n",
       "      <td>아니, 뭐 하는 겁니까?</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/scientist/whatyoudoing.wav</td>\n",
       "      <td>scientist/whatyoudoing.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>705</th>\n",
       "      <td>sc_scared1</td>\n",
       "      <td>sc_scared1</td>\n",
       "      <td>그만둬! 그자는 동료야!</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/scientist/stopattacking.wav</td>\n",
       "      <td>scientist/stopattacking.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>706</th>\n",
       "      <td>sc_scared2</td>\n",
       "      <td>sc_scared2</td>\n",
       "      <td>자네 미쳤나? 그만 쏘라고!</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/scientist/youinsane.wav</td>\n",
       "      <td>scientist/youinsane.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>707</th>\n",
       "      <td>sc_letyouin</td>\n",
       "      <td>sc_letyouin</td>\n",
       "      <td>조금만 기다리면 당신을 안으로 들어오게 하겠소.</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/scientist/letyouin.wav</td>\n",
       "      <td>scientist/letyouin.wav</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>708</th>\n",
       "      <td>sc_overhere</td>\n",
       "      <td>sc_overhere</td>\n",
       "      <td>잠깐! 여기야!</td>\n",
       "      <td>HLKv21/애드온/한국어 더빙/scientist/overhere.wav</td>\n",
       "      <td>scientist/overhere.wav</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>271 rows × 5 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "                              dubID             subID  \\\n",
       "186   scientist/c1a0_sci_bigday.wav   c1a0_sci_bigday   \n",
       "187  scientist/c1a0_sci_getaway.wav  c1a0_sci_getaway   \n",
       "188       scientist/c1a0_sci_gm.wav       c1a0_sci_gm   \n",
       "189      scientist/c1a0_sci_gm1.wav      c1a0_sci_gm1   \n",
       "190   scientist/c1a0_sci_itsyou.wav   c1a0_sci_itsyou   \n",
       "..                              ...               ...   \n",
       "704                      sc_scared0        sc_scared0   \n",
       "705                      sc_scared1        sc_scared1   \n",
       "706                      sc_scared2        sc_scared2   \n",
       "707                     sc_letyouin       sc_letyouin   \n",
       "708                     sc_overhere       sc_overhere   \n",
       "\n",
       "                                               subText  \\\n",
       "186                                  오늘은 중요한 날이야, 프리맨.   \n",
       "187                      저리 비켜주게 프리맨. 곧 중요한 메시지가 올 거야.   \n",
       "188                                            안녕, 고든.   \n",
       "189                                            안녕, 고든.   \n",
       "190  아! 자네군. 난 또 행정부서 직원인 줄 알았지. 오늘 아침에는 온통 행정 직원들만...   \n",
       "..                                                 ...   \n",
       "704                                      아니, 뭐 하는 겁니까?   \n",
       "705                                      그만둬! 그자는 동료야!   \n",
       "706                                    자네 미쳤나? 그만 쏘라고!   \n",
       "707                         조금만 기다리면 당신을 안으로 들어오게 하겠소.   \n",
       "708                                           잠깐! 여기야!   \n",
       "\n",
       "                                              dubPath  \\\n",
       "186   HLKv21/애드온/한국어 더빙/scientist/c1a0_sci_bigday.wav   \n",
       "187  HLKv21/애드온/한국어 더빙/scientist/c1a0_sci_getaway.wav   \n",
       "188       HLKv21/애드온/한국어 더빙/scientist/c1a0_sci_gm.wav   \n",
       "189      HLKv21/애드온/한국어 더빙/scientist/c1a0_sci_gm1.wav   \n",
       "190   HLKv21/애드온/한국어 더빙/scientist/c1a0_sci_itsyou.wav   \n",
       "..                                                ...   \n",
       "704      HLKv21/애드온/한국어 더빙/scientist/whatyoudoing.wav   \n",
       "705     HLKv21/애드온/한국어 더빙/scientist/stopattacking.wav   \n",
       "706         HLKv21/애드온/한국어 더빙/scientist/youinsane.wav   \n",
       "707          HLKv21/애드온/한국어 더빙/scientist/letyouin.wav   \n",
       "708          HLKv21/애드온/한국어 더빙/scientist/overhere.wav   \n",
       "\n",
       "                       dubPathShort  \n",
       "186   scientist/c1a0_sci_bigday.wav  \n",
       "187  scientist/c1a0_sci_getaway.wav  \n",
       "188       scientist/c1a0_sci_gm.wav  \n",
       "189      scientist/c1a0_sci_gm1.wav  \n",
       "190   scientist/c1a0_sci_itsyou.wav  \n",
       "..                              ...  \n",
       "704      scientist/whatyoudoing.wav  \n",
       "705     scientist/stopattacking.wav  \n",
       "706         scientist/youinsane.wav  \n",
       "707          scientist/letyouin.wav  \n",
       "708          scientist/overhere.wav  \n",
       "\n",
       "[271 rows x 5 columns]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# filter, only scientist speaker voice\n",
    "df = df[df[\"dubPath\"].str.contains(\"scientist\")]\n",
    "\n",
    "# remove too long wav because of out of memory\n",
    "df = df[df.apply(lambda x: librosa.get_duration(filename=x[\"dubPath\"]) < 15, axis=1)]\n",
    "\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c83dafd7-6898-4c2e-9d64-6d9b726a93fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "# resample\n",
    "#save resample audio\n",
    "target_rate = 22050\n",
    "for index, row in df.iterrows():\n",
    "    savePath = os.path.join(\n",
    "        save_dir, working_dir, \"wavs\", Path(row[\"dubPath\"]).stem + \".wav\"\n",
    "    )\n",
    "    speech_array, sample_rate = torchaudio.load(row[\"dubPath\"])\n",
    "    speech_array = torchaudio.functional.resample(\n",
    "        speech_array, sample_rate, target_rate\n",
    "    )\n",
    "    os.makedirs(os.path.dirname(savePath), exist_ok=True)\n",
    "    torchaudio.save(savePath, speech_array, target_rate)\n",
    "\n",
    "#save csv\n",
    "os.makedirs(os.path.dirname(savePath), exist_ok=True)\n",
    "with open(\n",
    "    os.path.join(save_dir, working_dir, \"metadata.csv\"), \"w\", encoding=\"utf-8\"\n",
    ") as file:\n",
    "    wr = csv.writer(file, delimiter=\"|\")\n",
    "    for index, row in df.iterrows():\n",
    "        lineSplit = line.split(\" \", 1)\n",
    "        file_name = os.path.join(\"wavs\", Path(row[\"dubPath\"]).stem + \".wav\")\n",
    "        text = row[\"subText\"].strip()\n",
    "        speaker_name = \"halfLife\"\n",
    "        wr.writerow([file_name, text, text, speaker_name])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "f06037eb-5f98-4c97-ad90-82f758c9bdee",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio  controls=\"controls\" >\n",
       "                    <source src=\"data:audio/x-wav;base64,[encoded data, 194160 characters]\" type=\"audio/x-wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IPython.display.Audio(\"half_life/kss/scientist/c1a0_sci_bigday.wav\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1fc57c29-13bf-4523-b6e7-243df81b33a1",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:tts]",
   "language": "python",
   "name": "conda-env-tts-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
