Convert summarization.py prompts and comments from French to English
Browse files- Translate all prompt templates to English
- Update system messages in LLM calls to English
- Convert function docstrings and comments to English
- Update error messages and print statements to English
- Maintain all functionality while ensuring English output
- src/summarization.py +50 -50
src/summarization.py
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
# summarization.py
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
"""
|
| 10 |
|
| 11 |
import time
|
|
@@ -18,13 +18,13 @@ from langchain.prompts import PromptTemplate
|
|
| 18 |
|
| 19 |
from .utils import available_gguf_llms, num_vcpus, s2tw_converter
|
| 20 |
|
| 21 |
-
#
|
| 22 |
print(f"Detected vCPUs: {num_vcpus}")
|
| 23 |
|
| 24 |
|
| 25 |
@lru_cache(maxsize=1)
|
| 26 |
def get_llm(selected_gguf_model: str) -> Llama:
|
| 27 |
-
"""Cache
|
| 28 |
repo_id, filename = available_gguf_llms[selected_gguf_model]
|
| 29 |
return Llama.from_pretrained(
|
| 30 |
repo_id=repo_id,
|
|
@@ -37,7 +37,7 @@ def get_llm(selected_gguf_model: str) -> Llama:
|
|
| 37 |
|
| 38 |
|
| 39 |
def create_text_splitter(chunk_size: int = 4000, chunk_overlap: int = 200) -> RecursiveCharacterTextSplitter:
|
| 40 |
-
"""
|
| 41 |
return RecursiveCharacterTextSplitter(
|
| 42 |
chunk_size=chunk_size,
|
| 43 |
chunk_overlap=chunk_overlap,
|
|
@@ -47,27 +47,27 @@ def create_text_splitter(chunk_size: int = 4000, chunk_overlap: int = 200) -> Re
|
|
| 47 |
|
| 48 |
|
| 49 |
def create_chunk_summary_prompt() -> PromptTemplate:
|
| 50 |
-
"""Prompt
|
| 51 |
-
template = """
|
| 52 |
|
| 53 |
Transcript:
|
| 54 |
{text}
|
| 55 |
|
| 56 |
-
|
| 57 |
return PromptTemplate(template=template, input_variables=["text"])
|
| 58 |
|
| 59 |
|
| 60 |
def create_final_summary_prompt() -> PromptTemplate:
|
| 61 |
-
"""Prompt
|
| 62 |
-
template = """
|
| 63 |
-
|
| 64 |
|
| 65 |
{user_prompt}
|
| 66 |
|
| 67 |
-
|
| 68 |
{partial_summaries}
|
| 69 |
|
| 70 |
-
|
| 71 |
return PromptTemplate(
|
| 72 |
template=template,
|
| 73 |
input_variables=["user_prompt", "partial_summaries"]
|
|
@@ -75,14 +75,14 @@ Résumé final:"""
|
|
| 75 |
|
| 76 |
|
| 77 |
def summarize_chunk(llm: Llama, text: str, prompt_template: PromptTemplate) -> str:
|
| 78 |
-
"""
|
| 79 |
try:
|
| 80 |
-
#
|
| 81 |
formatted_prompt = prompt_template.format(text=text)
|
| 82 |
|
| 83 |
response = llm.create_chat_completion(
|
| 84 |
messages=[
|
| 85 |
-
{"role": "system", "content": "
|
| 86 |
{"role": "user", "content": formatted_prompt}
|
| 87 |
],
|
| 88 |
stream=False,
|
|
@@ -90,43 +90,43 @@ def summarize_chunk(llm: Llama, text: str, prompt_template: PromptTemplate) -> s
|
|
| 90 |
summary = response['choices'][0]['message']['content']
|
| 91 |
return s2tw_converter.convert(summary)
|
| 92 |
except Exception as e:
|
| 93 |
-
print(f"
|
| 94 |
-
return f"[
|
| 95 |
|
| 96 |
|
| 97 |
def summarize_transcript_langchain(transcript: str, selected_gguf_model: str, prompt_input: str) -> Iterator[str]:
|
| 98 |
"""
|
| 99 |
-
|
| 100 |
|
| 101 |
-
|
| 102 |
-
- RecursiveCharacterTextSplitter
|
| 103 |
-
- PromptTemplate
|
| 104 |
-
-
|
| 105 |
|
| 106 |
-
|
| 107 |
"""
|
| 108 |
if not transcript or not transcript.strip():
|
| 109 |
-
yield "
|
| 110 |
return
|
| 111 |
|
| 112 |
try:
|
| 113 |
-
#
|
| 114 |
llm = get_llm(selected_gguf_model)
|
| 115 |
text_splitter = create_text_splitter()
|
| 116 |
chunk_prompt = create_chunk_summary_prompt()
|
| 117 |
final_prompt = create_final_summary_prompt()
|
| 118 |
|
| 119 |
-
#
|
| 120 |
transcript_tokens = len(llm.tokenize(transcript.encode('utf-8')))
|
| 121 |
|
| 122 |
-
#
|
| 123 |
if transcript_tokens <= 2000:
|
| 124 |
-
print(f"[summarize_transcript]
|
| 125 |
|
| 126 |
-
#
|
| 127 |
stream = llm.create_chat_completion(
|
| 128 |
messages=[
|
| 129 |
-
{"role": "system", "content": "
|
| 130 |
{"role": "user", "content": f"{prompt_input}\n\n{transcript}"}
|
| 131 |
],
|
| 132 |
stream=True,
|
|
@@ -140,36 +140,36 @@ def summarize_transcript_langchain(transcript: str, selected_gguf_model: str, pr
|
|
| 140 |
yield s2tw_converter.convert(full_response)
|
| 141 |
return
|
| 142 |
|
| 143 |
-
# Chunking
|
| 144 |
chunks = text_splitter.split_text(transcript)
|
| 145 |
-
print(f"[summarize_transcript]
|
| 146 |
|
| 147 |
-
#
|
| 148 |
partial_summaries = []
|
| 149 |
for i, chunk in enumerate(chunks, 1):
|
| 150 |
-
print(f"
|
| 151 |
summary = summarize_chunk(llm, chunk, chunk_prompt)
|
| 152 |
partial_summaries.append(summary)
|
| 153 |
|
| 154 |
-
#
|
| 155 |
combined_summaries = "\n\n".join(partial_summaries)
|
| 156 |
|
| 157 |
-
#
|
| 158 |
combined_tokens = len(llm.tokenize(combined_summaries.encode('utf-8')))
|
| 159 |
|
| 160 |
-
if combined_tokens <= 3500: #
|
| 161 |
-
print(f"[summarize_transcript]
|
| 162 |
|
| 163 |
-
#
|
| 164 |
final_prompt_formatted = final_prompt.format(
|
| 165 |
user_prompt=prompt_input,
|
| 166 |
partial_summaries=combined_summaries
|
| 167 |
)
|
| 168 |
|
| 169 |
-
# Streaming
|
| 170 |
stream = llm.create_chat_completion(
|
| 171 |
messages=[
|
| 172 |
-
{"role": "system", "content": "
|
| 173 |
{"role": "user", "content": final_prompt_formatted}
|
| 174 |
],
|
| 175 |
stream=True,
|
|
@@ -182,11 +182,11 @@ def summarize_transcript_langchain(transcript: str, selected_gguf_model: str, pr
|
|
| 182 |
full_response += delta['content']
|
| 183 |
yield s2tw_converter.convert(full_response)
|
| 184 |
else:
|
| 185 |
-
print(f"[summarize_transcript]
|
| 186 |
-
# Fallback
|
| 187 |
stream = llm.create_chat_completion(
|
| 188 |
messages=[
|
| 189 |
-
{"role": "system", "content": "
|
| 190 |
{"role": "user", "content": f"{prompt_input}\n\n{combined_summaries}"}
|
| 191 |
],
|
| 192 |
stream=True,
|
|
@@ -200,8 +200,8 @@ def summarize_transcript_langchain(transcript: str, selected_gguf_model: str, pr
|
|
| 200 |
yield s2tw_converter.convert(full_response)
|
| 201 |
|
| 202 |
except Exception as e:
|
| 203 |
-
print(f"
|
| 204 |
-
yield f"[
|
| 205 |
|
| 206 |
|
| 207 |
# Alias pour maintenir la compatibilité
|
|
|
|
| 1 |
# summarization.py
|
| 2 |
"""
|
| 3 |
+
Transcript summarization module with LLM.
|
| 4 |
+
Provides a robust function for summarizing long texts using
|
| 5 |
+
intelligent chunking and local language models.
|
| 6 |
|
| 7 |
+
Hybrid version: uses LangChain for text splitting and prompts,
|
| 8 |
+
but llama_cpp directly for LLM calls (better performance).
|
| 9 |
"""
|
| 10 |
|
| 11 |
import time
|
|
|
|
| 18 |
|
| 19 |
from .utils import available_gguf_llms, num_vcpus, s2tw_converter
|
| 20 |
|
| 21 |
+
# Detection of available logical cores
|
| 22 |
print(f"Detected vCPUs: {num_vcpus}")
|
| 23 |
|
| 24 |
|
| 25 |
@lru_cache(maxsize=1)
|
| 26 |
def get_llm(selected_gguf_model: str) -> Llama:
|
| 27 |
+
"""Cache and return the LLM model"""
|
| 28 |
repo_id, filename = available_gguf_llms[selected_gguf_model]
|
| 29 |
return Llama.from_pretrained(
|
| 30 |
repo_id=repo_id,
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def create_text_splitter(chunk_size: int = 4000, chunk_overlap: int = 200) -> RecursiveCharacterTextSplitter:
|
| 40 |
+
"""Create a text splitter with intelligent separators"""
|
| 41 |
return RecursiveCharacterTextSplitter(
|
| 42 |
chunk_size=chunk_size,
|
| 43 |
chunk_overlap=chunk_overlap,
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
def create_chunk_summary_prompt() -> PromptTemplate:
|
| 50 |
+
"""Prompt for summarizing an individual chunk"""
|
| 51 |
+
template = """Summarize this part of the transcript while keeping the key points and important information.
|
| 52 |
|
| 53 |
Transcript:
|
| 54 |
{text}
|
| 55 |
|
| 56 |
+
Concise summary:"""
|
| 57 |
return PromptTemplate(template=template, input_variables=["text"])
|
| 58 |
|
| 59 |
|
| 60 |
def create_final_summary_prompt() -> PromptTemplate:
|
| 61 |
+
"""Prompt for creating the final summary from partial summaries"""
|
| 62 |
+
template = """Here are the summaries of different parts of a transcript.
|
| 63 |
+
Create a coherent and synthetic summary of the whole.
|
| 64 |
|
| 65 |
{user_prompt}
|
| 66 |
|
| 67 |
+
Partial summaries:
|
| 68 |
{partial_summaries}
|
| 69 |
|
| 70 |
+
Final summary:"""
|
| 71 |
return PromptTemplate(
|
| 72 |
template=template,
|
| 73 |
input_variables=["user_prompt", "partial_summaries"]
|
|
|
|
| 75 |
|
| 76 |
|
| 77 |
def summarize_chunk(llm: Llama, text: str, prompt_template: PromptTemplate) -> str:
|
| 78 |
+
"""Summarize an individual chunk using LangChain for the prompt"""
|
| 79 |
try:
|
| 80 |
+
# Use LangChain to format the prompt
|
| 81 |
formatted_prompt = prompt_template.format(text=text)
|
| 82 |
|
| 83 |
response = llm.create_chat_completion(
|
| 84 |
messages=[
|
| 85 |
+
{"role": "system", "content": "You are an expert in transcript summarization. Produce clear, concise, and relevant summaries."},
|
| 86 |
{"role": "user", "content": formatted_prompt}
|
| 87 |
],
|
| 88 |
stream=False,
|
|
|
|
| 90 |
summary = response['choices'][0]['message']['content']
|
| 91 |
return s2tw_converter.convert(summary)
|
| 92 |
except Exception as e:
|
| 93 |
+
print(f"Error during chunk summarization: {e}")
|
| 94 |
+
return f"[Summarization error: {str(e)}]"
|
| 95 |
|
| 96 |
|
| 97 |
def summarize_transcript_langchain(transcript: str, selected_gguf_model: str, prompt_input: str) -> Iterator[str]:
|
| 98 |
"""
|
| 99 |
+
Hybrid LangChain + llama_cpp version of transcript summarization.
|
| 100 |
|
| 101 |
+
LangChain advantages used:
|
| 102 |
+
- RecursiveCharacterTextSplitter: intelligent chunking with natural separators
|
| 103 |
+
- PromptTemplate: clean template management
|
| 104 |
+
- More readable and maintainable code
|
| 105 |
|
| 106 |
+
Keeps llama_cpp for LLM calls (better performance).
|
| 107 |
"""
|
| 108 |
if not transcript or not transcript.strip():
|
| 109 |
+
yield "The transcript is empty."
|
| 110 |
return
|
| 111 |
|
| 112 |
try:
|
| 113 |
+
# Component initialization
|
| 114 |
llm = get_llm(selected_gguf_model)
|
| 115 |
text_splitter = create_text_splitter()
|
| 116 |
chunk_prompt = create_chunk_summary_prompt()
|
| 117 |
final_prompt = create_final_summary_prompt()
|
| 118 |
|
| 119 |
+
# Token estimation
|
| 120 |
transcript_tokens = len(llm.tokenize(transcript.encode('utf-8')))
|
| 121 |
|
| 122 |
+
# Direct summary if text is short
|
| 123 |
if transcript_tokens <= 2000:
|
| 124 |
+
print(f"[summarize_transcript] Direct summary: {transcript_tokens} tokens")
|
| 125 |
|
| 126 |
+
# Direct streaming with llama_cpp
|
| 127 |
stream = llm.create_chat_completion(
|
| 128 |
messages=[
|
| 129 |
+
{"role": "system", "content": "You are an expert in transcript summarization. Produce clear, concise, and relevant summaries."},
|
| 130 |
{"role": "user", "content": f"{prompt_input}\n\n{transcript}"}
|
| 131 |
],
|
| 132 |
stream=True,
|
|
|
|
| 140 |
yield s2tw_converter.convert(full_response)
|
| 141 |
return
|
| 142 |
|
| 143 |
+
# Chunking with LangChain for long texts
|
| 144 |
chunks = text_splitter.split_text(transcript)
|
| 145 |
+
print(f"[summarize_transcript] Text divided into {len(chunks)} chunks")
|
| 146 |
|
| 147 |
+
# Summary of each chunk
|
| 148 |
partial_summaries = []
|
| 149 |
for i, chunk in enumerate(chunks, 1):
|
| 150 |
+
print(f"Summarizing chunk {i}/{len(chunks)}")
|
| 151 |
summary = summarize_chunk(llm, chunk, chunk_prompt)
|
| 152 |
partial_summaries.append(summary)
|
| 153 |
|
| 154 |
+
# Combination and final summary
|
| 155 |
combined_summaries = "\n\n".join(partial_summaries)
|
| 156 |
|
| 157 |
+
# Check combination size
|
| 158 |
combined_tokens = len(llm.tokenize(combined_summaries.encode('utf-8')))
|
| 159 |
|
| 160 |
+
if combined_tokens <= 3500: # Leave some margin
|
| 161 |
+
print(f"[summarize_transcript] Final summary of {len(partial_summaries)} partial summaries")
|
| 162 |
|
| 163 |
+
# Use LangChain to format the final prompt
|
| 164 |
final_prompt_formatted = final_prompt.format(
|
| 165 |
user_prompt=prompt_input,
|
| 166 |
partial_summaries=combined_summaries
|
| 167 |
)
|
| 168 |
|
| 169 |
+
# Streaming with llama_cpp
|
| 170 |
stream = llm.create_chat_completion(
|
| 171 |
messages=[
|
| 172 |
+
{"role": "system", "content": "You are an expert in transcript summarization. Produce clear, concise, and relevant summaries."},
|
| 173 |
{"role": "user", "content": final_prompt_formatted}
|
| 174 |
],
|
| 175 |
stream=True,
|
|
|
|
| 182 |
full_response += delta['content']
|
| 183 |
yield s2tw_converter.convert(full_response)
|
| 184 |
else:
|
| 185 |
+
print(f"[summarize_transcript] Combination too long ({combined_tokens} tokens), simplified summary")
|
| 186 |
+
# Fallback: direct summary of the combination
|
| 187 |
stream = llm.create_chat_completion(
|
| 188 |
messages=[
|
| 189 |
+
{"role": "system", "content": "You are an expert in transcript summarization. Produce clear, concise, and relevant summaries."},
|
| 190 |
{"role": "user", "content": f"{prompt_input}\n\n{combined_summaries}"}
|
| 191 |
],
|
| 192 |
stream=True,
|
|
|
|
| 200 |
yield s2tw_converter.convert(full_response)
|
| 201 |
|
| 202 |
except Exception as e:
|
| 203 |
+
print(f"General error during summarization: {e}")
|
| 204 |
+
yield f"[Error during summarization: {str(e)}]"
|
| 205 |
|
| 206 |
|
| 207 |
# Alias pour maintenir la compatibilité
|