Luigi commited on
Commit
299bf2b
·
1 Parent(s): 228a065

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

Files changed (1) hide show
  1. src/summarization.py +50 -50
src/summarization.py CHANGED
@@ -1,11 +1,11 @@
1
  # summarization.py
2
  """
3
- Module de résumé de transcript avec LLM.
4
- Fournit une fonction robuste pour résumer des textes longs en utilisant
5
- un chunking intelligent et des modèles de langage locaux.
6
 
7
- Version hybride : utilise LangChain pour le text splitting et les prompts,
8
- mais llama_cpp directement pour les appels LLM (plus performant).
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
- # Détection des cœurs logiques disponibles
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 et retourne le modèle LLM"""
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
- """Crée un splitter de texte avec des séparateurs intelligents"""
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 pour résumer un chunk individuel"""
51
- template = """Résumez cette partie du transcript en gardant les points clés et les informations importantes.
52
 
53
  Transcript:
54
  {text}
55
 
56
- Résumé concis:"""
57
  return PromptTemplate(template=template, input_variables=["text"])
58
 
59
 
60
  def create_final_summary_prompt() -> PromptTemplate:
61
- """Prompt pour créer le résumé final à partir des résumés partiels"""
62
- template = """Voici les résumés des différentes parties d'un transcript.
63
- Créez un résumé cohérent et synthétique de l'ensemble.
64
 
65
  {user_prompt}
66
 
67
- Résumés partiels:
68
  {partial_summaries}
69
 
70
- Résumé final:"""
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
- """Résume un chunk individuel en utilisant LangChain pour le prompt"""
79
  try:
80
- # Utilise LangChain pour formater le prompt
81
  formatted_prompt = prompt_template.format(text=text)
82
 
83
  response = llm.create_chat_completion(
84
  messages=[
85
- {"role": "system", "content": "Vous êtes un expert en résumé de transcript. Produisez des résumés clairs, concis et pertinents."},
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"Erreur lors du résumé du chunk: {e}")
94
- return f"[Erreur de résumé: {str(e)}]"
95
 
96
 
97
  def summarize_transcript_langchain(transcript: str, selected_gguf_model: str, prompt_input: str) -> Iterator[str]:
98
  """
99
- Version hybride LangChain + llama_cpp du résumé de transcript.
100
 
101
- Avantages de LangChain utilisés :
102
- - RecursiveCharacterTextSplitter : chunking intelligent avec séparateurs naturels
103
- - PromptTemplate : gestion propre des templates de prompts
104
- - Code plus lisible et maintenable
105
 
106
- Garde llama_cpp pour les appels LLM (meilleures performances).
107
  """
108
  if not transcript or not transcript.strip():
109
- yield "Le transcript est vide."
110
  return
111
 
112
  try:
113
- # Initialisation des composants
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
- # Estimation des tokens
120
  transcript_tokens = len(llm.tokenize(transcript.encode('utf-8')))
121
 
122
- # Résumé direct si le texte est court
123
  if transcript_tokens <= 2000:
124
- print(f"[summarize_transcript] Résumé direct: {transcript_tokens} tokens")
125
 
126
- # Streaming direct avec llama_cpp
127
  stream = llm.create_chat_completion(
128
  messages=[
129
- {"role": "system", "content": "Vous êtes un expert en résumé de transcript. Produisez des résumés clairs, concis et pertinents."},
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 avec LangChain pour les textes longs
144
  chunks = text_splitter.split_text(transcript)
145
- print(f"[summarize_transcript] Texte divisé en {len(chunks)} chunks")
146
 
147
- # Résumé de chaque chunk
148
  partial_summaries = []
149
  for i, chunk in enumerate(chunks, 1):
150
- print(f"Résumé du chunk {i}/{len(chunks)}")
151
  summary = summarize_chunk(llm, chunk, chunk_prompt)
152
  partial_summaries.append(summary)
153
 
154
- # Combinaison et résumé final
155
  combined_summaries = "\n\n".join(partial_summaries)
156
 
157
- # Vérification de la taille de la combinaison
158
  combined_tokens = len(llm.tokenize(combined_summaries.encode('utf-8')))
159
 
160
- if combined_tokens <= 3500: # Laisser de la marge
161
- print(f"[summarize_transcript] Résumé final des {len(partial_summaries)} résumés partiels")
162
 
163
- # Utilise LangChain pour formater le prompt final
164
  final_prompt_formatted = final_prompt.format(
165
  user_prompt=prompt_input,
166
  partial_summaries=combined_summaries
167
  )
168
 
169
- # Streaming avec llama_cpp
170
  stream = llm.create_chat_completion(
171
  messages=[
172
- {"role": "system", "content": "Vous êtes un expert en résumé de transcript. Produisez des résumés clairs, concis et pertinents."},
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] Combinaison trop longue ({combined_tokens} tokens), résumé simplifié")
186
- # Fallback : résumé direct de la combinaison
187
  stream = llm.create_chat_completion(
188
  messages=[
189
- {"role": "system", "content": "Vous êtes un expert en résumé de transcript. Produisez des résumés clairs, concis et pertinents."},
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"Erreur générale lors du résumé: {e}")
204
- yield f"[Erreur lors du résumé: {str(e)}]"
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é