Skip to content

Instantly share code, notes, and snippets.

@subtleGradient
Last active June 7, 2020 19:50
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save subtleGradient/9b1eb9b6356c861ee3b7395c11bab9d2 to your computer and use it in GitHub Desktop.
Save subtleGradient/9b1eb9b6356c861ee3b7395c11bab9d2 to your computer and use it in GitHub Desktop.
bookmarklet = () =>
(async () => {
// https://gist.github.com/subtleGradient/9b1eb9b6356c861ee3b7395c11bab9d2
/*!
Copyright 2020 Thomas Aylott <oblivious@subtlegradient.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
async function download(fileName, data) {
const content =
typeof data === "string" || data instanceof Blob
? data
: JSON.stringify(data);
const downloadURL = window.URL.createObjectURL(
new Blob([content], { type: "application/json" })
);
const anchor = document.createElement("a");
anchor.download = fileName;
anchor.href = downloadURL;
await new Promise(resolve => setTimeout(resolve, 0));
anchor.dispatchEvent(new MouseEvent("click"));
}
function nextFrame() {
return new Promise(done => {
requestAnimationFrame(done);
});
}
async function mainTY() {
const clickOpenTranscript = () =>
[...document.querySelectorAll("ytd-menu-service-item-renderer")]
.filter(it => it.textContent.includes("Open transcript"))
.map(b => b.click()).length > 0;
const clickOpenMenu = () =>
[
...document.querySelectorAll('[aria-label="More actions"]')
].forEach(b => b.click());
async function turnOnTranscript() {
if (!clickOpenTranscript()) {
clickOpenMenu();
await nextFrame();
clickOpenTranscript();
}
}
const getTranscriptRootNode = () =>
document.querySelector("ytd-transcript-renderer");
const getTranscriptData = async () => {
if (!getTranscriptRootNode()) {
await turnOnTranscript();
await nextFrame();
if (!getTranscriptRootNode()) {
throw new Error("failed trying to open the transcript");
}
}
return getTranscriptRootNode().__data.data.body;
};
const transcriptToText = body =>
body.transcriptBodyRenderer.cueGroups
.map(cueGroup =>
cueGroup.transcriptCueGroupRenderer.cues.map(cue =>
cue.transcriptCueRenderer.cue.runs && cue.transcriptCueRenderer.cue.runs.map(run => run.text) || cue.transcriptCueRenderer.cue.simpleText
)
)
.flat()
.flat()
.join("\n");
const rawTextToPunctuated = (text, meta = null) => {
const puncWrap = document.createElement("aop-punc-wrap");
puncWrap.innerHTML = `
<form target=_aopPuncResult method=POST action="http://bark.phon.ioc.ee/punctuator">
<input type=hidden name=text>
</form>
`;
document.body.appendChild(puncWrap);
console.log(puncWrap);
puncWrap.querySelector(`input[name="text"]`).value = text;
const form = puncWrap.querySelector(`form`);
if (meta) {
form.action += `?meta=` + encodeURIComponent(JSON.stringify(meta));
}
form.submit();
};
const getYTID = () =>
document.location.search
.split(/[?&]/)
.filter(it => it.startsWith("v="))[0]
.split("=")[1];
const getMeta = () =>
JSON.parse(document.getElementById("scriptTag").innerText);
const transcript = await getTranscriptData();
const {
thumbnailUrl: [thumbnailUrl0],
name,
uploadDate,
description
} = getMeta();
/////////////////////////////////////
const meta = {
title: name,
id: getYTID(),
url: document.location.href,
uploadDate,
img: thumbnailUrl0,
description,
channel: {
name: document.querySelector("yt-formatted-string.ytd-channel-name>a")
.innerText,
url: document.querySelector("yt-formatted-string.ytd-channel-name>a")
.href
}
};
download(`transcript-${getYTID()}-${name}.json`, { meta, transcript });
rawTextToPunctuated(transcriptToText(transcript), meta);
}
async function mainPunc() {
const {
title,
id,
url,
uploadDate,
img,
description,
channel
} = JSON.parse(
decodeURIComponent(document.location.search.split("=")[1])
);
const roamDoc = [
{
title,
children: [
{ string: `by:: [[${channel.name}]] [link](${channel.url})` },
{ string: "canonical url:: " + url },
{ string: "uploadDate:: " + uploadDate },
{ string: `thumbnail:: ![](${img})` },
{ string: `video:: {{youtube: ${url}}}` },
{ string: "description::", children: [{ string: description }] },
{
string: "our notes:: ",
children: [{ string: "{{[[TODO]]}} write up some notes?" }]
},
{
string: "transcript::",
children: [
{
string:
"Punctuation automatically added using [Punctuator](http://bark.phon.ioc.ee/punctuator) by [[Ottokar Tilk]]"
},
{ string: "" },
...document.body.innerText
.split(/(?<=[.?!]) ?/g)
.map(string => ({ string }))
]
}
]
}
];
download(`transcript-${id}-${title}.roam.json`, roamDoc);
}
try {
if (location.host.endsWith("youtube.com")) {
await mainTY();
} else if (location.host.endsWith("bark.phon.ioc.ee")) {
await mainPunc();
}
} catch (e) {
console.error(e);
}
})();
BOOKMARKLET = `javascript:void (${encodeURIComponent(
bookmarklet.toString()
)})()`;
prompt(
`Copy this and paste it into your console.
Then paste that as a new bookmark.
Press enter to execute now`,
`copy(BOOKMARKLET)`
) && bookmarklet();
@subtleGradient
Copy link
Author

subtleGradient commented Jan 20, 2020

Usage (after installation)

  1. Go to a YouTube video page
  2. Click the bookmarklet
    • It should open the transcript panel on the screen
    • and starts loading the transcript from the server
  3. Click it again (after the transcript shows up)
    • and then download a JSON of the raw transcript data
    • and open a new window with the text transcript converted to proper punctuation
  4. Click the bookmarklet again (after the page finishes loading)
    • it should download a *.roam.json file
  5. Import your *.roam.json file into your RoamResearch DB

If you find any bugs, comment here.

@subtleGradient
Copy link
Author

subtleGradient commented Jan 20, 2020

How to install

  1. Open the browser devtools
  2. Copy all that code above & paste it into the devtools console
    • a prompt will open with the text copy(BOOKMARKLET) selected
    • press return/OK to execute the script immediately
    • press escape to close the prompt without executing the script
  3. Paste copy(BOOKMARKLET) into the devtools console
    • now you have the bookmarklet URI ready
  4. Create a new bookmark and set the pasted bookmarklet code URI as the bookmark url

@subtleGradient
Copy link
Author

@Klaudioz
Copy link

Klaudioz commented May 9, 2020

Hello, thanks for this tutorial. I'm trying to get the transcript for this video: https://www.youtube.com/watch?v=VtWDs6Zj2lc
and I'm getting the following in Roam: Screenshot

@subtleGradient
Copy link
Author

Hello, thanks for this tutorial. I'm trying to get the transcript for this video: https://www.youtube.com/watch?v=VtWDs6Zj2lc
and I'm getting the following in Roam: Screenshot

weird 🤷‍♀️

@Klaudioz
Copy link

Klaudioz commented Jun 7, 2020

Hello, thanks for this tutorial. I'm trying to get the transcript for this video: https://www.youtube.com/watch?v=VtWDs6Zj2lc
and I'm getting the following in Roam: Screenshot

weird

Sorry .. it was my bad trying to upload the json without roam in the name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment