KakaoQuotation/src/chat_ui.py

113 lines
4.5 KiB
Python

from PyQt5.QtWidgets import *
from src.chat_parser import *
from src.database import *
from PyQt5.QtCore import QDate
class MainWindow(QMainWindow):
def __init__(self, db_manager):
super().__init__()
self.db_manager = db_manager # 데이터베이스 매니저 인스턴스 저장
self.initUI()
def initUI(self):
self.setWindowTitle('KakaoTalk Chat Parser')
self.setGeometry(300, 300, 800, 600)
layout = QVBoxLayout()
# 캘린더 및 날짜 선택
self.startDateCalendar = QCalendarWidget()
self.startDateCalendar.setSelectedDate(QDate(2024, 1, 1))
self.endDateCalendar = QCalendarWidget()
self.endDateCalendar.setSelectedDate(QDate.currentDate())
# 채팅 데이터 가져오기 버튼
self.loadChatDataButton = QPushButton('채팅 데이터 가져오기')
self.loadChatDataButton.clicked.connect(self.load_chat_data)
# 채팅 파일 입력 버튼
self.loadChatFileButton = QPushButton('채팅 파일 입력')
self.loadChatFileButton.clicked.connect(self.load_chat_log)
# 사용자 선택 콤보 박스
self.userComboBox = QComboBox()
self.userComboBox.addItem("전체 유저 선택")
# 검색 필드
self.searchField = QLineEdit()
self.searchButton = QPushButton('검색')
self.searchButton.clicked.connect(self.search_chat_data)
# 배치
calendarLayout = QHBoxLayout()
calendarLayout.addWidget(self.startDateCalendar)
calendarLayout.addWidget(self.endDateCalendar)
layout.addLayout(calendarLayout)
layout.addWidget(self.loadChatDataButton)
layout.addWidget(self.userComboBox)
layout.addWidget(self.searchField)
layout.addWidget(self.searchButton)
layout.addWidget(self.loadChatFileButton)
self.textEdit = QTextEdit()
layout.addWidget(self.textEdit)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def load_chat_data(self):
start_date = self.startDateCalendar.selectedDate().toPyDate()
end_date = self.endDateCalendar.selectedDate().toPyDate()
collection_name = "YourCollectionNameHere" # 적절한 컬렉션 이름 사용
documents = self.db_manager.get_documents_by_date_range(collection_name, start_date, end_date)
self.textEdit.clear()
for doc in documents:
self.textEdit.append(f"{doc['datetime']} - {doc['user']}: {doc['message']}")
self.textEdit.append("Chat logs loaded successfully from the database.")
def search_chat_data(self):
text = self.searchField.text()
collection_name = "YourCollectionNameHere" # 적절한 컬렉션 이름 사용
if text.strip():
documents = self.db_manager.search_documents_by_text(collection_name, text)
self.textEdit.clear()
for doc in documents:
self.textEdit.append(f"{doc['datetime']} - {doc['user']}: {doc['message']}")
self.textEdit.append(f"Search results for '{text}':")
else:
self.textEdit.append("Please enter text to search.")
def load_chat_log(self):
options = QFileDialog.Options()
filename, _ = QFileDialog.getOpenFileName(self, "채팅파일 입력", "", "Text Files (*.txt);;All Files (*)", options=options)
if filename:
try:
with open(filename, 'r', encoding='utf-8') as file:
chat_log_contents = file.read()
# Parse the chat log contents
parsed_data = parse_chat_log(chat_log_contents)
if self.db_manager.db is not None: # 데이터베이스 연결 확인
for data in parsed_data:
chatroom_name = data.get('chatroom_name')
if self.db_manager.insert_if_not_exists(chatroom_name, data):
self.textEdit.append(f"{data.get('user')} - {data.get('message')}.")
else:
self.textEdit.append(f"Failed to insert data for chatroom {chatroom_name}.")
self.textEdit.append("All chat logs loaded and parsed successfully.")
else:
self.textEdit.append("Database connection not established.")
except Exception as e:
self.textEdit.append(f"An error occurred: {e}")