利用 Langchain 和 T5 模型,結合 Streamlit 框架,可以快速搭建一個互動式的檔案摘要與問答系統。系統的核心功能在於能有效處理 PDF 檔案,包含載入、分割、摘要生成與問答。使用者只需上傳 PDF 檔案,系統便能自動生成摘要,並根據使用者提問,從檔案中提取相關資訊。此外,文章更進一步探討如何運用開源大語言模型,結合 Hugging Face API 和 Langchain,實作從 YouTube 影片字幕中提取洞察的功能,包含字幕摘要和問答。透過 Streamlit 框架,使用者可以輕鬆與系統互動,輸入 YouTube 影片連結和問題,系統將自動抓取字幕並提供對應的摘要和答案。

檔案摘要應用程式的開發與實作

本章節將介紹如何使用語言模型(LLM)開發檔案摘要應用程式,特別是針對PDF檔案的摘要功能。我們將結合Langchain函式庫與T5模型來實作這一目標。

PDF問答系統的實作

在前面的章節中,我們已經瞭解如何使用Langchain和OpenAI建立一個PDF問答系統。該系統允許使用者上傳PDF檔案並提出相關問題,系統會根據檔案內容提供答案。

程式碼解析

import streamlit as st
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.document_loaders import PyPDFLoader, DirectoryLoader
from langchain.chains.summarize import load_summarize_chain
from transformers import T5Tokenizer, T5ForConditionalGeneration
from transformers import pipeline
import torch
import base64

# 下載並載入T5模型
tokenizer = T5Tokenizer.from_pretrained("MBZUAI/LaMini-Flan-T5-248M")
base_model = T5ForConditionalGeneration.from_pretrained("MBZUAI/LaMini-Flan-T5-248M")

# 檔案載入與預處理
def preprocess_file(file):
    loader = PyPDFLoader(file)
    pages = loader.load_and_split()
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=50)
    texts = text_splitter.split_documents(pages)
    final_texts = ""
    for text in texts:
        final_texts = final_texts + text.page_content
    return final_texts

# LLM Pipeline
def run_llm_pipeline(filepath):
    pipe_sum = pipeline(
        'summarization',
        model=base_model,
        tokenizer=tokenizer,
        max_length=200,
        min_length=50)
    input_text = preprocess_file(filepath)
    result = pipe_sum(input_text)
    result = result[0]['summary_text']
    return result

#### 內容解密:
此段程式碼主要負責載入T5模型並進行PDF檔案的預處理首先我們下載並載入了T5模型的tokenizer和base_model接著定義了`preprocess_file`函式來載入PDF檔案並將其分割成較小的文字區塊最後,`run_llm_pipeline`函式利用T5模型對輸入的文字進行摘要

### PDF摘要功能的實作
PDF摘要功能允許使用者上傳PDF檔案系統會自動生成檔案的摘要這一功能對於需要快速理解長篇檔案內容的使用者來說非常有用

