Spaces:
Sleeping
Sleeping
| 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 | |