Introduction
Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.
I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.
I also build and publish a variety of tools, libraries, and open-source projects.
This article walks through building an app that uses the OpenAI API to summarize content from links to services such as Voicy and YouTube.
You can try the app I built at the following URL. Select Audio Summary from the sidebar.
Usage instructions and source code are available on GitHub.
Although the application is functional, I recommend deleting the OpenAI API key you generated after using it as a security precaution.
We will use Streamlit, a Python framework, to build and deploy an application that others can access.
Download audio from a URL

Start by retrieving audio files from Voicy and YouTube links.
In Python, we can use the yt_dlp module for this.
We will use Poetry to manage our virtual environment.
Poetry is a Python package manager that I use regularly because it is convenient.
If you have not used Poetry before, the following article can help you get started.
If you already use another package manager, feel free to stick with it.
Create a directory and initialize the virtual environment using the following commands.
$ mkdir audio
$ cd audio
$ poetry initYou can press Enter to accept the default answers to the prompts.
Run the following commands to activate the virtual environment and install yt_dlp.
$ poetry shell
$ poetry add yt_dlpYou can now use yt_dlp.
Create a file in the directory you just set up.
$ touch download_audio.pyOpen the file and paste in the following code.
from yt_dlp import YoutubeDL
def get_audio_file(url: str):
ydl_opts = {
'outtmpl': './audio.%(ext)s',
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'
}],
}
ydl = YoutubeDL(ydl_opts)
ydl.download([url])
def main():
get_audio_file("https://voicy.jp/channel/2627/559190")
if __name__ == '__main__':
main()Here is how each part works.
from yt_dlp import YoutubeDLThis imports the yt_dlp module we installed earlier.
def get_audio_file(url: str):
ydl_opts = {
'outtmpl': './audio.%(ext)s',
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'
}],
}
ydl = YoutubeDL(ydl_opts)
ydl.download([url])This is the main part of the implementation.
The function takes a URL as an argument and retrieves its audio.
The ydl_opts dictionary defines the options used to download the audio file.
The main options are as follows.
Key options
outtmpl- The output file path.
format- The download quality.
preferredcodec- The file extension.
The function then downloads the audio from the specified URL.
For this example, we retrieve a broadcast by Voicy host Satoshi Nakajima.
Run the script.
If the command prints output and creates a file named audio.mp3, the download succeeded.
$ python download_audio.py
[voicy] Extracting URL: https://voicy.jp/channel/2627/559190
[voicy] 559190: Downloading JSON metadata
[download] Downloading multi_video: SlashGPTをオープンソース化しました
[voicy] Playlist SlashGPTをオープンソース化しました: Downloading 2 items of 2
[download] Downloading item 1 of 2
[info] 1934043: Downloading 1 format(s): hls
[hlsnative] Downloading m3u8 manifest
[hlsnative] Total fragments: 2
[download] Destination: ./audio.m4a
[download] 100% of 103.18KiB in 00:00:00 at 1.08MiB/s
[FixupM3u8] Fixing MPEG-TS in MP4 container of "./audio.m4a"
[ExtractAudio] Destination: ./audio.mp3
Deleting original file ./audio.m4a (pass -k to keep)
[download] Downloading item 2 of 2
[info] 1314556: Downloading 1 format(s): hls
[hlsnative] Downloading m3u8 manifest
[hlsnative] Total fragments: 45
[download] Destination: ./audio.m4a
[download] 100% of 3.92MiB in 00:00:02 at 1.67MiB/s
[FixupM3u8] Fixing MPEG-TS in MP4 container of "./audio.m4a"
[ExtractAudio] Destination: ./audio.mp3
Deleting original file ./audio.m4a (pass -k to keep)
[download] Finished downloading playlist: SlashGPTをオープンソース化しましたWe can now retrieve an audio file from a URL.
Transcribe audio

