SheridanCoriana6

YouTube Line By Line Translated Subtitles

Nov 2nd, 2026
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.83 KB | Software | 0 0
  1. // ==UserScript==
  2. // @name YouTube Line By Line Translated Subtitles - Fix C & Icon Toggle
  3. // @namespace http://tampermonkey.net/
  4. // @version 2.8.9
  5. // @description Synchronizacja z klawiszem C i ikonką CC + fix pustej linii.
  6. // @author marek7400
  7. // @match *://www.youtube.com/*
  8. // @match *://www.youtube-nocookie.com/*
  9. // @run-at document-idle
  10. // @grant none
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. let activeSubData = null;
  17. let customSubtitleElement = null;
  18. let playerApi = null;
  19. let settings = {};
  20. let isHoveringControls = false;
  21. let lastActiveSubDataCache = null;
  22. let currentViewMode = 'normal';
  23.  
  24. const defaultSettings = {
  25. normal: { enabled: true, color: '#FFFFFF', fontSize: 22, bgOpacity: 0.8, bgColor: '#000000', vPosition: 40, timeOffset: 0, containerWidth: 80 },
  26. fullscreen: { enabled: true, color: '#FFFFFF', fontSize: 28, bgOpacity: 0.7, bgColor: '#000000', vPosition: 60, timeOffset: 0, containerWidth: 80 }
  27. };
  28.  
  29. function saveSettings() {
  30. try { localStorage.setItem('yt-custom-subs-settings', JSON.stringify(settings)); } catch(e) { console.error("Save error", e); }
  31. }
  32.  
  33. function loadSettings() {
  34. const saved = localStorage.getItem('yt-custom-subs-settings');
  35. if (saved) {
  36. try {
  37. const parsed = JSON.parse(saved);
  38. settings = {
  39. normal: { ...defaultSettings.normal, ...parsed.normal },
  40. fullscreen: { ...defaultSettings.fullscreen, ...parsed.fullscreen }
  41. };
  42. } catch(e) { settings = JSON.parse(JSON.stringify(defaultSettings)); }
  43. } else {
  44. settings = JSON.parse(JSON.stringify(defaultSettings));
  45. }
  46. }
  47.  
  48. function hexToRgba(hex, opacity) {
  49. let c;
  50. if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
  51. c = hex.substring(1).split('');
  52. if (c.length == 3) c = [c[0], c[0], c[1], c[1], c[2], c[2]];
  53. c = '0x' + c.join('');
  54. return `rgba(${[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',')},${opacity})`;
  55. }
  56. return `rgba(0,0,0,${opacity})`;
  57. }
  58.  
  59. function applyStyles() {
  60. if (!customSubtitleElement) return;
  61. const mode = document.fullscreenElement ? 'fullscreen' : 'normal';
  62. const s = settings[mode];
  63.  
  64. const controlsHeight = 75;
  65. const bottomPosition = isHoveringControls ? `${controlsHeight}px` : `${s.vPosition}px`;
  66.  
  67. customSubtitleElement.style.color = s.color;
  68. customSubtitleElement.style.fontSize = `${s.fontSize}px`;
  69. customSubtitleElement.style.backgroundColor = hexToRgba(s.bgColor, s.bgOpacity);
  70. customSubtitleElement.style.bottom = bottomPosition;
  71. customSubtitleElement.style.width = `${s.containerWidth}%`;
  72.  
  73. if (!customSubtitleElement.innerText.trim()) {
  74. customSubtitleElement.style.display = 'none';
  75. }
  76. }
  77.  
  78. // --- SYNCHRONIZACJA Z YT ---
  79. function syncSettingsWithNativeCC() {
  80. const ccBtn = document.querySelector('.ytp-subtitles-button');
  81. if (!ccBtn) return;
  82.  
  83. // Sprawdź czy natywny przycisk YouTube jest aktywny (aria-pressed="true")
  84. const isNativeActive = ccBtn.getAttribute('aria-pressed') === 'true';
  85.  
  86. if (settings.normal.enabled !== isNativeActive) {
  87. settings.normal.enabled = isNativeActive;
  88. settings.fullscreen.enabled = isNativeActive;
  89.  
  90. // Odśwież UI panelu jeśli jest otwarty
  91. const p = document.getElementById('yt-custom-subs-panel');
  92. if (p && p.style.display !== 'none') {
  93. const b = p.querySelector('.toggle-btn');
  94. if(b) {
  95. b.textContent = isNativeActive ? "Turn Subtitles OFF" : "Turn Subtitles ON";
  96. b.style.background = isNativeActive ? "#3ea6ff" : "#555";
  97. }
  98. }
  99. saveSettings();
  100. }
  101. }
  102.  
  103. function processSubtitles(data) {
  104. if (!data || !data.events) return [];
  105. return data.events
  106. .filter(e => e.segs && e.segs.map(s => s.utf8).join('').trim() !== '')
  107. .map((event, i, all) => {
  108. const start = event.tStartMs;
  109. const text = event.segs.map(s => s.utf8).join('').replace(/\\n/g, '\n').trim();
  110. const next = all[i + 1];
  111.  
  112. // FIX: Używamy docelowego czasu trwania (dDurationMs), aby napis znikał w trakcie ciszy.
  113. let end = start + (event.dDurationMs || 3000);
  114.  
  115. // Zabezpieczenie: jeśli czas trwania jest na tyle długi, że wchodzi na kolejny napis, przycinamy go.
  116. if (next && end > next.tStartMs) {
  117. end = next.tStartMs;
  118. }
  119.  
  120. if (end <= start) end = start + 1000;
  121. return { start, end, text };
  122. });
  123. }
  124.  
  125. const originalFetch = window.fetch;
  126. window.fetch = function(...args) {
  127. const url = args[0] instanceof URL ? args[0].href : String(args[0]);
  128. const fetchPromise = originalFetch.apply(window, args);
  129. if (url.includes('/api/timedtext')) {
  130. fetchPromise.then(response => {
  131. const clone = response.clone();
  132. clone.json().then(jsonData => {
  133. lastActiveSubDataCache = processSubtitles(jsonData);
  134. activeSubData = lastActiveSubDataCache;
  135. }).catch(() => {});
  136. }).catch(() => {});
  137. }
  138. return fetchPromise;
  139. };
  140.  
  141. const originalXhrOpen = XMLHttpRequest.prototype.open;
  142. XMLHttpRequest.prototype.open = function(m, url) {
  143. this._isSubs = String(url).includes('/api/timedtext');
  144. return originalXhrOpen.apply(this, arguments);
  145. };
  146. const originalXhrSend = XMLHttpRequest.prototype.send;
  147. XMLHttpRequest.prototype.send = function() {
  148. if (this._isSubs) {
  149. this.addEventListener('load', () => {
  150. try {
  151. const data = processSubtitles(JSON.parse(this.responseText));
  152. lastActiveSubDataCache = data;
  153. activeSubData = data;
  154. } catch(e) {}
  155. });
  156. }
  157. return originalXhrSend.apply(this, arguments);
  158. };
  159.  
  160. function renderSubtitle() {
  161. if (!playerApi || !customSubtitleElement) return;
  162.  
  163. // KROK 1: Synchronizuj stan z przyciskiem YT
  164. syncSettingsWithNativeCC();
  165.  
  166. const mode = document.fullscreenElement ? 'fullscreen' : 'normal';
  167.  
  168. if (!settings[mode]?.enabled) {
  169. customSubtitleElement.style.display = 'none';
  170. customSubtitleElement.innerText = '';
  171. return;
  172. }
  173.  
  174. if (!activeSubData && lastActiveSubDataCache) activeSubData = lastActiveSubDataCache;
  175. if (!activeSubData) {
  176. customSubtitleElement.style.display = 'none';
  177. return;
  178. }
  179.  
  180. const timeMs = (playerApi.getCurrentTime() * 1000) + (settings[mode].timeOffset || 0);
  181. const active = activeSubData.find(sub => timeMs >= sub.start && timeMs < sub.end);
  182.  
  183. if (active && active.text.trim()) {
  184. if (customSubtitleElement.innerText !== active.text) {
  185. customSubtitleElement.innerText = active.text;
  186. }
  187. customSubtitleElement.style.display = 'block';
  188. customSubtitleElement.style.opacity = '1';
  189. } else {
  190. customSubtitleElement.style.opacity = '0';
  191. customSubtitleElement.style.display = 'none';
  192. customSubtitleElement.innerText = '';
  193. }
  194. }
  195.  
  196. // --- PANEL USTAWIEŃ ---
  197. function createPanel() {
  198. if (document.getElementById('yt-custom-subs-panel')) return;
  199.  
  200. const panel = document.createElement('div');
  201. panel.id = 'yt-custom-subs-panel';
  202. panel.style.cssText = `
  203. position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%);
  204. width: 350px; background: #181818; color: white; border-radius: 12px;
  205. z-index: 2147483646; font-family: sans-serif; display: flex; flex-direction: column;
  206. border: 1px solid #3e3e3e; box-shadow: 0 8px 32px rgba(0,0,0,0.8); font-size: 14px;
  207. `;
  208.  
  209. const styleTag = document.createElement('style');
  210. styleTag.textContent = `
  211. #yt-custom-subs-panel .control-group { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
  212. #yt-custom-subs-panel .slider-group { display: flex; flex-direction: column; gap: 5px; margin-bottom: 10px; }
  213. #yt-custom-subs-panel .slider-wrapper { display: flex; align-items: center; gap: 10px; }
  214. #yt-custom-subs-panel input[type=range] { flex-grow: 1; accent-color: #3ea6ff; }
  215. #yt-custom-subs-panel input[type=number] { width: 60px; background: #333; color: #fff; border: 1px solid #555; border-radius: 4px; padding: 2px 5px; }
  216. #yt-custom-subs-panel input[type=color] { border: 1px solid #555; background: none; width: 40px; height: 25px; cursor: pointer; }
  217. #yt-custom-subs-panel .toggle-btn { width: 100%; padding: 10px; background: #3ea6ff; color: #000; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; margin-bottom: 15px; }
  218. #yt-custom-subs-panel .mode-selector { text-align: center; padding: 10px 0; border-bottom: 1px solid #333; margin-bottom: 15px; }
  219. #yt-custom-subs-panel .mode-selector label { cursor: pointer; margin: 0 10px; }
  220. `;
  221. document.head.appendChild(styleTag);
  222.  
  223. const header = document.createElement('div');
  224. header.style.cssText = "padding: 12px; background: #282828; border-bottom: 1px solid #3e3e3e; cursor: move; border-top-left-radius: 12px; border-top-right-radius: 12px; display: flex; justify-content: space-between; font-weight: bold;";
  225.  
  226. const headerTitle = document.createElement('span');
  227. headerTitle.textContent = "⚙️ Subtitle Settings";
  228. const closeX = document.createElement('span');
  229. closeX.textContent = "✕";
  230. closeX.style.cssText = "cursor:pointer; padding: 0 5px;";
  231. closeX.onclick = () => { panel.style.display = 'none'; };
  232.  
  233. header.appendChild(headerTitle);
  234. header.appendChild(closeX);
  235. panel.appendChild(header);
  236.  
  237. const content = document.createElement('div');
  238. content.style.padding = "15px";
  239. panel.appendChild(content);
  240.  
  241. const toggleBtn = document.createElement('button');
  242. toggleBtn.className = "toggle-btn";
  243. content.appendChild(toggleBtn);
  244.  
  245. const modeDiv = document.createElement('div');
  246. modeDiv.className = "mode-selector";
  247. const createRadio = (val, labelText, checked) => {
  248. const lbl = document.createElement('label');
  249. const rad = document.createElement('input');
  250. rad.type = "radio"; rad.name = "viewMode"; rad.value = val; rad.checked = checked;
  251. rad.onchange = (e) => { currentViewMode = e.target.value; updatePanelUI(); };
  252. lbl.appendChild(rad);
  253. lbl.appendChild(document.createTextNode(" " + labelText));
  254. return lbl;
  255. };
  256. modeDiv.appendChild(createRadio("normal", "Normal", true));
  257. modeDiv.appendChild(createRadio("fullscreen", "Fullscreen", false));
  258. content.appendChild(modeDiv);
  259.  
  260. const updatePanelUI = () => {
  261. const s = settings[currentViewMode];
  262. toggleBtn.textContent = s.enabled ? "Turn Subtitles OFF" : "Turn Subtitles ON";
  263. toggleBtn.style.background = s.enabled ? "#3ea6ff" : "#555";
  264. panel.querySelectorAll('[data-key]').forEach(input => {
  265. input.value = s[input.dataset.key];
  266. });
  267. };
  268.  
  269. const createRow = (labelStr, type, key, props = {}) => {
  270. const div = document.createElement('div');
  271. div.className = "control-group";
  272. const lbl = document.createElement('label'); lbl.textContent = labelStr;
  273. const inp = document.createElement('input'); inp.type = type; inp.dataset.key = key;
  274. Object.assign(inp, props);
  275. div.appendChild(lbl); div.appendChild(inp);
  276. return div;
  277. };
  278.  
  279. const createSliderRow = (labelStr, key, min, max, step) => {
  280. const div = document.createElement('div');
  281. div.className = "slider-group";
  282. const lbl = document.createElement('label'); lbl.textContent = labelStr;
  283. const wrap = document.createElement('div'); wrap.className = "slider-wrapper";
  284. const range = document.createElement('input'); range.type = "range"; range.dataset.key = key; range.min = min; range.max = max; range.step = step;
  285. const num = document.createElement('input'); num.type = "number"; num.dataset.key = key; num.min = min; num.max = max; num.step = step;
  286. wrap.appendChild(range); wrap.appendChild(num); div.appendChild(lbl); div.appendChild(wrap);
  287. return div;
  288. };
  289.  
  290. content.appendChild(createRow("Color:", "color", "color"));
  291. content.appendChild(createRow("Font Size (px):", "number", "fontSize", { min: 8, max: 80 }));
  292. content.appendChild(createSliderRow("Container Width (%):", "containerWidth", 40, 100, 1));
  293. content.appendChild(createRow("BG Color:", "color", "bgColor"));
  294. content.appendChild(createSliderRow("BG Opacity:", "bgOpacity", 0, 1, 0.05));
  295. content.appendChild(createSliderRow("V-Position (px):", "vPosition", 0, 600, 1));
  296. content.appendChild(createRow("Time Offset (ms):", "number", "timeOffset", { step: 50 }));
  297.  
  298. document.body.appendChild(panel);
  299.  
  300. panel.addEventListener('input', (e) => {
  301. const key = e.target.dataset.key;
  302. if (!key) return;
  303. const val = e.target.type === 'color' ? e.target.value : parseFloat(e.target.value);
  304. settings[currentViewMode][key] = val;
  305. panel.querySelectorAll(`[data-key="${key}"]`).forEach(el => { el.value = val; });
  306. applyStyles();
  307. saveSettings();
  308. });
  309.  
  310. toggleBtn.onclick = () => {
  311. // Kliknięcie w panelu teraz symuluje kliknięcie w ikonkę YouTube
  312. const ccBtn = document.querySelector('.ytp-subtitles-button');
  313. if (ccBtn) ccBtn.click();
  314. };
  315.  
  316. let isDragging = false, offset = { x: 0, y: 0 };
  317. header.onmousedown = (e) => {
  318. isDragging = true;
  319. offset.x = e.clientX - panel.offsetLeft;
  320. offset.y = e.clientY - panel.offsetTop;
  321. };
  322. document.addEventListener('mousemove', (e) => {
  323. if (!isDragging) return;
  324. panel.style.left = (e.clientX - offset.x) + "px";
  325. panel.style.top = (e.clientY - offset.y) + "px";
  326. panel.style.transform = "none";
  327. });
  328. document.addEventListener('mouseup', () => { isDragging = false; });
  329.  
  330. updatePanelUI();
  331. }
  332.  
  333. function ensureGlobalUI() {
  334. const headerButtons = document.querySelector('#end #buttons') || document.querySelector('#buttons.ytd-masthead');
  335. if (!headerButtons) return;
  336.  
  337. let btn = document.getElementById('yt-cs-compact-btn');
  338. if (!btn) {
  339. btn = document.createElement('div');
  340. btn.id = 'yt-cs-compact-btn';
  341. const iconSpan = document.createElement('span'); iconSpan.textContent = "⚙️"; iconSpan.style.marginRight = "4px";
  342. const textSpan = document.createElement('span'); textSpan.textContent = "Subs";
  343. btn.appendChild(iconSpan); btn.appendChild(textSpan);
  344.  
  345. btn.style.cssText = `
  346. display: inline-flex !important; align-items: center !important;
  347. background-color: #000 !important; color: #fff !important;
  348. padding: 2px 8px !important; margin-right: 12px !important;
  349. font-size: 11px !important; font-family: Arial, sans-serif !important;
  350. font-weight: bold !important; cursor: pointer !important;
  351. border: 1px solid #333 !important; border-radius: 4px !important;
  352. user-select: none !important; height: 24px !important;
  353. align-self: center !important; z-index: 9999 !important;
  354. `;
  355.  
  356. btn.onclick = (e) => {
  357. e.preventDefault(); e.stopPropagation();
  358. const p = document.getElementById('yt-custom-subs-panel');
  359. if (p) { p.style.display = (p.style.display === 'none' ? 'flex' : 'none'); }
  360. else { createPanel(); }
  361. };
  362.  
  363. const allElements = headerButtons.querySelectorAll('*');
  364. let eyeElement = null;
  365. for (let el of allElements) {
  366. if (el.textContent && el.textContent.includes('👁️')) { eyeElement = el; break; }
  367. }
  368.  
  369. if (eyeElement) eyeElement.parentNode.insertBefore(btn, eyeElement);
  370. else headerButtons.insertBefore(btn, headerButtons.firstChild);
  371. }
  372. }
  373.  
  374. function init() {
  375. const player = document.getElementById('movie_player');
  376. if (player && !window.__SUBS_INIT__) {
  377. window.__SUBS_INIT__ = true;
  378. playerApi = player;
  379. loadSettings();
  380.  
  381. if (!document.getElementById('yt-subs-hide-orig')) {
  382. const s = document.createElement('style');
  383. s.id = 'yt-subs-hide-orig';
  384. s.textContent = `.ytp-caption-window-container { display: none !important; }`;
  385. document.head.appendChild(s);
  386. }
  387.  
  388. customSubtitleElement = document.createElement('div');
  389. customSubtitleElement.id = 'yt-custom-subs-element';
  390. customSubtitleElement.style.cssText = `
  391. position: absolute; left: 50%; transform: translateX(-50%);
  392. padding: 3px 10px; border-radius: 4px; text-align: center;
  393. z-index: 101; pointer-events: none; transition: opacity 0.2s, bottom 0.2s;
  394. text-shadow: 1px 1px 2px #000, -1px -1px 2px #000; white-space: pre-line;
  395. font-family: "YouTube Noto", Roboto, Arial, sans-serif;
  396. display: none;
  397. `;
  398. player.appendChild(customSubtitleElement);
  399.  
  400. const controls = player.querySelector('.ytp-chrome-bottom');
  401. if (controls) {
  402. controls.addEventListener('mouseenter', () => { isHoveringControls = true; applyStyles(); });
  403. controls.addEventListener('mouseleave', () => { isHoveringControls = false; applyStyles(); });
  404. }
  405.  
  406. const observer = new MutationObserver(() => { applyStyles(); });
  407. observer.observe(player, { attributes: true, attributeFilter:['class'] });
  408.  
  409. document.addEventListener('fullscreenchange', () => { setTimeout(applyStyles, 100); });
  410. setInterval(renderSubtitle, 100);
  411. }
  412. ensureGlobalUI();
  413. }
  414.  
  415. setInterval(init, 1000);
  416.  
  417. document.addEventListener('keydown', (e) => {
  418. if (['INPUT', 'TEXTAREA'].includes(e.target.tagName) || e.target.isContentEditable) return;
  419.  
  420. // Jeśli użytkownik naciska X lub C, chcemy wywołać natywne przełączenie napisów
  421. // klawisz 'C' YouTube obsługuje sam, ale klawisz 'X' musimy "podpiąć" pod kliknięcie ikonki
  422. if (e.key.toLowerCase() === 'x') {
  423. const ccBtn = document.querySelector('.ytp-subtitles-button');
  424. if (ccBtn) ccBtn.click();
  425. }
  426. // Dla klawisza 'C' nic nie robimy - YouTube zmieni stan ikonki CC,
  427. // a nasza funkcja renderSubtitle sama wykryje tę zmianę i włączy/wyłączy napisy skryptu.
  428. });
  429. })();
Advertisement
Add Comment
Please, Sign In to add comment