summryai / summarize_transcription.py
Ramakrushna's picture
AMIT's python files (#1)
e79a00d verified
import os
import logging
from langchain_openai import OpenAI
from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnableSequence
import time
def summarize_text(text):
"""Summarizes the given text using LangChain with OpenAI."""
prompt_template = PromptTemplate(
input_variables=["text"],
template="Please summarize the following text:\n\n{text}"
)
llm = OpenAI(temperature=0.7) # Adjust the temperature for creativity
summarization_chain = RunnableSequence(prompt_template | llm)
max_retries = 3
for attempt in range(max_retries):
try:
summary = summarization_chain.invoke({"text": text})
return summary
except Exception as e:
if 'insufficient_quota' in str(e) and attempt < max_retries - 1:
print(f'Quota exceeded. Retrying in {2 ** attempt} seconds...')
time.sleep(2 ** attempt) # Exponential backoff
else:
logging.error(f'An error occurred: {e}')
raise e
if __name__ == "__main__":
# Ensure the blogs folder exists
if not os.path.exists('blogs'):
os.makedirs('blogs')
# Get the transcription file path from the user
transcription_file_path = input("Enter the path to the transcription file: ")
# Read the transcription text
try:
with open(transcription_file_path, 'r') as file:
transcription_text = file.read()
# Summarize the transcription text
summary = summarize_text(transcription_text)
# Save the summary to a text file in the blogs folder
summary_file_path = os.path.join('blogs', os.path.basename(transcription_file_path).replace('.txt', '_summary.txt'))
with open(summary_file_path, 'w') as summary_file:
summary_file.write(summary)
print(f"Summary saved to: {summary_file_path}")
except Exception as e:
logging.error(f'An error occurred while processing the transcription file: {e}')