The next step is to convert the downloaded audio into text.
We will use Whisper, OpenAI's speech recognition model, which supports tasks such as transcription.
The implementations in this section and the following section on summarization are based on this article.
First, define the environment variables.
Run the following command to create a .env file.
$ touch .envOpen the file and paste in the following content.
OPENAI_API_KEY="<Open AI API Key>"Replace <Open AI API Key> with your OpenAI API key.
Install the following modules.
$ poetry add openai
$ poetry add python-dotenvThese modules provide access to the OpenAI API and environment variables.
Run the following command to create a file.
$ touch audio_to_text.pyPaste the following code into the file.
import os
import openai
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
def get_audio_text(file_path: str) -> str:
audio_file = open(file_path, "rb")
transcript = openai.Audio.transcribe("whisper-1", audio_file)
return transcript["text"]
def main():
file_path = "./audio.mp3"
audio_text = get_audio_text(file_path)
print(audio_text)
if __name__ == "__main__":
main()We can break this implementation down as well.
import os
import openai
from dotenv import load_dotenvThese lines import the modules installed earlier and other dependencies.
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')This loads the environment variables defined in the .env file and passes the API key to the openai module.
The module can then use your OpenAI API key.
def get_audio_text(file_path: str) -> str:
audio_file = open(file_path, "rb")
transcript = openai.Audio.transcribe("whisper-1", audio_file)
return transcript["text"]This is the main transcription logic.
It reads the file at the file_path supplied as an argument.
It then uses Whisper to convert the audio file to text.
Finally, it returns the transcribed text to the caller.
def main():
file_path = "./audio.mp3"
audio_text = get_audio_text(file_path)
print(audio_text)This calls the get_audio_text function described above.
The audio file downloaded in the previous section was saved as audio.mp3, so we pass that file path to get_audio_text.
The script then prints the transcription to standard output.
Run the script.
$ python audio_to_text.py
こんにちは中島です 日本に出張したりしててちょっと...If text appears in the output as shown above, transcription succeeded.
Summarize the text

Now we can summarize the transcription.
This section also draws on the article referenced in the previous section.
Install the required modules.
$ poetry add llama-indexCreate a file.
$ touch summary_text.pyPaste the following code into it.
import os
import openai
from llama_index import StorageContext, StringIterableReader, GPTVectorStoreIndex, load_index_from_storage
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
STORAGE_PATH = "./storage"
def get_summary_text(audio_text: str, summary_prompt: str) -> str:
if not os.path.exists(STORAGE_PATH):
os.makedirs(STORAGE_PATH)
try:
storage_context = StorageContext.from_defaults(persist_dir=STORAGE_PATH)
vector_index = load_index_from_storage(storage_context)
except Exception:
documents = StringIterableReader().load_data(texts=[audio_text])
vector_index = GPTVectorStoreIndex.from_documents(documents)
vector_index.storage_context.persist(persist_dir=STORAGE_PATH)
query_engine = vector_index.as_query_engine()
response = query_engine.query(summary_prompt)
return response.response
def main():
text = """
こんにちは中島です 日本に出張したりしててちょっと...
"""
prompt = "テキストの内容を5~10の項目に分けて要約してください。"
summary_text = get_summary_text(text, prompt)
print(f"summary_text: {summary_text}")
if __name__ == "__main__":
main()Here is how each part works.
import os
import openai
from llama_index import StorageContext, StringIterableReader, GPTVectorStoreIndex, load_index_from_storage
from dotenv import load_dotenvThese lines import the modules installed earlier and other dependencies.
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
STORAGE_PATH = "./storage"As before, this sets the OpenAI API key.
STORAGE_PATH is the directory where files generated during text vectorization are stored.
def get_summary_text(audio_text: str, summary_prompt: str) -> str:
if not os.path.exists(STORAGE_PATH):
os.makedirs(STORAGE_PATH)
try:
storage_context = StorageContext.from_defaults(persist_dir=STORAGE_PATH)
vector_index = load_index_from_storage(storage_context)
except Exception:
documents = StringIterableReader().load_data(texts=[audio_text])
vector_index = GPTVectorStoreIndex.from_documents(documents)
vector_index.storage_context.persist(persist_dir=STORAGE_PATH)
query_engine = vector_index.as_query_engine()
response = query_engine.query(summary_prompt)
return response.responseThis is the main summarization logic.
The function accepts audio_text, the transcribed audio, and summary_prompt, the prompt used to generate the summary.
First, it checks whether the directory at STORAGE_PATH exists and creates it if necessary.
If the directory contains files with vector information, the function uses those files. If they are missing or an error occurs, it converts the supplied text into vectors.
Once vectorization is complete, the function summarizes the text using the supplied prompt and the vector information.
It then returns the summary to the caller.
def main():
text = """
こんにちは中島です 日本に出張したりしててちょっと...
"""
prompt = "テキストの内容を5~10の項目に分けて要約してください。"
summary_text = get_summary_text(text, prompt)
print(f"summary_text: {summary_text}")This calls the get_summary_text function described above.
Store the transcription from the previous section in the text variable.
Run the script.
$ python summary_text.py
1. 自然言語のインターフェースを使うことで、複雑なシステムでも文脈を理解してメニューを探さなくてもやってくれるシステムができる。
2. ユーザーインターフェースの進化の意味で、一気に進んだという感じである。
...If the output is organized into individual points as shown above, summarization succeeded.
We have now checked the entire processing pipeline.
Build the app with Streamlit

