영상 데이터의 정보를 어떻게 하면 가져와 정보를 수집할 수 있을까 하는 생각이 있었습니다.
그러다 OpenAI의 Whisper를 접했고 쉽게 사용할 수 있는 방법이 있어 이를 기술하고자 합니다.
Whisper는 ChatGPT로 유명한 OpenAI의 자동 음성 인식(ASR) 시스템입니다.
음성 정보를 넣으면 언어를 인식하고, 다른 언어를 자동으로 영문으로 번역까지 해 올 수 있습니다.
YouTube 영상의 url을 넣었을 때 해당 영상을 다운 받고, Whisper를 통해 인식하여 텍스트로 가져오고, 한글로 번역하는 과정까지 작성해 보도록 하겠습니다.
먼저 사용할 python Package들을 다운받아 줍니다.
YouTube Download를 위해 pytube, ASR을 위해 whisper를 다운받아 줍니다.
# Youtube Download package
!pip install pytube
# OpenAI Whisper
!pip install git+https://github.com/openai/whisper.git
저는 BBC의 영상으로 진행하였습니다.
사용한 영상의 Url은 https://www.youtube.com/watch?v=lw7ZpMPleBg 입니다.
from pytube import YouTube
youtube_video = YouTube('https://www.youtube.com/watch?v={0}'.format(youtube_url))
youtube_video.streams.filter(file_extension='mp4').get_by_resolution('720p').download(output_path='.', filename='input.mp4')
Input.mp4로 영상을 다운 받았습니다.
Whisper에는 영상 정보가 아닌 음성 정보만 넣어주어야 하기 때문에 이를 mp3로 변환해 주어야 합니다.
ffmpeg를 사용하여 이를 mp3로 변환해 줍니다.
!ffmpeg -i input.mp4 -vn -ab 128k audio.mp3
mp4 파일을 mp3로 변환해 주었습니다.
Audio 모듈을 통해 변환된 음성 파일을 확인할 수 있습니다.
from IPython.display import Audio
Audio('audio.mp3')
다음으로 whipser를 통해 음성을 인식해 보겠습니다.
사용하는 Model에 따라 정확도/실행 속도에 영향을 미칩니다.
github에 표기되어 있는 정보이며 아래에서 model을 선정하면 됩니다.
Size | Parameters | English-only model |
Multilingual model |
Required VRAM |
Relative speed |
tiny | 39M | tiny.en | tiny | ~1 GB | ~32x |
base | 74M | base.en | base | ~1 GB | ~16x |
small | 244M | small.en | small | ~2 GB | ~6x |
medium | 769M | medium.en | medium | ~5 GB | ~2x |
large | 1550M | N/A | large | ~10 GB | 1x |
영상이 영문만 나와있을 경우 *.en model을 사용하면 됩니다.
저는 간단하게 사용하기 위해 base를 사용했습니다.
import whisper
model = whisper.load_model('base')
result = model.transcribe('audio.mp3')
# 영문으로 자동 변환을 하려면 task='translate' 추가
# model.transcribe('audio.mp3', task='translate')
result['text']
아래와 같이 결과가 잘 나왔습니다.
Now in Pakistan at least 59 people have died and more than 150 have been injured in an explosion at a mosque in the city of Peshawar. The attack is thought to have targeted members of the police force. No one has yet admitted responsibility. Our Pakistan correspondent Caroline Davis reports from the scene. A violent act that destroyed a place of prayer. The explosion ripped through the mosque in a police compound in Peshawar when it was filling up for lunchtime prayers. Hundreds were inside. Some survivors crawled from the rubble. Rescue workers used their bare hands to try to find others. Ambulances were still arriving at Peshawar's lady-reading hospital well into the evening. The families who had waited hoping for better news now distraught as instead their loved ones arrived lifeless. Inside the hospital waiting in a corridor we found Zahab Nawaz, his arm in a plaster cast and his back injured. He told us that he remembers a white flash and was blown five or six feet back by the force of the blast. Then the rubble fell on him. He spent more than an hour trapped beneath it. Still in his police uniform sitting with his wife, Javed Khan tells us that he had just walked into the mosque when the blast happened. He fell down with the force and has a severe head injury. It was a hectic situation. There were so many patients, so many attendants over here, so many injuries over here. It definitely makes me afraid. I am a human being. These are my brothers and sisters over here. I do care for them. My heart bleeps for them. These people here have some of the perhaps severe burns, others have got broken bones through falling rubble. While the number of people coming in still keeps rising, the death toll too has been going up. This evening funeral prayers for the dead. Pakistan has seen a growing number of violent attacks by groups who want Sharia law implemented in the country. Pakistan's army had claimed that they had broken the capabilities of these groups, but today's explosion and the damage it has caused will make many fearful that more attacks are to come. Caroline Davis BBC News, Basha'wa |
위의 예제는 단순하게 텍스트 정보만 가져 왔지만 어떤 언어를 사용하는지 여부도 확인할 수도 있습니다.
result['language']
Github에는 다른 방법을 통해 가져오는 방법도 기술되어 있습니다.
import whisper
model=whisper.load_model("base")
# load audio and pad/trim it to fit 30 seconds
audio=whisper.load_audio("audio.mp3")
audio=whisper.pad_or_trim(audio)
# make log-Mel spectrogram and move to the same device as the model
mel=whisper.log_mel_spectrogram(audio).to(model.device)
# detect the spoken language
_, probs=model.detect_language(mel)
print(f"Detected language: {max(probs, key=probs.get)}")
# decode the audiooptions=whisper.DecodingOptions()
result=whisper.decode(model, mel, options)
# print the recognized text
print(result.text)
각 문장의 데이터가 언제 말한 것인지, 시간도 같이 볼 수 있습니다.
결과 데이터는 초 단위로 나오기 때문에 이를 시:분:초 단위로 보기 위하여 datetime을 이용해 변환하는 함수를 만들어 주었습니다.
from datetime import timedelta
def sec_to_hour_min_sec(seconds):
dt = timedelta(seconds=seconds)
hours, remainder = divmod(dt.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return '{}:{:02d}:{:02d}'.format(hours, minutes, seconds)
for seg in result['segments']:
print('[{0} ~ {1}] {2}'.format(sec_to_hour_min_sec(seg['start']), sec_to_hour_min_sec(seg['end']), seg['text']))
[0:00:00 ~ 0:00:08] Now in Pakistan at least 59 people have died and more than 150 have been injured in an explosion at a mosque in the city of Peshawar. [0:00:08 ~ 0:00:14] The attack is thought to have targeted members of the police force. No one has yet admitted responsibility. [0:00:14 ~ 0:00:19] Our Pakistan correspondent Caroline Davis reports from the scene. [0:00:19 ~ 0:00:24] A violent act that destroyed a place of prayer. [0:00:24 ~ 0:00:30] The explosion ripped through the mosque in a police compound in Peshawar when it was filling up for lunchtime prayers. [0:00:30 ~ 0:00:36] Hundreds were inside. Some survivors crawled from the rubble. [0:00:38 ~ 0:00:42] Rescue workers used their bare hands to try to find others. [0:00:43 ~ 0:00:48] Ambulances were still arriving at Peshawar's lady-reading hospital well into the evening. [0:00:48 ~ 0:00:57] The families who had waited hoping for better news now distraught as instead their loved ones arrived lifeless. [0:00:57 ~ 0:01:05] Inside the hospital waiting in a corridor we found Zahab Nawaz, his arm in a plaster cast and his back injured. [0:01:05 ~ 0:01:12] He told us that he remembers a white flash and was blown five or six feet back by the force of the blast. [0:01:12 ~ 0:01:18] Then the rubble fell on him. He spent more than an hour trapped beneath it. [0:01:18 ~ 0:01:25] Still in his police uniform sitting with his wife, Javed Khan tells us that he had just walked into the mosque when the blast happened. [0:01:25 ~ 0:01:29] He fell down with the force and has a severe head injury. [0:01:29 ~ 0:01:35] It was a hectic situation. There were so many patients, so many attendants over here, so many injuries over here. [0:01:35 ~ 0:01:40] It definitely makes me afraid. I am a human being. These are my brothers and sisters over here. [0:01:40 ~ 0:01:43] I do care for them. My heart bleeps for them. [0:01:43 ~ 0:01:48] These people here have some of the perhaps severe burns, others have got broken bones through falling rubble. [0:01:48 ~ 0:01:53] While the number of people coming in still keeps rising, the death toll too has been going up. [0:01:55 ~ 0:01:57] This evening funeral prayers for the dead. [0:01:57 ~ 0:02:04] Pakistan has seen a growing number of violent attacks by groups who want Sharia law implemented in the country. [0:02:04 ~ 0:02:15] Pakistan's army had claimed that they had broken the capabilities of these groups, but today's explosion and the damage it has caused will make many fearful that more attacks are to come. [0:02:15 ~ 0:02:42] Caroline Davis BBC News, Basha'wa |
다른 언어를 영문으로는 자동 번역해 주지만 이를 한글로 변환해 주고 싶다면 별도의 패키지를 활용 해야 합니다.
저는 google 번역을 사용한 googletrans를 사용하였습니다.
해당 번역은 구글 번역을 사용하여 정확도가 높으나 API 개수 제한이 있습니다.
많은 번역이 필요하다면 다른 번역기 패키지로 변경해주세요.
!pip install --upgrade googletrans==3.1.0a0
from googletrans import Translator
translator = Translator()
# 전체 번역
# trans_text = translator.translate(result['text'], dest='ko').text
# print(trans_text)
# 한 줄씩 번역
for seg in result['segments']:
trans_text = translator.translate(seg['text'], dest='ko').text
print('[{0} ~ {1}] {2}'.format(sec_to_hour_min_sec(seg['start']), sec_to_hour_min_sec(seg['end']), trans_text))
[0:00:00 ~ 0:00:08] 현재 파키스탄에서는 페샤와르 시의 한 모스크에서 발생한 폭발로 최소 59명이 사망하고 150명 이상이 부상당했습니다. [0:00:08 ~ 0:00:14] 이번 공격은 경찰을 겨냥한 것으로 추정된다. 아직 아무도 책임을 인정하지 않았습니다. [0:00:14 ~ 0:00:19] 파키스탄 특파원 Caroline Davis가 현장에서 보도합니다. [0:00:19 ~ 0:00:24] 기도처를 파괴한 폭력 행위. [0:00:24 ~ 0:00:30] 폭발은 페샤와르의 경찰 건물에 있는 모스크가 점심 시간 기도를 위해 가득 차 있을 때 찢어졌습니다. [0:00:30 ~ 0:00:36] 수백 명이 안에 있었다. 일부 생존자들은 잔해에서 기어 나왔습니다. [0:00:38 ~ 0:00:42] 구조 대원들은 맨손으로 다른 사람을 찾으려고 했습니다. [0:00:43 ~ 0:00:48] 구급차는 페샤와르의 여성 독서 병원에 저녁 늦게까지 도착하고 있었습니다. [0:00:48 ~ 0:00:57] 더 나은 소식을 기다리던 가족들은 이제 사랑하는 사람들이 생명 없이 도착하면서 정신이 혼미해졌습니다. [0:00:57 ~ 0:01:05] 병원 내부 복도에서 기다리고 있는 Zahab Nawaz를 발견했습니다. 그의 팔은 석고 깁스를 하고 있고 등은 다쳤습니다. [0:01:05 ~ 0:01:12] 그는 흰색 섬광을 기억하고 폭발의 힘에 의해 5~6피트 뒤로 날아갔다고 말했습니다. [0:01:12 ~ 0:01:18] 그런 다음 잔해가 그에게 떨어졌습니다. 그는 그 아래에 갇혀 한 시간 이상을 보냈습니다. [0:01:18 ~ 0:01:25] 여전히 경찰복을 입고 아내와 함께 앉아 있는 Javed Khan은 폭발이 일어났을 때 모스크에 막 들어갔었다고 말했습니다. [0:01:25 ~ 0:01:29] 그는 힘으로 넘어져 심각한 머리 부상을 입었습니다. [0:01:29 ~ 0:01:35] 바쁜 상황이었습니다. 여기엔 환자가 너무 많았고 간병인도 많았고 부상자도 많았습니다. [0:01:35 ~ 0:01:40] 확실히 나를 두렵게 만든다. 나는 인간입니다. 여기 있는 내 형제자매들입니다. [0:01:40 ~ 0:01:43] 나는 그들을 돌본다. 그들을 위해 내 마음이 울립니다. [0:01:43 ~ 0:01:48] 여기 계신 분들 중 일부는 심각한 화상을 입었을 수도 있고, 다른 사람들은 떨어지는 잔해 때문에 뼈가 부러졌을 수도 있습니다. [0:01:48 ~ 0:01:53] 들어오는 사람의 수가 계속 증가하는 동안 사망자 수도 증가하고 있습니다. [0:01:55 ~ 0:01:57] 오늘 저녁 죽은 자를 위한 장례기도. [0:01:57 ~ 0:02:04] 파키스탄에서는 샤리아 법이 국내에 시행되기를 원하는 단체들의 폭력적인 공격이 증가하고 있습니다. [0:02:04 ~ 0:02:15] 파키스탄군은 이 그룹의 능력을 무너뜨렸다고 주장했지만 오늘의 폭발과 그로 인한 피해는 더 많은 공격이 올 것이라는 두려움을 불러일으킬 것입니다. [0:02:15 ~ 0:02:42] 캐롤라인 데이비스 BBC 뉴스, 바샤와 |
Whisper의 자세한 내용은 아래 github를 확인하실 수 있습니다.
GitHub - openai/whisper: Robust Speech Recognition via Large-Scale Weak Supervision
Robust Speech Recognition via Large-Scale Weak Supervision - GitHub - openai/whisper: Robust Speech Recognition via Large-Scale Weak Supervision
github.com