Advertisement
Chrisdbhr

Summary SRT files in folder

Oct 28th, 2024
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.39 KB | Software | 0 0
  1. import os
  2. from llama_cpp import Llama
  3. import tkinter as tk
  4. from tkinter import filedialog
  5.  
  6. # Carrega o modelo em formato GGUF
  7. model_path = "C:/Users/Chris/.cache/lm-studio/models/hugging-quants/Llama-3.2-3B-Instruct-Q8_0-GGUF/llama-3.2-3b-instruct-q8_0.gguf"
  8. llm = Llama(model_path=model_path)
  9.  
  10. def summarize_text(text, chunk_size=130):
  11.     # Divide o texto em blocos de chunk_size palavras para evitar o limite de contexto
  12.     words = text.split()
  13.     summaries = []
  14.    
  15.     for i in range(0, len(words), chunk_size):
  16.         chunk = " ".join(words[i:i + chunk_size])
  17.         output = llm(chunk, max_tokens=100)  # Limite de tokens para o resumo
  18.         summaries.append(output["choices"][0]["text"].strip())
  19.    
  20.     # Junta os resumos dos blocos
  21.     return " ".join(summaries)
  22.  
  23. def process_folder(folder_path):
  24.     # Caminha recursivamente na pasta
  25.     for root, dirs, files in os.walk(folder_path):
  26.         if "FolderSummary.md" in files:
  27.             continue  # Ignora pastas que já têm um resumo
  28.  
  29.         folder_summary = []
  30.         for file in files:
  31.             if file.endswith(".srt"):
  32.                 file_path = os.path.join(root, file)
  33.                 try:
  34.                     with open(file_path, "r", encoding="utf-8") as f:
  35.                         text = f.read()
  36.                         summary = summarize_text(text)
  37.                         folder_summary.append(f"## {file}\n{summary}\n")
  38.                 except Exception as e:
  39.                     print(f"Ocorreu um erro ao processar o arquivo {file_path}: {e}")
  40.                     continue  # Pula para o próximo arquivo
  41.  
  42.         # Cria o FolderSummary.md com os resumos
  43.         if folder_summary:
  44.             summary_path = os.path.join(root, "FolderSummary.md")
  45.             with open(summary_path, "w", encoding="utf-8") as f:
  46.                 f.write("# Resumo da Pasta\n\n" + "\n".join(folder_summary))
  47.             print(f"Resumo criado em {summary_path}")
  48.  
  49. while True:
  50.     try:
  51.         # Solicita o diretório ao usuário
  52.         root = tk.Tk()
  53.         root.withdraw()
  54.         folder_selected = filedialog.askdirectory(title="Selecione a pasta para sumarizar")
  55.  
  56.         if folder_selected:
  57.             process_folder(folder_selected)
  58.             print("Processamento concluído.")
  59.         else:
  60.             print("Nenhuma pasta foi selecionada.")
  61.        
  62.         # Pergunta se o usuário quer processar outra pasta
  63.         retry = input("Deseja selecionar outra pasta? (s/n): ").strip().lower()
  64.         if retry != 's':
  65.             print("Encerrando o programa.")
  66.             break
  67.     except Exception as e:
  68.         print(f"Ocorreu um erro: {e}")
  69.         retry = input("Deseja tentar novamente? (s/n): ").strip().lower()
  70.         if retry != 's':
  71.             print("Encerrando o programa.")
  72.             break
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement