From 1ccbc1d985a4b5b6b761465584d4945adf364ef8 Mon Sep 17 00:00:00 2001 From: flt6 <1404262047@qq.com> Date: Tue, 6 May 2025 22:36:39 +0800 Subject: [PATCH] conversation --- conversation_trans/main.py | 85 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 conversation_trans/main.py diff --git a/conversation_trans/main.py b/conversation_trans/main.py new file mode 100644 index 0000000..02a19fe --- /dev/null +++ b/conversation_trans/main.py @@ -0,0 +1,85 @@ +from json import loads +from typing import Literal +from re import sub + +data = loads(r'''''') + + +class Msg: + id:int + par:int + role:Literal["SYSTEM","USER","ASSISTANT"] + thinking_time:float + thinking_content:str + content:str + time:float + + def __init__(self,msg:dict): + if msg is None: + self.time=0 + return + print(msg) + self.id=msg["id"] + if msg["metadata"]["is_visually_hidden_from_conversation"]: + self.par=0 + self.time=msg["create_time"] + return + self.par=msg["metadata"]["parent_id"] + self.role=msg["author"]["role"] + # self.thinking_time=sub(r"\\[\(\)]","$",msg["thinking_elapsed_secs"]) + # self.thinking_content=sub(r"\\[\[\]]","$$",msg["thinking_content"]) + self.content=msg["content"]["parts"][0] + self.time=msg["create_time"] + + if self.par==None:self.par=0 + +inp = data["messages"] +# inp = data["data"]["biz_data"]["chat_messages"] +msgs:list[Msg]=[Msg(None)] + +child:list[list[Msg]]=[[] for _ in range(len(inp)+1)] + +new=Msg(None) + +for smsg in inp: + msg = Msg(smsg) + msgs.append(msg) + child[msg.par].append(msg) + if msg.time>new.time: + new=msg + +que=[0] +path=[] +def dfs(x:int): + path.append(x) + if new.id==x: + return True + for msg in child[x]: + if dfs(msg.id): return True + path.pop() + + +if not dfs(0): + raise RuntimeError("Cannot find latest node in tree.") + +path.pop(0) +title = "Conversation" +# title = data['data']['biz_data']['chat_session']['title'] +out=[f"# {title}"] +for i in path: + resp=[] + msg:Msg = msgs[i] + resp.append(f"## {msg.role.capitalize()}") + if msg.thinking_time is not None: + resp.append(f"> thinking for {msg.thinking_time}s") + resp.extend(map("> {}".format,msg.thinking_content.splitlines())) + resp.append(msg.content) + out.append("\n".join(resp)) + +try: + with open(f"{title}.md","w",encoding="utf-8") as f: + f.write("\n\n".join(out)) +except IOError or OSError: + with open(f"out.md","w",encoding="utf-8") as f: + f.write("\n\n".join(out)) + \ No newline at end of file