|
| 1 | +""" |
| 2 | +This script summarizes a transcript file by splitting it into manageable chunks, |
| 3 | +summarizing each chunk using the Ollama API, and then combining the summaries into a final summary. |
| 4 | +""" |
| 5 | + |
| 6 | +import os |
| 7 | +import sys |
| 8 | +import ollama |
| 9 | +from transformers import AutoTokenizer |
| 10 | + |
| 11 | +# Log file name |
| 12 | +LOG_FILENAME = "summarized.log" |
| 13 | + |
| 14 | +# Load tokenizer |
| 15 | +tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") |
| 16 | + |
| 17 | +def split_text_by_tokens(text, max_tokens=2000): |
| 18 | + """Splits the input text into chunks that do not exceed the specified token limit.""" |
| 19 | + words = text.split() |
| 20 | + chunks = [] |
| 21 | + current_chunk = [] |
| 22 | + |
| 23 | + # Split the text into words and process them |
| 24 | + for word in words: |
| 25 | + current_chunk.append(word) |
| 26 | + tokens = tokenizer(" ".join(current_chunk))["input_ids"] |
| 27 | + if len(tokens) > max_tokens: |
| 28 | + current_chunk.pop() |
| 29 | + chunks.append(" ".join(current_chunk)) |
| 30 | + current_chunk = [word] |
| 31 | + |
| 32 | + if current_chunk: |
| 33 | + chunks.append(" ".join(current_chunk)) |
| 34 | + |
| 35 | + return chunks |
| 36 | + |
| 37 | +def summarize_chunk(text, model="llama3.1:8b"): |
| 38 | + """Summarizes a chunk of text using the specified Ollama model.""" |
| 39 | + # Ollama prompt |
| 40 | + prompt = ( |
| 41 | + "You are an expert summarizer. Summarize the following transcript into a short list " |
| 42 | + "of the main topics discussed or mentioned. Use only bullet points. " |
| 43 | + "Do not include any pleasantries to the user, or any sort of heading.\n\n" |
| 44 | + f"{text}" |
| 45 | + ) |
| 46 | + |
| 47 | + # Ollama response handler |
| 48 | + response = ollama.chat( |
| 49 | + model=model, |
| 50 | + messages=[ |
| 51 | + {"role": "system", "content": "You summarize transcripts into concise topic overviews."}, |
| 52 | + {"role": "user", "content": prompt} |
| 53 | + ] |
| 54 | + ) |
| 55 | + return response['message']['content'] |
| 56 | + |
| 57 | +def summarize_transcript(full_path, model): |
| 58 | + """Summarizes a single transcript file by splitting |
| 59 | + it into chunks and summarizing each chunk.""" |
| 60 | + with open(full_path, "r", encoding="utf-8") as f: |
| 61 | + transcript = f.read() |
| 62 | + |
| 63 | + # Split transcript into chunks |
| 64 | + print("Splitting transcript into chunks...") |
| 65 | + chunks = split_text_by_tokens(transcript) |
| 66 | + |
| 67 | + print(f"{len(chunks)} chunks created. Summarizing each...") |
| 68 | + |
| 69 | + # Summarize each chunk |
| 70 | + partial_summaries = [] |
| 71 | + for i, chunk in enumerate(chunks): |
| 72 | + print(f"Summarizing chunk {i+1}/{len(chunks)}...") |
| 73 | + summary = summarize_chunk(chunk, model) |
| 74 | + partial_summaries.append(summary) |
| 75 | + |
| 76 | + print("Generating final summary from chunk summaries...") |
| 77 | + |
| 78 | + # Combine partial summaries |
| 79 | + combined_summary = "\n".join(partial_summaries) |
| 80 | + |
| 81 | + # Save result |
| 82 | + base_name = os.path.splitext(full_path)[0] |
| 83 | + base_name = base_name.replace("_transcript", "") |
| 84 | + summary_path_txt = f"{base_name}_summary.txt" |
| 85 | + with open(summary_path_txt, "w", encoding="utf-8") as f: |
| 86 | + f.write(combined_summary) |
| 87 | + summary_path_md = f"{base_name}_summary.md" |
| 88 | + with open(summary_path_md, "w", encoding="utf-8") as f: |
| 89 | + f.write(combined_summary) |
| 90 | + |
| 91 | + print(f"Summary saved to: {summary_path_txt} and {summary_path_md}") |
| 92 | + |
| 93 | +def summarize_transcripts(file_path, model="llama3.1:8b"): |
| 94 | + """Loops through all .txt files in the specified directory, |
| 95 | + skipping already processed files and summary files."""\ |
| 96 | + |
| 97 | + # Create a log file to track processed files |
| 98 | + log_path = os.path.join(file_path, LOG_FILENAME) |
| 99 | + processed_files = set() |
| 100 | + |
| 101 | + # Load already processed files from log |
| 102 | + if os.path.exists(log_path): |
| 103 | + with open(log_path, "r", encoding="utf-8") as log_file: |
| 104 | + processed_files = set(line.strip() for line in log_file if line.strip()) |
| 105 | + |
| 106 | + # Loop through all .txt files in the directory |
| 107 | + for file in os.listdir(file_path): |
| 108 | + full_path = os.path.join(file_path, file) |
| 109 | + # Skip summary files and already processed files |
| 110 | + if file.endswith(".txt") and not file.endswith("_summary.txt") and not file.endswith("corrected.txt") and not file.endswith("_summary.md") and not file.endswith("corrected.md") and file not in processed_files: |
| 111 | + print(f"Processing {file}...") |
| 112 | + summarize_transcript(full_path, model) |
| 113 | + with open(log_path, "a", encoding="utf-8") as log_file: |
| 114 | + log_file.write(file + "\n") |
| 115 | + log_file.flush() |
| 116 | + if file in processed_files: |
| 117 | + print(f"⏭️ Skipping (already summarized): {file}") |
| 118 | + |
| 119 | +# When script is run, summarize all transcripts in the current directory |
| 120 | +if __name__ == "__main__": |
| 121 | + summarize_transcripts(sys.argv[1] if len(sys.argv) > 1 else os.getcwd()) |
0 commit comments