Spaces:
Runtime error
Runtime error
Update backupapp.py
Browse files- backupapp.py +53 -31
backupapp.py
CHANGED
@@ -3,33 +3,56 @@ import openai
|
|
3 |
import os
|
4 |
import base64
|
5 |
import glob
|
|
|
|
|
|
|
6 |
|
7 |
from datetime import datetime
|
8 |
from openai import ChatCompletion
|
9 |
from xml.etree import ElementTree as ET
|
10 |
from bs4 import BeautifulSoup
|
11 |
|
12 |
-
import json
|
13 |
-
|
14 |
-
# from dotenv import load_dotenv
|
15 |
-
# load_dotenv()
|
16 |
-
|
17 |
openai.api_key = os.getenv('OPENAI_KEY')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
def chat_with_model(prompts):
|
20 |
model = "gpt-3.5-turbo"
|
21 |
-
#model = "gpt-4-32k"
|
22 |
conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
|
23 |
conversation.extend([{'role': 'user', 'content': prompt} for prompt in prompts])
|
24 |
response = openai.ChatCompletion.create(model=model, messages=conversation)
|
25 |
return response['choices'][0]['message']['content']
|
26 |
|
27 |
def generate_filename(prompt):
|
28 |
-
|
29 |
-
safe_date_time = datetime.now().strftime("%m%d_%I_%M_%p")
|
30 |
safe_prompt = "".join(x for x in prompt if x.isalnum())[:30]
|
31 |
return f"{safe_date_time}_{safe_prompt}.txt"
|
32 |
-
|
33 |
def create_file(filename, prompt, response):
|
34 |
with open(filename, 'w') as file:
|
35 |
file.write(f"<h1>Prompt:</h1> <p>{prompt}</p> <h1>Response:</h1> <p>{response}</p>")
|
@@ -67,60 +90,59 @@ def CompressXML(xml_text):
|
|
67 |
for elem in list(root.iter()):
|
68 |
if isinstance(elem.tag, str) and 'Comment' in elem.tag:
|
69 |
elem.parent.remove(elem)
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
def read_file_content(file):
|
75 |
if file.type == "application/json":
|
76 |
content = json.load(file)
|
77 |
return str(content)
|
78 |
-
elif file.type == "text/html":
|
79 |
content = BeautifulSoup(file, "html.parser")
|
80 |
return content.text
|
81 |
elif file.type == "application/xml" or file.type == "text/xml":
|
82 |
tree = ET.parse(file)
|
83 |
root = tree.getroot()
|
84 |
-
|
85 |
-
return
|
86 |
-
|
|
|
|
|
|
|
87 |
elif file.type == "text/plain":
|
88 |
return file.getvalue().decode()
|
89 |
else:
|
90 |
return ""
|
91 |
|
92 |
def main():
|
93 |
-
st.title("Chat with AI")
|
94 |
-
|
95 |
prompts = ['']
|
96 |
-
|
97 |
user_prompt = st.text_area("Your question:", '', height=120)
|
98 |
-
uploaded_file = st.file_uploader("Choose a file", type=["xml", "json", "htm", "txt"])
|
99 |
|
100 |
if user_prompt:
|
101 |
prompts.append(user_prompt)
|
102 |
|
103 |
if uploaded_file is not None:
|
104 |
-
file_content = read_file_content(uploaded_file)
|
105 |
-
st.markdown(f"**Content Added to Prompt:**\n{file_content}")
|
106 |
prompts.append(file_content)
|
107 |
|
108 |
-
if st.button('Chat'):
|
109 |
-
st.write('
|
110 |
response = chat_with_model(prompts)
|
111 |
st.write('Response:')
|
112 |
st.write(response)
|
113 |
-
|
114 |
filename = generate_filename(user_prompt)
|
115 |
create_file(filename, user_prompt, response)
|
116 |
-
|
117 |
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
118 |
-
|
|
|
|
|
|
|
119 |
htm_files = glob.glob("*.txt")
|
120 |
for file in htm_files:
|
121 |
st.sidebar.markdown(get_table_download_link(file), unsafe_allow_html=True)
|
122 |
-
if st.sidebar.button(f"πDelete {file}"):
|
123 |
-
#if st.sidebar.button("π Delete"):
|
124 |
os.remove(file)
|
125 |
st.experimental_rerun()
|
126 |
|
|
|
3 |
import os
|
4 |
import base64
|
5 |
import glob
|
6 |
+
import json
|
7 |
+
import mistune
|
8 |
+
import pytz
|
9 |
|
10 |
from datetime import datetime
|
11 |
from openai import ChatCompletion
|
12 |
from xml.etree import ElementTree as ET
|
13 |
from bs4 import BeautifulSoup
|
14 |
|
|
|
|
|
|
|
|
|
|
|
15 |
openai.api_key = os.getenv('OPENAI_KEY')
|
16 |
+
st.set_page_config(
|
17 |
+
page_title="GPT Streamlit Document Reasoner",
|
18 |
+
layout="wide")
|
19 |
+
# st.title("GPT Chat with Optional File Context - Talk to your data!")
|
20 |
+
|
21 |
+
# Output options sidebar menu
|
22 |
+
# st.sidebar.title("Output Options")
|
23 |
+
menu = ["txt", "htm", "md"]
|
24 |
+
choice = st.sidebar.selectbox("Choose output file type to save results", menu)
|
25 |
+
choicePrefix = "Output and download file set to "
|
26 |
+
if choice == "txt":
|
27 |
+
st.sidebar.write(choicePrefix + "Text file.")
|
28 |
+
elif choice == "htm":
|
29 |
+
st.sidebar.write(choicePrefix + "HTML5.")
|
30 |
+
elif choice == "md":
|
31 |
+
st.sidebar.write(choicePrefix + "Markdown.")
|
32 |
+
elif choice == "py":
|
33 |
+
st.sidebar.write(choicePrefix + "Python AI UI/UX")
|
34 |
+
|
35 |
+
# sidebar slider for file input length to include in inference blocks
|
36 |
+
max_length = st.sidebar.slider("Max document length", min_value=1000, max_value=32000, value=3000, step=1000)
|
37 |
+
|
38 |
+
# Truncate document
|
39 |
+
def truncate_document(document, length):
|
40 |
+
return document[:length]
|
41 |
|
42 |
def chat_with_model(prompts):
|
43 |
model = "gpt-3.5-turbo"
|
44 |
+
#model = "gpt-4-32k" # 32k tokens between prompt and inference tokens
|
45 |
conversation = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
|
46 |
conversation.extend([{'role': 'user', 'content': prompt} for prompt in prompts])
|
47 |
response = openai.ChatCompletion.create(model=model, messages=conversation)
|
48 |
return response['choices'][0]['message']['content']
|
49 |
|
50 |
def generate_filename(prompt):
|
51 |
+
central = pytz.timezone('US/Central')
|
52 |
+
safe_date_time = datetime.now(central).strftime("%m%d_%I_%M_%p")
|
53 |
safe_prompt = "".join(x for x in prompt if x.isalnum())[:30]
|
54 |
return f"{safe_date_time}_{safe_prompt}.txt"
|
55 |
+
|
56 |
def create_file(filename, prompt, response):
|
57 |
with open(filename, 'w') as file:
|
58 |
file.write(f"<h1>Prompt:</h1> <p>{prompt}</p> <h1>Response:</h1> <p>{response}</p>")
|
|
|
90 |
for elem in list(root.iter()):
|
91 |
if isinstance(elem.tag, str) and 'Comment' in elem.tag:
|
92 |
elem.parent.remove(elem)
|
93 |
+
return ET.tostring(root, encoding='unicode', method="xml")
|
94 |
+
|
95 |
+
def read_file_content(file,max_length):
|
|
|
|
|
96 |
if file.type == "application/json":
|
97 |
content = json.load(file)
|
98 |
return str(content)
|
99 |
+
elif file.type == "text/html" or file.type == "text/htm":
|
100 |
content = BeautifulSoup(file, "html.parser")
|
101 |
return content.text
|
102 |
elif file.type == "application/xml" or file.type == "text/xml":
|
103 |
tree = ET.parse(file)
|
104 |
root = tree.getroot()
|
105 |
+
xml = CompressXML(ET.tostring(root, encoding='unicode'))
|
106 |
+
return xml
|
107 |
+
elif file.type == "text/markdown" or file.type == "text/md":
|
108 |
+
md = mistune.create_markdown()
|
109 |
+
content = md(file.read().decode())
|
110 |
+
return content
|
111 |
elif file.type == "text/plain":
|
112 |
return file.getvalue().decode()
|
113 |
else:
|
114 |
return ""
|
115 |
|
116 |
def main():
|
|
|
|
|
117 |
prompts = ['']
|
118 |
+
file_content = ""
|
119 |
user_prompt = st.text_area("Your question:", '', height=120)
|
120 |
+
uploaded_file = st.file_uploader("Choose a file", type=["xml", "json", "html", "htm", "md", "txt"])
|
121 |
|
122 |
if user_prompt:
|
123 |
prompts.append(user_prompt)
|
124 |
|
125 |
if uploaded_file is not None:
|
126 |
+
file_content = read_file_content(uploaded_file, max_length)
|
|
|
127 |
prompts.append(file_content)
|
128 |
|
129 |
+
if st.button('π¬ Chat'):
|
130 |
+
st.write('Thinking and Reasoning with your inputs...')
|
131 |
response = chat_with_model(prompts)
|
132 |
st.write('Response:')
|
133 |
st.write(response)
|
134 |
+
|
135 |
filename = generate_filename(user_prompt)
|
136 |
create_file(filename, user_prompt, response)
|
|
|
137 |
st.sidebar.markdown(get_table_download_link(filename), unsafe_allow_html=True)
|
138 |
+
|
139 |
+
if len(file_content) > 0:
|
140 |
+
st.markdown(f"**File Content Added:**\n{file_content}")
|
141 |
+
|
142 |
htm_files = glob.glob("*.txt")
|
143 |
for file in htm_files:
|
144 |
st.sidebar.markdown(get_table_download_link(file), unsafe_allow_html=True)
|
145 |
+
if st.sidebar.button(f"π Delete {file}"):
|
|
|
146 |
os.remove(file)
|
147 |
st.experimental_rerun()
|
148 |
|