We can now use Streamlit to turn these operations into an application.
Install the module.
$ poetry add streamlitCreate the files.
$ touch lib.py
$ touch app.pyPaste the following code into the corresponding files.
from yt_dlp import YoutubeDL
import openai
import os
from llama_index import StorageContext, StringIterableReader, GPTVectorStoreIndex, load_index_from_storage
STORAGE_PATH = "./storage"
def get_audio_file(url: str):
ydl_opts = {
'outtmpl': './audio.%(ext)s',
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'
}],
}
ydl = YoutubeDL(ydl_opts)
ydl.download([url])
def get_audio_text(file_path: str) -> str:
audio_file = open(file_path, "rb")
transcript = openai.Audio.transcribe("whisper-1", audio_file)
return transcript["text"]
def get_summary_text(audio_text: str, summary_prompt: str) -> str:
if not os.path.exists(STORAGE_PATH):
os.makedirs(STORAGE_PATH)
try:
storage_context = StorageContext.from_defaults(persist_dir=STORAGE_PATH)
vector_index = load_index_from_storage(storage_context)
except Exception:
documents = StringIterableReader().load_data(texts=[audio_text])
vector_index = GPTVectorStoreIndex.from_documents(documents)
vector_index.storage_context.persist(persist_dir=STORAGE_PATH)
query_engine = vector_index.as_query_engine()
response = query_engine.query(summary_prompt)
return response.responseimport streamlit as st
import openai
import webbrowser
import os
import shutil
import lib
AUDIO_FILE_PATH = "./audio.mp3"
STORAGE_PATH = "./storage"
def main():
summary_prompt = ''
audio_text = ''
api_flag = False
st.title('Audio Summary')
if st.button("Reset", key="reset"):
if os.path.exists(STORAGE_PATH):
shutil.rmtree(STORAGE_PATH)
if os.path.exists(AUDIO_FILE_PATH):
os.remove(AUDIO_FILE_PATH)
open_ai_api_key: str = st.text_input(label="Open AI API Key (required)", type="password")
if st.button("Register Open AI API Key", key="api_key") and open_ai_api_key:
st.success("Open AI API Key is set.", icon="✅")
if (api_flag is False):
os.environ['OPENAI_API_KEY'] = open_ai_api_key
openai.api_key = open_ai_api_key
api_flag = True
audio_url: str = st.text_input(label="Audio URL (required)")
if audio_url:
st.success("Audio URL is set.", icon="✅")
if st.button("Get Audio File", key="get_audio_file"):
with st.spinner(text="Get Audio Data..."):
lib.get_audio_file(audio_url)
summary_prompt = st.selectbox(
label="Choice Prompt (required)",
options=[
"テキストの内容を300文字程度で要約してください。",
"テキストの内容を5~10の項目に分けて要約してください",
"テキストの内容を500文字程度にまとめてください。",
"テキストの内容を1000文字程度にまとめてください。",
]
)
if audio_url and os.path.exists(AUDIO_FILE_PATH):
st.success("Get Audio Data.", icon="✅")
audio_file = open(AUDIO_FILE_PATH, 'rb')
audio_bytes = audio_file.read()
st.audio(audio_bytes, format='audio/mp3')
st.download_button(label="Download Audio File", data=audio_bytes, file_name="audio.mp3", mime="audio/mp3")
col1, col2 = st.columns(2)
with col1:
st.write("Summary Text Using OpenAI")
summary_btn = st.button("Get Summary Text", key="get_summary_text")
with col2:
st.write("Open ChatGPT")
check_open_chatgpt_btn = st.button("Open ChatGPT Button", key="check_open_chatgpt")
if summary_btn:
with st.spinner(text="Convert Audio Text..."):
audio_text = lib.get_audio_text(AUDIO_FILE_PATH)
if audio_text:
st.success("Convert Audio Text.", icon="✅")
with st.expander("Audio Text"):
st.write(audio_text)
with st.spinner(text="Get Summary Text..."):
summary_text = lib.get_summary_text(audio_text, summary_prompt)
if summary_text:
st.success("Get Summary Text.", icon="✅")
st.write(summary_text)
if check_open_chatgpt_btn:
with st.spinner(text="Convert Audio Text..."):
audio_text = lib.get_audio_text(AUDIO_FILE_PATH)
if audio_text:
st.success("Convert Audio Text.", icon="✅")
st.info("以下のコードをコピーして、以下のボタンを押したのち、開いたChatGPTページ内の入力欄に貼り付けてください。")
st.write(f"{summary_prompt}\n{audio_text}")
if st.button("Open ChatGPT", key="open_chatgpt"):
search_url = 'https://chat.openai.com/'
with st.spinner(text="Open ChatGPT..."):
webbrowser.open(search_url)
if __name__ == "__main__":
main()The implementation is quite long, so I will skip a line-by-line explanation here.
For more details, refer to the Streamlit documentation.
Run the following command.
$ streamlit run app.p
You can now view your Streamlit app in your browser.
Local URL: http://localhost:8501
Network URL: http://192.168.1.2:8501Your browser should open automatically. If it does not, visit the URL printed in the output.

