Spaces:
Sleeping
Sleeping
File size: 9,492 Bytes
aa04092 |
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
from typing import List, Dict, Optional
from dataclasses import dataclass
from datetime import datetime
import json
from config import Config
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
import os
import pytz
@dataclass
class ChatSession:
id: str
messages: List[Dict[str, str]]
system_prompt: str
model: str
created_at: str
context_summary: Optional[str] = None
context_messages: List[Dict[str, str]] = None
def __post_init__(self):
if self.context_messages is None:
self.context_messages = []
class ChatManager:
def __init__(self):
self.current_session: ChatSession = self._create_new_session()
self.history: List[ChatSession] = []
self._setup_pdf_fonts()
def _setup_pdf_fonts(self):
"""Set up CID fonts for PDF generation with Japanese support"""
try:
# Register the Japanese font
pdfmetrics.registerFont(UnicodeCIDFont('HeiseiMin-W3'))
pdfmetrics.registerFont(UnicodeCIDFont('HeiseiKakuGo-W5'))
except Exception as e:
print(f"Warning: Could not register PDF fonts: {str(e)}")
def _format_datetime(self, dt_str: str, timezone: str = None) -> str:
"""Format datetime string according to the specified timezone"""
if not timezone:
timezone = Config.DEFAULT_TIMEZONE
try:
dt = datetime.strptime(dt_str, "%Y-%m-%d %H:%M:%S")
tz = pytz.timezone(timezone)
local_dt = pytz.utc.localize(dt).astimezone(tz)
return local_dt.strftime("%Y-%m-%d %H:%M:%S %Z")
except Exception as e:
print(f"Error formatting datetime: {str(e)}")
return dt_str
def _create_new_session(self, system_prompt: str = "", model: str = "gpt-4o") -> ChatSession:
return ChatSession(
id=datetime.now().strftime("%Y%m%d_%H%M%S"),
messages=[],
system_prompt=system_prompt,
model=model,
created_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
context_summary=None,
context_messages=[]
)
def new_chat(self, system_prompt: str, model: str) -> None:
if self.current_session.messages:
self.history.append(self.current_session)
if len(self.history) > Config.MAX_HISTORY_CHATS:
self.history.pop(0)
self.current_session = self._create_new_session(system_prompt, model)
def add_message(self, role: str, content: str) -> None:
message = {
"role": role,
"content": content,
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
self.current_session.messages.append(message)
self.current_session.context_messages.append(message)
# Keep only the most recent context window messages
if len(self.current_session.context_messages) > Config.CONTEXT_WINDOW_MESSAGES:
self.current_session.context_messages.pop(0)
def get_messages(self, include_system: bool = True, timezone: str = None) -> List[Dict[str, str]]:
messages = []
if include_system and self.current_session.system_prompt:
messages.append({
"role": "system",
"content": self.current_session.system_prompt
})
# Add context summary if available
if self.current_session.context_summary:
messages.append({
"role": "system",
"content": f"Previous conversation context: {self.current_session.context_summary}"
})
# Add recent context messages with formatted timestamps
for msg in self.current_session.context_messages:
formatted_msg = msg.copy()
if "timestamp" in formatted_msg:
formatted_msg["timestamp"] = self._format_datetime(formatted_msg["timestamp"], timezone)
messages.append(formatted_msg)
return messages
def update_context_summary(self, summary: str) -> None:
"""Update the conversation context summary."""
self.current_session.context_summary = summary
def load_chat(self, session_id: str) -> bool:
for session in self.history:
if session.id == session_id:
self.current_session = session
return True
return False
def clear_current_chat(self) -> None:
self.current_session = self._create_new_session(
self.current_session.system_prompt,
self.current_session.model
)
def export_chat_markdown(self, timezone: str = None) -> str:
"""Export current chat session as Markdown format."""
md_content = []
# Add header with timezone-aware timestamp
created_at = self._format_datetime(self.current_session.created_at, timezone)
md_content.append(f"# Chat Session - {created_at}\n")
md_content.append(f"Model: {self.current_session.model}\n")
# Add system prompt if exists
if self.current_session.system_prompt:
md_content.append("## System Prompt\n")
md_content.append(f"{self.current_session.system_prompt}\n")
# Add context summary if exists
if self.current_session.context_summary:
md_content.append("## Context Summary\n")
md_content.append(f"{self.current_session.context_summary}\n")
# Add messages with timezone-aware timestamps
md_content.append("## Messages\n")
for msg in self.current_session.messages:
role = msg["role"].title()
content = msg["content"].replace("\n", "\n ")
timestamp = self._format_datetime(msg.get("timestamp", ""), timezone)
md_content.append(f"### {role} ({timestamp})\n{content}\n")
return "\n".join(md_content)
def save_markdown_file(self, timezone: str = None) -> str:
"""Save current chat session as Markdown file and return the filename."""
try:
# Create export directory if it doesn't exist
os.makedirs("export", exist_ok=True)
filename = f"export/chat_export_{self.current_session.id}.md"
content = self.export_chat_markdown(timezone)
with open(filename, "w", encoding="utf-8") as f:
f.write(content)
return filename
except Exception as e:
raise Exception(f"Failed to save markdown file: {str(e)}")
def export_chat_pdf(self, timezone: str = None) -> str:
"""Export current chat session as PDF format."""
try:
# Create export directory if it doesn't exist
os.makedirs("export", exist_ok=True)
filename = f"export/chat_export_{self.current_session.id}.pdf"
doc = SimpleDocTemplate(filename, pagesize=A4)
styles = getSampleStyleSheet()
# Create custom styles with Japanese font support
styles.add(ParagraphStyle(
name='JapaneseText',
parent=styles['Normal'],
fontName='HeiseiMin-W3',
fontSize=10,
leading=14
))
styles.add(ParagraphStyle(
name='JapaneseHeading',
parent=styles['Heading1'],
fontName='HeiseiKakuGo-W5',
fontSize=16,
leading=20
))
story = []
# Add header with timezone-aware timestamp
created_at = self._format_datetime(self.current_session.created_at, timezone)
story.append(Paragraph(f"Chat Session - {created_at}", styles['JapaneseHeading']))
story.append(Paragraph(f"Model: {self.current_session.model}", styles['JapaneseText']))
story.append(Spacer(1, 12))
# Add system prompt if exists
if self.current_session.system_prompt:
story.append(Paragraph("System Prompt", styles['JapaneseHeading']))
story.append(Paragraph(self.current_session.system_prompt, styles['JapaneseText']))
story.append(Spacer(1, 12))
# Add context summary if exists
if self.current_session.context_summary:
story.append(Paragraph("Context Summary", styles['JapaneseHeading']))
story.append(Paragraph(self.current_session.context_summary, styles['JapaneseText']))
story.append(Spacer(1, 12))
# Add messages with timezone-aware timestamps
story.append(Paragraph("Messages", styles['JapaneseHeading']))
for msg in self.current_session.messages:
role = msg["role"].title()
content = msg["content"]
timestamp = self._format_datetime(msg.get("timestamp", ""), timezone)
story.append(Paragraph(f"{role} ({timestamp})", styles['JapaneseHeading']))
story.append(Paragraph(content, styles['JapaneseText']))
story.append(Spacer(1, 12))
doc.build(story)
return filename
except Exception as e:
raise Exception(f"Failed to save PDF file: {str(e)}") |