Spaces:
Sleeping
Sleeping
File size: 1,223 Bytes
c998b77 |
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 |
import os
import json
import pandas as pd
from datetime import datetime
# Ensure storage directory exists
CONVERSATION_DIR = "conversations"
os.makedirs(CONVERSATION_DIR, exist_ok=True)
def save_conversation_to_json(user_id, conversation):
"""
Save conversation as a JSON file.
"""
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"{CONVERSATION_DIR}/conversation_{user_id}_{timestamp}.json"
with open(filename, "w") as f:
json.dump({
"user_id": user_id,
"timestamp": timestamp,
"conversation": conversation
}, f, indent=2)
return filename
def save_conversation_to_csv(user_id, conversation):
"""
Save conversation as a CSV file.
"""
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"{CONVERSATION_DIR}/conversation_{user_id}_{timestamp}.csv"
rows = []
for msg in conversation:
rows.append({
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"user_id": user_id,
"role": msg["role"],
"content": msg["content"]
})
df = pd.DataFrame(rows)
df.to_csv(filename, index=False)
return filename
|