If you see a page like the one above, the application is running.
The following GitHub repository contains a video demonstrating how to use it.
https://github.com/cardene777/ai_app/tree/main/audio_summary
You have now launched the application with Streamlit.
Deploy with Streamlit

Finally, deploy the application you just built.
We will use Streamlit Share, which simplifies deployment.
Start by preparing the required files.
$ touch packages.txtAdd the following content to the file you created.
ffmpegUpload the files you have created to GitHub.
The following article provides an example of how to do this.
A private repository may not work for this deployment, so the original setup recommends using a public repository.
Visit the following URL.

You should see a page like the one above. Sign in with GitHub.

On the next page, click New app in the upper-right corner.

On the page shown above, select the repository you created in the Repository field.
Set Branch to main.
Set Main file path to app.py.
You can also customize the App URL if needed.
After configuring these settings, click Deploy!.
That completes the deployment process.
If the page that opens displays the same Streamlit interface you tested locally, deployment succeeded.
Source code

The code used in this article is available here.
Conclusion

This article covered building and deploying an application that summarizes content from links to services such as Voicy and YouTube.
I hope you found it useful.
The OpenAI API opens up many other possibilities, which I plan to explore in future articles.
I also recommend Streamlit as a straightforward way to turn Python code into an application.
If you have any questions, feel free to contact me via Twitter.
I usually write about Python and blockchain development.
I also share illustrated explanations on Twitter, so feel free to follow along.




