Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

podcast script generation component #15

Merged
merged 32 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
536c98d
Add devcontainer and requirements
daavoo Nov 14, 2024
0ae661e
Add pyproject.toml
daavoo Nov 15, 2024
c4a1ee1
Add data_loaders and tests
daavoo Nov 15, 2024
d2b276c
Add data_cleaners and tests
daavoo Nov 15, 2024
8629481
Update demo
daavoo Nov 15, 2024
cef92b3
Add `LOADERS` and `CLEANERS`
daavoo Nov 19, 2024
acd50a9
Add markdown and docx
daavoo Nov 19, 2024
2a8f005
Add API Reference
daavoo Nov 19, 2024
95c342a
Update tests
daavoo Nov 19, 2024
e8ac586
Update install
daavoo Nov 19, 2024
ee7d299
Add initial scripts
daavoo Nov 19, 2024
fb38207
More tests
daavoo Nov 20, 2024
29df436
Merge remote-tracking branch 'origin/main' into AH-104-Initial-Podcas…
daavoo Nov 21, 2024
d4b6066
fix merge
daavoo Nov 21, 2024
abeb3c0
Add podcast writing to demo/app
daavoo Nov 21, 2024
4bcc57b
Add missing deps
daavoo Nov 21, 2024
06627fa
Add text_to_podcast module
daavoo Nov 21, 2024
4457813
Expose model options and prompt tuning in the app
daavoo Nov 21, 2024
c73d4d3
pre-commit
daavoo Nov 21, 2024
a868093
Strip system_prompt
daavoo Nov 21, 2024
8b2c57b
Rename to inference module. Add docstrings
daavoo Nov 22, 2024
d2c75c9
pre-commit
daavoo Nov 22, 2024
7a7e39c
Add CURATED_REPOS
daavoo Nov 22, 2024
e1c6ccb
JSON prompt
daavoo Nov 22, 2024
72413a1
Update API docs
daavoo Nov 22, 2024
8817ea0
Fix format
daavoo Nov 22, 2024
06a2c3d
Make text cutoff based on `model.n_ctx()`. Consider ~4 characters per…
daavoo Nov 25, 2024
39fb3b3
Add inference tests
daavoo Nov 25, 2024
1968278
Drop __init__ imports
daavoo Nov 25, 2024
f88b713
Fix outdated arg
daavoo Nov 25, 2024
73ac7bf
Drop redundant JSON output in prompt
daavoo Nov 25, 2024
1c11c98
Update default stop
daavoo Nov 25, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/.devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
},
"packages": ["libgl1-mesa-dev"]
},
"postCreateCommand": "pip install -e '.[demo]'"
"postCreateCommand": "pip install -e . --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu"
}
51 changes: 49 additions & 2 deletions demo/app.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
from pathlib import Path

import streamlit as st
from huggingface_hub import list_repo_files

from opennotebookllm.preprocessing import DATA_LOADERS, DATA_CLEANERS
from opennotebookllm.text_to_podcast import load_model
from opennotebookllm.text_to_podcast import text_to_podcast

PODCAST_PROMPT = """
daavoo marked this conversation as resolved.
Show resolved Hide resolved
Convert this text into a podcast script.
The conversation should be between 2 speakers.
Use [SPEAKER1] and [SPEAKER2] to limit sections.
Do not include [INTRO], [OUTRO] or any other [SECTION].
Text:
"""

REPO = "allenai/OLMoE-1B-7B-0924-Instruct-GGUF"