#### 程式碼解析
```python
@st.cache_data
# 顯示PDF檔案
def display_pdf(file):
    with open(file, "rb") as f:
        base64_pdf = base64.b64encode(f.read()).decode('utf-8')
    pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
    st.markdown(pdf_display, unsafe_allow_html=True)

# Streamlit程式碼
st.set_page_config(layout="wide")

def main():
    st.title("Document Summarization App using Language Model")
    uploaded_file = st.file_uploader("Upload your PDF file", type=['pdf'])
    if uploaded_file is not None:
        if st.button("Summarize"):
            col1, col2 = st.columns(2)
            filepath = "data/" + uploaded_file.name
            with open(filepath, "wb") as temp_file:
                temp_file.write(uploaded_file.read())
            with col1:
                st.info("Uploaded File")
                pdf_view = display_pdf(filepath)
            with col2:
                summary = run_llm_pipeline(filepath)
                st.info("Summarization Complete")
                st.success(summary)

if __name__ == "__main__":
    main()

內容解密:

此段程式碼主要負責實作PDF摘要功能的Streamlit應用。首先,我們定義了display_pdf函式來顯示上傳的PDF檔案。接著,在main函式中,我們設定了Streamlit的頁面組態並實作了檔案上傳功能。當使用者點選“Summarize”按鈕後,系統會呼叫run_llm_pipeline函式生成摘要並顯示結果。

檔案摘要應用程式開發

PDF 檔案預處理

在開發檔案摘要應用程式時,第一步是對上傳的 PDF 檔案進行預處理。以下程式碼展示瞭如何使用 PyPDFLoaderRecursiveCharacterTextSplitter 來載入和分割 PDF 檔案:

def file_preprocessing(file):
    loader = PyPDFLoader(file)
    pages = loader.load_and_split()
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=50)
    texts = text_splitter.split_documents(pages)
    final_texts = ""
    for text in texts:
        final_texts = final_texts + text.page_content
    return final_texts

內容解密:

  1. 使用 PyPDFLoader 載入 PDF 檔案並將其分割成多個頁面。
  2. 建立 RecursiveCharacterTextSplitter 例項,將頁面分割成更小的文字區塊,設定 chunk_size 為 200 個字元,chunk_overlap 為 50 個字元,以確保區塊之間有適當的重疊。
  3. 將分割後的文字區塊合併成一個完整的文字字串 final_texts
  4. 傳回 final_texts,代表 PDF 檔案的完整文字內容。

使用語言模型進行檔案摘要

對 PDF 檔案進行預處理後,可以使用語言模型(LLM)對檔案內容進行摘要。以下程式碼展示瞭如何建立一個摘要流程:

def llm_pipeline(filepath):
    pipe_sum = pipeline(
        'summarization',
        model=base_model,
        tokenizer=tokenizer,
        max_length=200,
        min_length=50)
    input_text = file_preprocessing(filepath)
    result = pipe_sum(input_text)
    result = result[0]['summary_text']
    return result

內容解密:

  1. 使用 Hugging Face 的 pipeline 函式建立一個專門用於文字摘要的流程,指定模型、標記器以及生成摘要的最大和最小長度。
  2. 呼叫 file_preprocessing 函式對 PDF 檔案進行預處理,傳回檔案的完整文字內容。
  3. 使用摘要流程對預處理後的文字進行摘要,結果儲存在 result 變數中。
  4. 從結果中提取實際的摘要文字並傳回。

在 Streamlit 應用程式中顯示 PDF 檔案

為了在 Streamlit 應用程式中顯示上傳的 PDF 檔案,可以使用以下函式:

@st.cache_data
def displayPDF(file):
    with open(file, "rb") as f:
        base64_pdf = base64.b64encode(f.read()).decode('utf-8')
    pdf_display = F'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
    st.markdown(pdf_display, unsafe_allow_html=True)

內容解密:

  1. 讀取 PDF 檔案並使用 Base64 編碼。
  2. 將編碼後的 PDF 檔案嵌入到 HTML iframe 中,以在 Streamlit 介面中渲染。

Streamlit 應用程式主函式

最後,定義 Streamlit 應用程式的主函式:

st.set_page_config(layout="wide")

def main():
    st.title("根據語言模型的檔案摘要應用程式")
    uploaded_file = st.file_uploader("上傳您的 PDF 檔案", type=['pdf'])
    if uploaded_file is not None:
        if st.button("摘要"):
            col1, col2 = st.columns(2)
            filepath = "data/"+uploaded_file.name
            with open(filepath, "wb") as temp_file:
                temp_file.write(uploaded_file.read())
            with col1:
                st.info("已上傳的檔案")
                pdf_view = displayPDF(filepath)
            with col2:
                summary = llm_pipeline(filepath)
                st.info("摘要完成")
                st.success(summary)

if __name__ == "__main__":
    main()

內容解密:

  1. 組態 Streamlit 頁面佈局並定義主函式。
  2. 提供一個檔案上傳器讓使用者上傳 PDF 檔案。
  3. 當使用者點選「摘要」按鈕時,將檔案暫存並在一欄中顯示上傳的檔案內容,同時在另一欄中進行摘要處理。
  4. 將摘要結果顯示在成功訊息中。

您可以透過執行以下命令來執行此應用程式:

streamlit run PDF-Summary-Streamlit.py

並在瀏覽器中存取 http://localhost:8501/ 以檢視 UI。

從影片逐字稿中擷取洞察:應用與實作

在現今的數位時代,從影片逐字稿中擷取洞察已變得越來越有價值。隨著影片內容在各大平台上持續佔據主導地位,企業開始意識到這些影片中隱含的資訊所具有的潛力。影片逐字稿提供了豐富的文字資料,可以用來取得寶貴的洞察並應對關鍵的商業應用場景。

影片逐字稿分析的益處

透過分析影片逐字稿,企業可以獲得多項益處。首先,擷取逐字稿中的洞察可以實作對影片內容的高效、準確索引。企業不再僅依賴手動標記或有限的後設資料,而是可以利用逐字稿中的文字來分類別、搜尋和檢索特定的影片片段。這樣不僅增強了內容的可發現性,也讓使用者能夠快速找到相關資訊,從而改善使用者經驗和參與度。

此外,影片逐字稿為全面的內容分析奠定了基礎。透過運用自然語言處理(NLP)技術,企業可以從逐字稿中提取關鍵概念、情感和主題模式。這種分析有助於識別影片內容中的熱門話題、客戶情感和新興趨勢。這些洞察使企業能夠改進行銷策略,更好地瞭解目標受眾,並根據不斷變化的客戶偏好調整產品或服務。

實作影片逐字稿摘要與問答系統

本文將介紹如何使用Hugging Face上的開源LLMs以及Langchain和OpenAPI函式庫,從影片逐字稿中擷取洞察。首先,我們將使用開源模型和Streamlit應用程式來實作影片字幕摘要和問答功能。

程式碼實作

以下是實作影片字幕摘要和問答系統的程式碼範例:

import streamlit as st
import requests
import urllib.parse
from langchain.document_loaders import YoutubeLoader
import json
import re

# HuggingFace Inference API 端點
SUMMARIZATION_ENDPOINT = "https://api-inference.huggingface.co/models/tiiuae/falcon-7b-instruct"
QA_ENDPOINT = "https://api-inference.huggingface.co/models/gpt2-large"

# Streamlit 應用程式
def main():
    st.title("YouTube 字幕摘要與問答")
    
    # 取得使用者輸入
    url = st.text_input("輸入 YouTube 網址:")
    question = st.text_input("根據字幕提出問題:")
    
    if st.button("摘要與回答"):
        if url:
            # 從 YouTube 網址中提取影片 ID
            video_id = extract_video_id(url)
            print("VIDEO_ID", video_id)
            
            # 取得 YouTube 字幕
            transcript = get_youtube_captions(video_id)
            print("======TRANSCRIPT", transcript)
            
            # 根據逐字稿回答問題
            answer = answer_question(transcript, question)
            print("**********", answer)
            
            # 使用 HuggingFace 模型生成摘要
            summary = generate_summary(transcript)
            print("
---
-
---
--SUMMARY", summary)
            
            # 顯示結果
            st.subheader("摘要:")
            st.write(summary)

#### 內容解密:
此段程式碼主要負責建立一個 Streamlit 應用程式用於從 YouTube 影片中提取字幕並進行摘要和問答首先透過 `extract_video_id` 函式從使用者輸入的 YouTube 網址中提取影片 ID接著使用 `get_youtube_captions` 函式取得該影片的字幕之後程式分別呼叫 `answer_question``generate_summary` 函式來根據字幕回答使用者提出的問題並生成摘要最後將生成的摘要顯示在 Streamlit 應用程式的介面上

#### 程式邏輯解析

1. **使用者輸入處理**程式首先透過 Streamlit 的 `text_input` 功能取得使用者輸入的 YouTube 網址和問題
2. **提取影片 ID**使用 `extract_video_id` 函式從 YouTube 網址中提取影片 ID這是為了後續能夠取得該影片的字幕
3. **取得字幕**呼叫 `get_youtube_captions` 函式傳入影片 ID 以取得對應的字幕內容
4. **問答與摘要生成**分別使用 `answer_question``generate_summary` 函式來根據字幕內容回答使用者問題和生成摘要
5. **結果顯示**最後將生成的摘要顯示在 Streamlit 應用程式的介面上