File size: 3,516 Bytes
377f826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""

Data Scientist.: Dr.Eddy Giusepe Chirinos Isidro



Neste script é um pouco mais complexo, usamos a Function Calling para

receber um Resumo, logo extrai os Pontos Importantes e logo extraí as Palavras-Chaves

"""
import openai
import json
from termcolor import colored

import logging
logging.basicConfig(level=logging.INFO)

#Substitua sua chave de API OpenAI:
import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key  = os.environ['OPENAI_API_KEY']

model = "gpt-3.5-turbo-16k-0613" # model = "gpt-4-0613"

def summarize_text(text, model):
    response = openai.ChatCompletion.create(
        model = model,
        messages = [
            {"role": "user", "content": f"Resumir: {text}"},
        ],
        stream = True,
        functions = [
            {
                "name": "resumir_documento",
                "description": "Resume um documento retornando um resumo, uma lista python de pontos importantes e uma lista python de palavras-chave",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "summary": {
                            "type": "string",
                            "description": "um breve resumo do documento e que tenha como máximo 30 palavras."
                        },
                        "important_points": {
                            "type": "array",
                            "items": {
                                "type": "string",
                                "description": "uma lista em python de pontos importantes do documento."
                            }
                        },
                        "keywords": {
                            "type": "array",
                            "items": {
                                "type": "string",
                                "description": "uma lista python de palavras-chave no documento."
                            }
                        }
                    },
                    "required": ["summary", "important_points", "keywords"]
                }
            }
        ],
        function_call = {"name": "resumir_documento"} # Pode ser "auto" or "none"
    )

    responses = ''
    for chunk in response:
        # print(chunk)
        if chunk["choices"][0]["delta"].get("function_call"):
            chunk = chunk["choices"][0]["delta"]
            # print(chunk)
            token = chunk["function_call"]["arguments"]
            responses += token # Anexamos cada Token ao 'responses'
            print(colored(token, "green"), end='', flush=True)

    # Atribuímos todos os argumentos às variáveis:
    summary, important_points, keywords = json.loads(responses).values()

    return summary, important_points, keywords

# Lendo o conteúdo de sample.txt:
with open('sample.txt', 'r', encoding="utf-8", errors="ignore") as file:
    sample = file.read().replace('\n', '')

summary, important_points, keywords = summarize_text(sample, model)

print("\n")
logging.info(" 🤗 Printamos o Resumo:")
print(colored(f"Summary: {summary}", "blue"))

print("\n")
logging.info(" 🤗🤗 Printamos os Pontos Importantes:") 
print(colored(f"Important Points: {important_points}", "yellow"))

print("\n")
logging.info("🤗🤗🤗 Printamos as Palavras Chave:")
print(colored(f"Keywords: {keywords}", "magenta"))