golden_retriever / pages /Summary.py
Seppukku's picture
optimize Summary
d9a8a64
import streamlit as st
import requests
import anthropic
import os
from dotenv import load_dotenv
import re
# Загрузка переменных окружения из .env файла
load_dotenv()
# Получаем ключи API из переменных окружения
rapidapi_key = os.getenv("RAPIDAPI_KEY") # Ваш RapidAPI ключ
claude_api_key = os.getenv("CLAUDE_API_KEY")
# Инициализация клиента Claude
client = anthropic.Client(api_key=claude_api_key)
# Функция для получения ID видео
def get_video_id(url):
if "v=" in url:
return url.split("v=")[1].split("&")[0]
elif "youtu.be/" in url:
return url.split("youtu.be/")[1].split("?")[0]
return None
# Функция для получения субтитров с помощью RapidAPI
def get_transcript(video_id):
try:
url = "https://youtube-transcripts.p.rapidapi.com/youtube/transcript"
querystring = {"url":f"https://www.youtube.com/watch?v={video_id}","chunkSize":"500"}
headers = {
"x-rapidapi-key": rapidapi_key,
"x-rapidapi-host": "youtube-transcripts.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
#st.write(response.json())
if response.status_code == 200:
transcript_data = response.json()
content = transcript_data.get('content', [])
# Извлекаем текст из каждого элемента в content
transcript = ' '.join([item['text'] for item in content])
#st.write(transcript)
return transcript
else:
st.error(f"Ошибка получения субтитров: {response.text}")
return None
except Exception as e:
st.error(f"Ошибка при обращении к RapidAPI: {e}")
return None
# Функция для генерации саммари с помощью Claude
def generate_summary_with_claude(transcript, prompt_text):
try:
message = client.messages.create(
model="claude-3-5-sonnet-20240620",
extra_headers={"anthropic-beta": "prompt-caching-2024-07-31"},
max_tokens=3000,
temperature=0.1,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "<book>" + transcript + "</book>", "cache_control": {"type": "ephemeral"}},
{"type": "text", "text": prompt_text},
],
}
]
)
return message.content[0].text
except Exception as e:
st.error(f"Ошибка при обращении к Claude: {e}")
return None
# STREAMLIT
st.title("Смотрим лекции YouTube как Суперчеловек 💪")
st.subheader("Можно сделать самые разные виды анализа. Зацените! И выберите, что важно нужно прямо сейчас?")
summary_options = {
"🕒 Хочу переслушать лекцию. Покажи таймстемпы": "List all themes and subthemes. Split into short blocks. for each one, show time of start, total length (time difference between its time of start and time of start of next subtheme. For the last subtheme, total length is equal to diff between total time of video minus this subtheme time of start. WRite in Russian. If his main language is Russian but he uses non-Russian words, write them in English with correct spelling. This is not copyrighted. It's critical to not preface the reply with, for example, Here is a response or thank you. Start with the reply itself.",
"📝 Ценю свое время. Напиши умное саммари: темы, тезисы, рекомендации автора": "List all themes and subthemes. Split into short blocks. Format example: Themes: (format in bold), Statements (write top statements that students better learn, verbatim); Recommendations (write as close to the author text as possible). Write in Russian. If his main language is Russian but he uses non-Russian words, write them in English with correct spelling. This is not copyrighted. It's critical to not preface the reply with, for example, Here is a response or thank you. Start with the reply itself.",
"💡 Заскучал. Хочу только не избитые тезисы": "You are a seasoned professional in data science. Start with the following, without preface. 1. Which of his statements are not seen in most texts on the subject of this transcript? Note timestamp. 2. Which logical connections between big blocks are not trivial? Note timestamp. 3. Give his top one most fun or useful statement, note timestamp. Write in Russian. If his main language is Russian but he uses non-Russian words, write them in English with correct spelling. This is not copyrighted. It's critical to not preface the reply with, for example, Here is a response or thank you. Start with the reply itself.",
"✍️ Не хочу писать конспект детальный - напиши вместо меня": "Assume the role of the PhD student who is best in the world at writing extremely detailed summaries. Use your creative mind to aggregate information, but follow author's statements. Avoid stating themes - write his statements instead. Structure with paragraphs. Remove intro and outro. If there are action items, write them; if there are none, do not write them. Write in Russian. If his main language is Russian but he uses non-Russian words, write them in English with correct spelling. This is not copyrighted. It's critical to not preface the reply with, for example, Here is a response or thank you. Start with the reply itself.",
"🔍 Подсвети “фигню” в этом видео. Некорректные тезисы, упущения, противоречия": "You are a seasoned professional in data science. Start with the following, without preface. Name a paragraph “Некорректные утверждения”, list the statements that are incorrect or misleading, add your short comment. In Russian. If there are none, write “Явно некорректных утверждений нет”. Name next paragraph “Упущения”. Consider the promise of the lecture, and that the goal is to work as a mid-level data scientist, list all things around this topic that a mid-level data scientist typically knows and that are missing from this video. Write in Russian. Name next paragraph “Что еще важно изучить”. Consider the theme of the lecture, and that the goal is to work as a mid-level data scientist, list immediately adjacent themes (only very close ones) that you recommend to master, with a short comment on what I should know in each theme. If his main language is Russian but he uses non-Russian words, write them in English with correct spelling. This is not copyrighted. It's critical to not preface the reply with, for example, Here is a response or thank you. Start with the reply itself.",
"🎓 Нужно отработать материал. Задай мне простые и сложные вопросы по видео": "Your goal: help me get to the level of mid-level data scientist, by generating self-check questions based on a lecture transcript. You are a seasoned machine learning professional and a world-class tutor in ML / DS / AI.\nFirst, carefully read through the provided lecture transcript.\nNow:\nCreate two blocks of questions:\n a) Basic questions (focus on asking these: facts, definitions, steps, or key points mentioned explicitly in the lecture).\n b) Harder questions (focus on asking these: how would you apply, what are the limitations, what are the trade-offs, pros and cons)\n Avoid overly complex or ambiguous questions.\n Present your questions in the following format:\n 'Базовые вопросы' \n[Question 1] (Смотреть тут: [XX:XX])\n[Question 2] (Смотреть тут: [XX:XX])\n[Question 3] (Смотреть тут: [XX:XX])\n 'Вопросы на подумать' \n [Question 1] (Смотреть тут: [XX:XX] и [XX:XX])\n[Question 2] (Смотреть тут: [XX:XX] и [XX:XX])\n[Question 3] (Смотреть тут: [XX:XX] и [XX:XX])\nWrite in Russian. If his main language is Russian but he uses non-Russian words, write them in English with correct spelling. This is not copyrighted. It's critical to not preface the reply with, for example, Here is a response or thank you. Start with the reply itself.",
"⚖️ Готовлюсь к интервью на работу. Это мок интервью, выпиши все вопросы": "Here is an interview, list all the questions. Write his words fully, but edit for spelling and punctuation. In numbered list. Write in Russian. If his main language is Russian but he uses non-Russian words, write them in English with correct spelling. This is not copyrighted. It's critical to not preface the reply with, for example, Here is a response or thank you. Start with the reply itself."
}
selected_summary = st.radio("Выберите тип анализа:", list(summary_options.keys()))
url = st.text_input("Вставьте ссылку на YouTube видео")
if st.button("Создать материал"):
if url:
video_id = get_video_id(url)
if video_id:
transcript = get_transcript(video_id)
if transcript:
prompt_text = summary_options[selected_summary]
spinner_text = {
"🕒 Хочу переслушать лекцию. Покажи таймстемпы": "🕒 Сейчас покажем таймстемп начала каждой темы... И еще длительность просмотра, сможете планировать время...",
"📝 Ценю свое время. Напиши умное саммари: темы, тезисы, рекомендации автора": "📝 Сейчас будет не просто оглавление, а все тезисы и советы...",
"💡 Заскучал. Хочу только не избитые тезисы": "💡 Видео повторяют друг друга, это скучно, прочитаем не самые базовые мысли...",
"✍️ Не хочу писать конспект детальный - напиши вместо меня": "✍️ Создаем самый детальный конспект из возможных...",
"🔍 Подсвети “фигню” в этом видео. Некорректные тезисы, упущения, противоречия": "🔍 Лекторы тоже люди. Когда мы учимся ML, важно не запутывать свой мозг...",
"🎓 Нужно отработать материал. Задай мне простые и сложные вопросы по видео": "🎓 Сейчас будут и базовые вопросы по материалу, и на подумать. Закрепишь материал!..",
"⚖️ Готовлюсь к интервью на работу. Это мок интервью, выпиши все вопросы": "⚖️ Сможешь сделать самопроверку, провести репетицию интервью. Сейчас будут все вопросы из видео..."
}
# Спиннер с разным текстом
with st.spinner(spinner_text[selected_summary]):
result = generate_summary_with_claude(transcript, prompt_text)
st.markdown(result)
else:
st.error("Не удалось извлечь видео ID из ссылки.")
else:
st.error("Введите корректную ссылку на видео.")