File size: 1,971 Bytes
d9814cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import os.path
import datetime
import json
import codecs

# Get the current date
today = datetime.date.today()
# Convert the date to a string using the strftime() method
date_string = today.strftime("%Y-%m-%d")
# Print the date string
print(date_string)


def save_response(input_text, response):
    # Open the responses.txt file using the UTF-8 encoding
    with codecs.open("responses.txt", "a", "utf-8") as file:
        # Write or append text to the file
        response_txt = (
            date_string
            + "\n"
            + "Input: "
            + input_text
            + "\n"
            + "Response: "
            + response.response
            + "\n\nSource:"
            + response.get_formatted_sources()
            + "\n------------------------\n\n"
        )
        file.write(response_txt + "\n")

    # Save as JSON format
    response_json = {
        "date": date_string,
        "input": input_text,
        "response": response.response,
        "source": response.get_formatted_sources(),
    }

    # Check if the responses.json file exists
    if os.path.isfile("responses.json"):
        # Open the existing JSON file in read mode using the UTF-8 encoding
        with codecs.open("responses.json", "r", "utf-8") as f:
            # Load the existing JSON data into memory and parse it
            data = json.load(f)
    else:
        # The file doesn't exist, initialize the data with an empty list
        data = []

    # Append the new JSON object to the existing data
    if isinstance(data, list):
        # The existing data is a list, so we can append to it
        data.append(response_json)
    else:
        # The existing data is not a list, so we create a new list
        data = [data, response_json]

    # Open the JSON file in write mode using the UTF-8 encoding and write the updated data to it
    with open("responses.json", "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False)