uploaded_file = st.file_uploader(
"Choose a file", type=["pdf", "html", "txt", "docx", "md"]
Expand All @@ -17,9 +29,44 @@
raw_text = DATA_LOADERS[extension](uploaded_file)
with col1:
st.title("Raw Text")
st.write(raw_text[:200])
st.text_area(f"Total Length: {len(raw_text)}", f"{raw_text[:500]} . . .")

clean_text = DATA_CLEANERS[extension](raw_text)
with col2:
st.title("Cleaned Text")
st.write(clean_text[:200])
st.text_area(f"Total Length: {len(clean_text)}", f"{clean_text[:500]} . . .")

# I set this value as a quick safeguard but we should actually tokenize the text and count the number of real tokens.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stefanfrench :

I think we should try to set the text limit from the input doc in a bit of a more rigorous way, e.g. doing it based on the actual number of real tokens as you suggest in your comment. If you prefer we can do this as a separate issue

I am currently looking into this. I am trying to find a way to use the llama_cpp API to don't waste the tokenization call just for the sake of filtering.
If I don't find an easy solution today, maybe we can consider it a follow-up to not block the full PR

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@daavoo - sounds good!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I gave it a try (to encode first) but the code became way more complicated.
However, it seems that people consider 1 token ~= 4 characters a common default and it is the value used when trying to estimate token consumption without expending calls.

So, I updated the code to use this 4 approximation and made a small improvement to use the context lenght associated to each model (before I was too lazy and just hardcoded the number to 4096 as it was the value for OLMoE)

if len(clean_text) > 4096 * 3:
st.warning(
f"Input text is too big ({len(clean_text)}). Using only a subset of it ({4096 * 3})."
)
clean_text = clean_text[: 4096 * 3]

model_name = st.selectbox(
"Select Model",
[
x
for x in list_repo_files(REPO)
if ".gguf" in x
# The float16 is too big for the 16GB RAM codespace
and "f16" not in x
],
index=None,
)
if model_name:
with st.spinner("Downloading and Loading Model..."):
model = load_model(model_id=f"{REPO}/{model_name}")

system_prompt = st.text_area("Podcast generation prompt", value=PODCAST_PROMPT)

if st.button("Generate Podcast Script"):
with st.spinner("Generating Podcast Script..."):
text = ""
for chunk in text_to_podcast(
clean_text, model, system_prompt=system_prompt.strip(), stream=True
):
text += chunk
if text.endswith("\n"):
st.write(text)
text = ""
9 changes: 4 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ requires-python = ">=3.10"
dynamic = ["version"]
dependencies = [
"beautifulsoup4",
"huggingface-hub",
"llama-cpp-python",
"loguru",
"PyPDF2[crypto]",
"python-docx"
"python-docx",
"streamlit",
]

[project.optional-dependencies]
Expand All @@ -27,10 +30,6 @@ tests = [
"pytest-sugar>=0.9.6",
]

demo = [
"streamlit"
]

[project.urls]
Documentation = "https://mozilla-ai.github.io/OpenNotebookLLM/"
Issues = "https://github.com/mozilla-ai/OpenNotebookLLM/issues"
Expand Down
2 changes: 2 additions & 0 deletions src/opennotebookllm/text_to_podcast/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .inference import load_model as load_model
from .inference import text_to_podcast as text_to_podcast
32 changes: 32 additions & 0 deletions src/opennotebookllm/text_to_podcast/inference.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from llama_cpp import Llama


def load_model(
model_id: str = "allenai/OLMoE-1B-7B-0924-Instruct-GGUF/olmoe-1b-7b-0924-instruct-q8_0.gguf",
) -> Llama:
org, repo, filename = model_id.split("/")
model = Llama.from_pretrained(
repo_id=f"{org}/{repo}",
filename=filename,
# 0 means that the model limit will be used, instead of the default (512) or other hardcoded value
n_ctx=0,
)
return model


def text_to_podcast(
input_text: str, model: Llama, system_prompt: str, stream: bool = False
):
response = model.create_chat_completion(
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": input_text},
],
stream=stream,
)
if stream:
for item in response:
if item["choices"][0].get("delta", {}).get("content", None):
yield item["choices"][0].get("delta", {}).get("content", None)
else:
return response["choices"][0]["message"]["content"]