import json import os import re import uuid import streamlit as st import pandas as pd from custom import * import copy import io def get_history_chats(path: str) -> list: if "apikey" in st.secrets: if not os.path.exists(path): os.makedirs(path) files = [f for f in os.listdir(f'./{path}') if f.endswith('.json')] files_with_time = [(f, os.stat(f'./{path}/' + f).st_ctime) for f in files] sorted_files = sorted(files_with_time, key=lambda x: x[1], reverse=True) chat_names = [os.path.splitext(f[0])[0] for f in sorted_files] if len(chat_names) == 0: chat_names.append('New Chat_' + str(uuid.uuid4())) else: chat_names = ['New Chat_' + str(uuid.uuid4())] return chat_names def save_data(path: str, file_name: str, history: list, paras: dict, contexts: dict, **kwargs): if not os.path.exists(path): os.makedirs(path) with open(f"./{path}/{file_name}.json", 'w', encoding='utf-8') as f: json.dump({"history": history, "paras": paras, "contexts": contexts, **kwargs}, f) def remove_data(path: str, chat_name: str): try: os.remove(f"./{path}/{chat_name}.json") except FileNotFoundError: pass # 清除缓存 try: st.session_state.pop('history' + chat_name) for item in ["context_select", "context_input", "context_level", *initial_content_all['paras']]: st.session_state.pop(item + chat_name + "value") except KeyError: pass def load_data(path: str, file_name: str) -> dict: try: with open(f"./{path}/{file_name}.json", 'r', encoding='utf-8') as f: data = json.load(f) return data except FileNotFoundError: content = copy.deepcopy(initial_content_all) if "apikey" in st.secrets: with open(f"./{path}/{file_name}.json", 'w', encoding='utf-8') as f: f.write(json.dumps(content)) return content def show_each_message(message: str, role: str, area=None): if area is None: area = [st.markdown] * 2 if role == 'user': icon = user_svg name = user_name background_color = user_background_color else: icon = gpt_svg name = gpt_name background_color = gpt_background_color message = colon_correction( url_correction(message) ) area[0](f"\n