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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"source": [
|
| 6 |
+
"!pip install -q -r requirements.txt"
|
| 7 |
+
],
|
| 8 |
+
"metadata": {
|
| 9 |
+
"colab": {
|
| 10 |
+
"base_uri": "https://localhost:8080/"
|
| 11 |
+
},
|
| 12 |
+
"id": "_r4UUCGMTYac",
|
| 13 |
+
"outputId": "ceb295aa-f5cb-48ce-d194-5322d319461d"
|
| 14 |
+
},
|
| 15 |
+
"execution_count": 1,
|
| 16 |
+
"outputs": [
|
| 17 |
+
{
|
| 18 |
+
"output_type": "stream",
|
| 19 |
+
"name": "stdout",
|
| 20 |
+
"text": [
|
| 21 |
+
" Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n",
|
| 22 |
+
" Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n",
|
| 23 |
+
" Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
|
| 24 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m57.6/57.6 kB\u001b[0m \u001b[31m1.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 25 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m32.8/32.8 MB\u001b[0m \u001b[31m1.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 26 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m85.5/85.5 MB\u001b[0m \u001b[31m1.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 27 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m817.7/817.7 kB\u001b[0m \u001b[31m1.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 28 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m312.3/312.3 kB\u001b[0m \u001b[31m1.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 29 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m8.1/8.1 MB\u001b[0m \u001b[31m1.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 30 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.8/1.8 MB\u001b[0m \u001b[31m1.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 31 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.9/1.9 MB\u001b[0m \u001b[31m902.6 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 32 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m299.3/299.3 kB\u001b[0m \u001b[31m788.9 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 33 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m116.4/116.4 kB\u001b[0m \u001b[31m959.8 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 34 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m75.6/75.6 kB\u001b[0m \u001b[31m1.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 35 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m207.3/207.3 kB\u001b[0m \u001b[31m1.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 36 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m6.9/6.9 MB\u001b[0m \u001b[31m1.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 37 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m83.0/83.0 kB\u001b[0m \u001b[31m648.6 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 38 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m49.4/49.4 kB\u001b[0m \u001b[31m601.8 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 39 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m62.7/62.7 kB\u001b[0m \u001b[31m500.1 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 40 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━��━━━\u001b[0m \u001b[32m77.9/77.9 kB\u001b[0m \u001b[31m473.3 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 41 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m58.3/58.3 kB\u001b[0m \u001b[31m556.6 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 42 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m53.0/53.0 kB\u001b[0m \u001b[31m573.6 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 43 |
+
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m141.1/141.1 kB\u001b[0m \u001b[31m668.0 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
|
| 44 |
+
"\u001b[?25h Building wheel for openai-whisper (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n"
|
| 45 |
+
]
|
| 46 |
+
}
|
| 47 |
+
]
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"cell_type": "code",
|
| 51 |
+
"execution_count": 2,
|
| 52 |
+
"metadata": {
|
| 53 |
+
"colab": {
|
| 54 |
+
"base_uri": "https://localhost:8080/"
|
| 55 |
+
},
|
| 56 |
+
"id": "R1QTyYcpIJuw",
|
| 57 |
+
"outputId": "6060c0f3-621e-43ba-823d-676256cb406a"
|
| 58 |
+
},
|
| 59 |
+
"outputs": [
|
| 60 |
+
{
|
| 61 |
+
"output_type": "stream",
|
| 62 |
+
"name": "stdout",
|
| 63 |
+
"text": [
|
| 64 |
+
"Writing app.py\n"
|
| 65 |
+
]
|
| 66 |
+
}
|
| 67 |
+
],
|
| 68 |
+
"source": [
|
| 69 |
+
"%%writefile app.py\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"import os\n",
|
| 72 |
+
"import re\n",
|
| 73 |
+
"import streamlit as st\n",
|
| 74 |
+
"import transformers\n",
|
| 75 |
+
"from transformers import pipeline\n",
|
| 76 |
+
"from transformers import AutoTokenizer\n",
|
| 77 |
+
"import nltk\n",
|
| 78 |
+
"from PIL import Image\n",
|
| 79 |
+
"import torch\n",
|
| 80 |
+
"import ffmpeg\n",
|
| 81 |
+
"import speech_recognition as sr\n",
|
| 82 |
+
"from pytube import YouTube\n",
|
| 83 |
+
"import string\n",
|
| 84 |
+
"import whisper\n",
|
| 85 |
+
"from moviepy.editor import AudioFileClip\n",
|
| 86 |
+
"from langchain.text_splitter import CharacterTextSplitter\n",
|
| 87 |
+
"from langchain_core.messages import AIMessage, HumanMessage, SystemMessage\n",
|
| 88 |
+
"from langchain.embeddings import OpenAIEmbeddings\n",
|
| 89 |
+
"from langchain.vectorstores import FAISS\n",
|
| 90 |
+
"from langchain.chat_models import ChatOpenAI\n",
|
| 91 |
+
"from langchain.memory import ConversationBufferWindowMemory\n",
|
| 92 |
+
"from langchain.chains import ConversationalRetrievalChain\n",
|
| 93 |
+
"from langchain.callbacks import get_openai_callback\n",
|
| 94 |
+
"from key import openai_api_key\n",
|
| 95 |
+
"from langchain import PromptTemplate\n",
|
| 96 |
+
"from langchain import LLMChain\n",
|
| 97 |
+
"os.environ['OPENAI_API_KEY'] = openai_api_key\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"\n",
|
| 100 |
+
" # Criando a função que corta o texto em chunks:\n",
|
| 101 |
+
"def get_chunks(texto_transcrito):\n",
|
| 102 |
+
" \"\"\"Função que recebe uma string (um texto transcrito) e devolve\n",
|
| 103 |
+
" uma lista de strings, em que cada string (\"chunk\") contém um\n",
|
| 104 |
+
" tamanho específico, com overlap entre os pedaços. \"\"\"\n",
|
| 105 |
+
" text_splitter=CharacterTextSplitter(separator='.', chunk_size=1000, chunk_overlap=100, length_function=len)\n",
|
| 106 |
+
" chunks = text_splitter.split_text(texto_transcrito)\n",
|
| 107 |
+
" return chunks\n",
|
| 108 |
+
"\n",
|
| 109 |
+
" # Criando a função de vectorstore para transformar os chunks de texto em embeddings:\n",
|
| 110 |
+
"def get_vectorstore(chunks):\n",
|
| 111 |
+
" \"\"\"Função que recebe uma lista de chunks de texto e\n",
|
| 112 |
+
" os converte em embeddings (representações numéricas)\n",
|
| 113 |
+
" usando um modelo de embeddings pré-treinado. \"\"\"\n",
|
| 114 |
+
" embeddings = OpenAIEmbeddings()\n",
|
| 115 |
+
" vectorstore = FAISS.from_texts(texts=chunks, embedding=embeddings)\n",
|
| 116 |
+
" return vectorstore\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"\n",
|
| 119 |
+
" # Criando a função para converter o vídeo para o formato adequado:\n",
|
| 120 |
+
"@st.cache_data\n",
|
| 121 |
+
"def convert_mp4_to_wav(mp4_file, wav_file):\n",
|
| 122 |
+
" \"\"\"Função que converte um arquivo de vídeo no formato MP4 para um arquivo de\n",
|
| 123 |
+
" áudio no formato WAV a partir das seguintes entradas: o caminho do arquivo\n",
|
| 124 |
+
" de vídeo no formato MP4 que se deseja converter; o caminho onde o arquivo\n",
|
| 125 |
+
" de áudio WAV resultante será salvo. Nenhuma saída explícita é retornada.\"\"\"\n",
|
| 126 |
+
" video = AudioFileClip(mp4_file)\n",
|
| 127 |
+
" video.write_audiofile(wav_file)\n",
|
| 128 |
+
"\n",
|
| 129 |
+
" # Criando a função que gera a transcrição:\n",
|
| 130 |
+
"@st.cache_data\n",
|
| 131 |
+
"def get_transcriptions(url):\n",
|
| 132 |
+
" \"\"\" Função que recebe um link de um vídeo no YouTube e\n",
|
| 133 |
+
" devolve um dicionário contendo o título do vídeo (key)\n",
|
| 134 |
+
" e a transcrição de seu áudio (value). \"\"\"\n",
|
| 135 |
+
" dicionario = {}\n",
|
| 136 |
+
" # Baixando o áudio:\n",
|
| 137 |
+
" youtube_content = YouTube(url)\n",
|
| 138 |
+
" audio_streams = youtube_content.streams.filter(only_audio=True)\n",
|
| 139 |
+
" audio_streams[0].download()\n",
|
| 140 |
+
" title = youtube_content.title\n",
|
| 141 |
+
" # Convertendo para Wav:\n",
|
| 142 |
+
" mp4_file = '/content/'+''.join(char for char in title if char not in string.punctuation.replace('/', '').replace('-', '').replace('!', '').replace('(', '').replace(')', ''))+'.mp4'\n",
|
| 143 |
+
" wav_file = '/content/'+''.join(char for char in title if char not in string.punctuation.replace('/', '').replace('-', '').replace('!', '').replace('(', '').replace(')', ''))+'.wav'\n",
|
| 144 |
+
" convert_mp4_to_wav(mp4_file, wav_file)\n",
|
| 145 |
+
" # Inicializando o reconhecedor de fala:\n",
|
| 146 |
+
" r = sr.Recognizer()\n",
|
| 147 |
+
" # Carregando o áudio gravado pelo Whisper em um objeto de áudio:\n",
|
| 148 |
+
" with sr.AudioFile(wav_file) as source:\n",
|
| 149 |
+
" audio = r.record(source)\n",
|
| 150 |
+
" # Transcrevendo:\n",
|
| 151 |
+
" texto_transcrito = r.recognize_whisper(audio)\n",
|
| 152 |
+
" # Adicionando ao dicionario:\n",
|
| 153 |
+
" dicionario[title] = texto_transcrito\n",
|
| 154 |
+
" return dicionario\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" # Criando a função que carrega o sumarizador extrativo (para português e inglês) via HuggingFace:\n",
|
| 158 |
+
"@st.cache_resource\n",
|
| 159 |
+
"def load_extractive():\n",
|
| 160 |
+
" \"\"\" Função sem valores de entrada que carrega o modelo\n",
|
| 161 |
+
" de sumarização extrativa via HuggingFace. \"\"\"\n",
|
| 162 |
+
" return pipeline(\"summarization\", model=\"NotXia/longformer-bio-ext-summ\", tokenizer=AutoTokenizer.from_pretrained(\"NotXia/longformer-bio-ext-summ\"), trust_remote_code=True)\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" # Criando a função que gera a sumarização extrativa:\n",
|
| 165 |
+
"@st.cache_data\n",
|
| 166 |
+
"def get_summarization(_model_pipeline, full_text, ratio):\n",
|
| 167 |
+
" \"\"\" Função que recebe um texto completo a ser resumido, juntamente\n",
|
| 168 |
+
" à taxa desejada de sumarização e a pipeline do modelo que fará o\n",
|
| 169 |
+
" sumário, e devolve a versão resumida desse texto. \"\"\"\n",
|
| 170 |
+
" sentences = nltk.sent_tokenize(full_text)\n",
|
| 171 |
+
" extractive_sentences = _model_pipeline({\"sentences\": sentences}, strategy=\"ratio\", strategy_args=ratio)\n",
|
| 172 |
+
" extractive_text = \" \".join(extractive_sentences[0])\n",
|
| 173 |
+
" return extractive_text\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" # Criando a função que gera a tradução do texto a partir do ChatGPT:\n",
|
| 177 |
+
"@st.cache_data\n",
|
| 178 |
+
"def get_translation(summarized_text):\n",
|
| 179 |
+
" \"\"\" Função que recebe um resumo a ser traduzido,\n",
|
| 180 |
+
" juntamente à pipeline do modelo que fará a tradução,\n",
|
| 181 |
+
" e devolve a versão traduzida do texto. \"\"\"\n",
|
| 182 |
+
" LLM = ChatOpenAI(openai_api_key=openai_api_key, temperature=0.25, model_name=\"gpt-3.5-turbo\")\n",
|
| 183 |
+
" messages = [SystemMessage(content='Você é um especialista em traduções de texto do inglês para português'), HumanMessage(content=summarized_text)]\n",
|
| 184 |
+
" translation = LLM(messages)\n",
|
| 185 |
+
" return translation.content\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" # Criando a função que corrige os erros de transcrição do texto a partir do ChatGPT:\n",
|
| 189 |
+
"@st.cache_data\n",
|
| 190 |
+
"def get_correction(transcription):\n",
|
| 191 |
+
" \"\"\" Função que recebe a transcrição (em PT-BR) e corrige eventuais\n",
|
| 192 |
+
" erros do whisper - por exemplo, a troca de palavras que, embora\n",
|
| 193 |
+
" semelhantes na pronúncia, são totalmente absurdas no contexto. \"\"\"\n",
|
| 194 |
+
" correction_prompt = PromptTemplate.from_template(template = 'Você é um especialista em correção de textos. Você receberá uma transcrição de um áudio e deverá substituir as palavras transcritas erroneamente, considerando apenas a pronúncia, por palavras adequadas que façam sentido no contexto do texto. Além disso, corrija questões gramáticais para facilitar a compreensão. Corrija a seguinte transcrição: {transcription}')\n",
|
| 195 |
+
" LLM = ChatOpenAI(openai_api_key=openai_api_key, temperature=0.1, model_name=\"gpt-3.5-turbo\")\n",
|
| 196 |
+
" corrector = LLMChain(prompt=correction_prompt, llm=LLM)\n",
|
| 197 |
+
" with get_openai_callback() as cb:\n",
|
| 198 |
+
" corrected_transcription = corrector.run({\"transcription\": transcription})\n",
|
| 199 |
+
" total_t = cb.total_tokens\n",
|
| 200 |
+
" prompt_t = cb.prompt_tokens\n",
|
| 201 |
+
" completion_t = cb.completion_tokens\n",
|
| 202 |
+
" total_cost = cb.total_cost\n",
|
| 203 |
+
" return corrected_transcription\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" # Criando o chatbot\n",
|
| 207 |
+
"def alan_videos(vectorstore):\n",
|
| 208 |
+
" \"\"\" Função que inicializa e configura um LLM da OpenAI\n",
|
| 209 |
+
" e retorna um chatbot configurado pronto para uso. \"\"\"\n",
|
| 210 |
+
" memory = ConversationBufferWindowMemory(memory_key='chat_history', return_messages=True, k=3)\n",
|
| 211 |
+
" LLM = ChatOpenAI(openai_api_key=openai_api_key, temperature=0.25, model_name=\"gpt-3.5-turbo\")\n",
|
| 212 |
+
" retriever=vectorstore.as_retriever()\n",
|
| 213 |
+
" chatbot = ConversationalRetrievalChain.from_llm(llm=LLM, retriever=retriever, memory=memory)\n",
|
| 214 |
+
" return chatbot\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Criando um modelo de chat:\n",
|
| 217 |
+
"def chat(pergunta):\n",
|
| 218 |
+
" \"\"\" Função que processa uma pergunta utilizando o chatbot\n",
|
| 219 |
+
" configurado (alan_videos) e retorna sua resposta. \"\"\"\n",
|
| 220 |
+
" with get_openai_callback() as cb:\n",
|
| 221 |
+
" resposta = st.session_state.alanvideos.invoke({\"question\": pergunta})\n",
|
| 222 |
+
" total_t = cb.total_tokens\n",
|
| 223 |
+
" prompt_t = cb.prompt_tokens\n",
|
| 224 |
+
" completion_t = cb.completion_tokens\n",
|
| 225 |
+
" total_cost = cb.total_cost\n",
|
| 226 |
+
" return resposta['answer']\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # Criando a função para customização com CSS:\n",
|
| 230 |
+
"def local_css(file_name):\n",
|
| 231 |
+
" \"\"\" Função que carrega um arquivo CSS local e aplica o estilo\n",
|
| 232 |
+
" ao Streamlit app, personalizando a interface do usuário. \"\"\"\n",
|
| 233 |
+
" with open(file_name, \"r\") as f:\n",
|
| 234 |
+
" st.markdown(f\"<style>{f.read()}</style>\", unsafe_allow_html=True)\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" # Configurando a aba do site:\n",
|
| 237 |
+
"icon = Image.open(\"Traçado laranja #f1863d.png\")\n",
|
| 238 |
+
"st.set_page_config(page_title=\"AlanVideos\", page_icon=icon, layout=\"wide\", initial_sidebar_state=\"auto\")\n",
|
| 239 |
+
"\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" # Configurando o site:\n",
|
| 242 |
+
"def main():\n",
|
| 243 |
+
" local_css(\"style.css\")\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" header = st.container()\n",
|
| 246 |
+
" model = st.container()\n",
|
| 247 |
+
" model_1 = st.container()\n",
|
| 248 |
+
" model_2 = st.container()\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" # Configurando a barra lateral:\n",
|
| 251 |
+
" with st.sidebar:\n",
|
| 252 |
+
" with st.form(\"data_collection\"):\n",
|
| 253 |
+
" link = st.text_area(label=\"Coloque o link do seu vídeo do YouTube:\", height=25, placeholder=\"Digite seu link...\")\n",
|
| 254 |
+
" language = st.selectbox('Qual a linguagem do seu vídeo?', ('Português (pt)', 'Inglês (en)'))\n",
|
| 255 |
+
" translate = st.selectbox('Você deseja que o seu vídeo seja traduzido para Português?', ('Não', 'Sim'))\n",
|
| 256 |
+
" compression_rate = st.slider(label=\"Selecione o percentual de sumarização:\", min_value=0.05, max_value=0.50, value=0.25, step=0.05)\n",
|
| 257 |
+
" submitted = st.form_submit_button(\"Enviar\")\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" # Verificando se o link do vídeo é válido:\n",
|
| 260 |
+
" if link != '':\n",
|
| 261 |
+
" if re.match((r'(https?://)?(www\\.)?''(youtube|youtu|youtube-nocookie)\\.(com|be)/''(watch\\?v=|embed/|v/|.+\\?v=)?([^&=%\\?]{11})'), link):\n",
|
| 262 |
+
" st.success('Dados coletados!', icon=\"✅\")\n",
|
| 263 |
+
" else:\n",
|
| 264 |
+
" st.error('Link inválido. Por favor, insira um link do YouTube.', icon=\"🚨\")\n",
|
| 265 |
+
"\n",
|
| 266 |
+
" if \"alanvideos\" not in st.session_state:\n",
|
| 267 |
+
" st.session_state.alanvideos = None\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" # Configurando o cabeçalho:\n",
|
| 270 |
+
" with header:\n",
|
| 271 |
+
" st.title(\":orange[Alan]Chat\")\n",
|
| 272 |
+
" st.subheader(\"Olá, usuário! Este é um projeto que utiliza técnicas de inteligência artificial para simplificar e acelerar a compreensão de conteúdo audiovisual. Por favor, preencha o formulário ao lado para que possamos responder as suas dúvidas a respeito de um vídeo do YouTube! :)\", divider = \"orange\")\n",
|
| 273 |
+
"\n",
|
| 274 |
+
" # Configurando os modelos:\n",
|
| 275 |
+
" with model:\n",
|
| 276 |
+
" if submitted and re.match((r'(https?://)?(www\\.)?''(youtube|youtu|youtube-nocookie)\\.(com|be)/''(watch\\?v=|embed/|v/|.+\\?v=)?([^&=%\\?]{11})'), link):\n",
|
| 277 |
+
" with st.spinner(\"Carregando modelos...\"):\n",
|
| 278 |
+
" nltk.download(\"punkt\")\n",
|
| 279 |
+
" extractive = load_extractive()\n",
|
| 280 |
+
" with st.spinner(\"Transcrevendo texto...\"):\n",
|
| 281 |
+
" transcription = get_transcriptions(link)\n",
|
| 282 |
+
" texto_cru = ''.join(list(transcription.values()))\n",
|
| 283 |
+
" # Preparando o modelo de sumarização após o envio de um link:\n",
|
| 284 |
+
" with model_1:\n",
|
| 285 |
+
" st.header(\"Texto Sumarizado:\")\n",
|
| 286 |
+
" with st.spinner(\"Carregando sumarização...\"):\n",
|
| 287 |
+
" summary = get_summarization(extractive, texto_cru, compression_rate)\n",
|
| 288 |
+
" # Usando o GPT para corrigir a transcrição, caso o vídeo seja em PT-BR:\n",
|
| 289 |
+
" if language == 'Português (pt)':\n",
|
| 290 |
+
" summary = get_correction(summary)\n",
|
| 291 |
+
" # Usando o GPT para traduzir a transcrição para PT-BR, caso o usuário prefira:\n",
|
| 292 |
+
" elif language == 'Inglês (en)' and translate == 'Sim':\n",
|
| 293 |
+
" with st.spinner(\"Traduzindo sumarização...\"):\n",
|
| 294 |
+
" summary = get_translation(summary)\n",
|
| 295 |
+
" st.session_state['summary'] = summary\n",
|
| 296 |
+
" # Preparando o AlanVideos após o envio de um link:\n",
|
| 297 |
+
" with model_2:\n",
|
| 298 |
+
" st.header(\"Resposta das perguntas:\")\n",
|
| 299 |
+
" with st.spinner(\"Preparando AlanVideoss...\"):\n",
|
| 300 |
+
" # Separando o texto em chunks:\n",
|
| 301 |
+
" chunks = get_chunks(texto_cru)\n",
|
| 302 |
+
" # Armazenando os pedaços de texto em embeddings:\n",
|
| 303 |
+
" vectorstore = get_vectorstore(chunks)\n",
|
| 304 |
+
" # Criando o chatbot:\n",
|
| 305 |
+
" st.session_state.alanvideos = alan_videos(vectorstore)\n",
|
| 306 |
+
"\n",
|
| 307 |
+
" # Apresentando os resultados:\n",
|
| 308 |
+
" with model:\n",
|
| 309 |
+
" # Resultado do modelo de sumarização:\n",
|
| 310 |
+
" with model_1:\n",
|
| 311 |
+
" if 'summary' in st.session_state:\n",
|
| 312 |
+
" st.write(st.session_state['summary'])\n",
|
| 313 |
+
" # Resultado do AlanVideos:\n",
|
| 314 |
+
" if 'summary' in st.session_state:\n",
|
| 315 |
+
" if \"chat_history\" not in st.session_state:\n",
|
| 316 |
+
" st.session_state.chat_history = [AIMessage(content=f\"Olá, meu nome é Alan, e estou aqui para responder perguntas sobre o vídeo. Como posso ajudar?\")]\n",
|
| 317 |
+
" pergunta = st.chat_input('Faça uma pergunta sobre o vídeo: ')\n",
|
| 318 |
+
" if pergunta is not None and pergunta != \"\":\n",
|
| 319 |
+
" resposta = chat(pergunta)\n",
|
| 320 |
+
" st.session_state.chat_history.append(HumanMessage(content=pergunta))\n",
|
| 321 |
+
" st.session_state.chat_history.append(AIMessage(content=resposta))\n",
|
| 322 |
+
" for message in st.session_state.chat_history:\n",
|
| 323 |
+
" if isinstance(message, AIMessage):\n",
|
| 324 |
+
" with st.chat_message(\"AI\"):\n",
|
| 325 |
+
" st.write(message.content)\n",
|
| 326 |
+
" elif isinstance(message, HumanMessage):\n",
|
| 327 |
+
" with st.chat_message(\"Human\"):\n",
|
| 328 |
+
" st.write(message.content)\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"main()"
|
| 331 |
+
]
|
| 332 |
+
},
|
| 333 |
+
{
|
| 334 |
+
"cell_type": "code",
|
| 335 |
+
"execution_count": 3,
|
| 336 |
+
"metadata": {
|
| 337 |
+
"colab": {
|
| 338 |
+
"base_uri": "https://localhost:8080/"
|
| 339 |
+
},
|
| 340 |
+
"id": "tPfm2EHyimcF",
|
| 341 |
+
"outputId": "80127d2b-8c4a-4475-bac9-a682fe37ff24"
|
| 342 |
+
},
|
| 343 |
+
"outputs": [
|
| 344 |
+
{
|
| 345 |
+
"output_type": "stream",
|
| 346 |
+
"name": "stdout",
|
| 347 |
+
"text": [
|
| 348 |
+
"34.136.19.61\n"
|
| 349 |
+
]
|
| 350 |
+
}
|
| 351 |
+
],
|
| 352 |
+
"source": [
|
| 353 |
+
"!wget -q -O - ipv4.icanhazip.com"
|
| 354 |
+
]
|
| 355 |
+
},
|
| 356 |
+
{
|
| 357 |
+
"cell_type": "code",
|
| 358 |
+
"execution_count": 4,
|
| 359 |
+
"metadata": {
|
| 360 |
+
"colab": {
|
| 361 |
+
"base_uri": "https://localhost:8080/"
|
| 362 |
+
},
|
| 363 |
+
"id": "dmF1j2csipF8",
|
| 364 |
+
"outputId": "2bc0bbbb-b2f6-4e4b-8e32-5423790888ff"
|
| 365 |
+
},
|
| 366 |
+
"outputs": [
|
| 367 |
+
{
|
| 368 |
+
"output_type": "stream",
|
| 369 |
+
"name": "stdout",
|
| 370 |
+
"text": [
|
| 371 |
+
"\n",
|
| 372 |
+
"Collecting usage statistics. To deactivate, set browser.gatherUsageStats to false.\n",
|
| 373 |
+
"\u001b[0m\n",
|
| 374 |
+
"\u001b[0m\n",
|
| 375 |
+
"\u001b[34m\u001b[1m You can now view your Streamlit app in your browser.\u001b[0m\n",
|
| 376 |
+
"\u001b[0m\n",
|
| 377 |
+
"\u001b[34m Network URL: \u001b[0m\u001b[1mhttp://172.28.0.12:8501\u001b[0m\n",
|
| 378 |
+
"\u001b[34m External URL: \u001b[0m\u001b[1mhttp://34.136.19.61:8501\u001b[0m\n",
|
| 379 |
+
"\u001b[0m\n",
|
| 380 |
+
"\u001b[K\u001b[?25hnpx: installed 22 in 3.639s\n",
|
| 381 |
+
"your url is: https://tangy-heads-feel.loca.lt\n",
|
| 382 |
+
"\u001b[34m Stopping...\u001b[0m\n",
|
| 383 |
+
"^C\n"
|
| 384 |
+
]
|
| 385 |
+
}
|
| 386 |
+
],
|
| 387 |
+
"source": [
|
| 388 |
+
"!streamlit run app.py & npx localtunnel --port 8501"
|
| 389 |
+
]
|
| 390 |
+
}
|
| 391 |
+
],
|
| 392 |
+
"metadata": {
|
| 393 |
+
"accelerator": "GPU",
|
| 394 |
+
"colab": {
|
| 395 |
+
"collapsed_sections": [
|
| 396 |
+
"ETBAYQ66Heo-",
|
| 397 |
+
"h2eI6F54GrDY"
|
| 398 |
+
],
|
| 399 |
+
"gpuType": "T4",
|
| 400 |
+
"provenance": []
|
| 401 |
+
},
|
| 402 |
+
"kernelspec": {
|
| 403 |
+
"display_name": "Python 3",
|
| 404 |
+
"name": "python3"
|
| 405 |
+
},
|
| 406 |
+
"language_info": {
|
| 407 |
+
"name": "python"
|
| 408 |
+
}
|
| 409 |
+
},
|
| 410 |
+
"nbformat": 4,
|
| 411 |
+
"nbformat_minor": 0
|
| 412 |
+
}
|
Tra/303/247ado laranja #f1863d.png
ADDED
|
htmlTemplates.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
css = '''
|
| 2 |
+
<style>
|
| 3 |
+
.chat-message {
|
| 4 |
+
padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex
|
| 5 |
+
}
|
| 6 |
+
.chat-message.user {
|
| 7 |
+
background-color: #2b313e
|
| 8 |
+
}
|
| 9 |
+
.chat-message.bot {
|
| 10 |
+
background-color: #475063
|
| 11 |
+
}
|
| 12 |
+
.chat-message .avatar {
|
| 13 |
+
width: 20%;
|
| 14 |
+
}
|
| 15 |
+
.chat-message .avatar img {
|
| 16 |
+
max-width: 78px;
|
| 17 |
+
max-height: 78px;
|
| 18 |
+
border-radius: 50%;
|
| 19 |
+
object-fit: cover;
|
| 20 |
+
}
|
| 21 |
+
.chat-message .message {
|
| 22 |
+
width: 80%;
|
| 23 |
+
padding: 0 1.5rem;
|
| 24 |
+
color: #fff;
|
| 25 |
+
}
|
| 26 |
+
'''
|
| 27 |
+
|
| 28 |
+
bot_template = '''
|
| 29 |
+
<div class="chat-message bot">
|
| 30 |
+
<div class="avatar">
|
| 31 |
+
<img src="https://w7.pngwing.com/pngs/971/3/png-transparent-alan-turing-the-enigma-bletchley-park-the-imitation-game-alan-turing-law-actor-thumbnail.png" style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;">
|
| 32 |
+
</div>
|
| 33 |
+
<div class="message">{{MSG}}</div>
|
| 34 |
+
</div>
|
| 35 |
+
'''
|
| 36 |
+
|
| 37 |
+
user_template = '''
|
| 38 |
+
<div class="chat-message user">
|
| 39 |
+
<div class="avatar">
|
| 40 |
+
<img src="https://e7.pngegg.com/pngimages/901/543/png-clipart-computer-icons-person-random-icons-miscellaneous-image-file-formats.png">
|
| 41 |
+
</div>
|
| 42 |
+
<div class="message">{{MSG}}</div>
|
| 43 |
+
</div>
|
| 44 |
+
'''
|
requirements.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Bibliotecas de Processamento de Vídeo
|
| 2 |
+
ffmpeg-python
|
| 3 |
+
pytube
|
| 4 |
+
|
| 5 |
+
# Reconhecimento e Processamento de Fala
|
| 6 |
+
git+https://github.com/openai/whisper.git
|
| 7 |
+
SpeechRecognition
|
| 8 |
+
|
| 9 |
+
# Frameworks de Machine Learning e Deep Learning
|
| 10 |
+
torch
|
| 11 |
+
transformers
|
| 12 |
+
|
| 13 |
+
# Indexação de Dados e Busca por Similaridade
|
| 14 |
+
faiss-gpu
|
| 15 |
+
|
| 16 |
+
# Bibliotecas PLN e APIs de IA
|
| 17 |
+
nltk
|
| 18 |
+
langchain
|
| 19 |
+
openai
|
| 20 |
+
|
| 21 |
+
# Framework de Aplicação Web
|
| 22 |
+
streamlit
|
style.css
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Customize the colors for interactive Streamlit elements */
|
| 2 |
+
.stButton>button {
|
| 3 |
+
background-color: #f1863d; /* Orange background for buttons */
|
| 4 |
+
color: #ededf5;
|
| 5 |
+
}
|
| 6 |
+
|
| 7 |
+
.stTextInput>div>div>input {
|
| 8 |
+
background-color: #ededf5;
|
| 9 |
+
color: #383838; /* Dark text for contrast */
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
h1.changa-title {
|
| 13 |
+
font-family: "Changa", sans-serif;
|
| 14 |
+
font-weight: 700; /* Bold weight */
|
| 15 |
+
font-style: normal;
|
| 16 |
+
color: #ededf5 !important; /* Ensure the color applies overriding default */
|
| 17 |
+
}
|