parent
25e4f1643f
commit
5f530fa0c1
|
|
@ -58,7 +58,7 @@
|
|||
<enum>Qt::ScrollBarAlwaysOn</enum>
|
||||
</property>
|
||||
<property name="editTriggers">
|
||||
<set>QAbstractItemView::AllEditTriggers</set>
|
||||
<set>QAbstractItemView::AnyKeyPressed|QAbstractItemView::DoubleClicked</set>
|
||||
</property>
|
||||
<property name="alternatingRowColors">
|
||||
<bool>true</bool>
|
||||
|
|
|
|||
544
taoseller.py
544
taoseller.py
|
|
@ -44,7 +44,7 @@ from PyQt5.QtCore import pyqtSignal, QObject
|
|||
from PyQt5 import QtCore, QtGui, QtWidgets, uic
|
||||
from PyQt5.QtCore import Qt, QUrl, pyqtSignal, QAbstractTableModel, QTimer, QObject, pyqtSlot, QEvent, QUrl, QTimer
|
||||
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QPixmap, QGuiApplication, QColor, QKeyEvent
|
||||
from PyQt5.QtWidgets import QApplication, QFileDialog, QTableWidgetItem, QLabel, QMainWindow, QTableView, QVBoxLayout, QWidget, QComboBox, QMessageBox, QGraphicsScene, QGraphicsPixmapItem, QDialogButtonBox, QInputDialog, QMessageBox, QTabWidget, QSpinBox
|
||||
from PyQt5.QtWidgets import QStyledItemDelegate, QLineEdit, QApplication, QFileDialog, QTableWidgetItem, QLabel, QMainWindow, QTableView, QVBoxLayout, QWidget, QComboBox, QMessageBox, QGraphicsScene, QGraphicsPixmapItem, QDialogButtonBox, QInputDialog, QMessageBox, QTabWidget, QSpinBox
|
||||
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEnginePage, QWebEngineSettings
|
||||
from PyQt5.QtWebChannel import QWebChannel
|
||||
|
||||
|
|
@ -71,6 +71,21 @@ BASE_PATH = None
|
|||
#msg = self.format(record)
|
||||
#self.appendPlainText.emit(msg)
|
||||
|
||||
|
||||
def update_db(db_name, query, params):
|
||||
""" 데이터베이스 업데이트 공통 메서드 """
|
||||
with sqlite3.connect(db_name) as conn:
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.execute(query, params)
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
print(f"Failed to update database: {e}")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
class CustomSpinBox(QSpinBox):
|
||||
def __init__(self, delta=1000, parent=None):
|
||||
super(CustomSpinBox, self).__init__(parent)
|
||||
|
|
@ -81,13 +96,31 @@ class CustomSpinBox(QSpinBox):
|
|||
# 3자리 숫자마다 콤마를 찍는 로직
|
||||
return "{:,}".format(value)
|
||||
|
||||
class EditDelegate(QStyledItemDelegate):
|
||||
def createEditor(self, parent, option, index):
|
||||
# QLineEdit 위젯을 생성합니다.
|
||||
editor = QLineEdit(parent)
|
||||
# 현재 셀의 데이터를 가져옵니다.
|
||||
current_text = index.data(Qt.DisplayRole)
|
||||
# QLineEdit에 현재 데이터를 설정합니다.
|
||||
editor.setText(current_text)
|
||||
return editor
|
||||
|
||||
def setEditorData(self, editor, index):
|
||||
# editor에 index 위치의 데이터를 설정합니다.
|
||||
text = index.model().data(index, Qt.DisplayRole)
|
||||
editor.setText(str(text))
|
||||
|
||||
|
||||
class PandasModel(QAbstractTableModel):
|
||||
def __init__(self, data):
|
||||
def __init__(self, data, db_file, table_name):
|
||||
super(PandasModel, self).__init__()
|
||||
self._data = data
|
||||
self.selected_cell = None # 선택된 셀 초기값 설정
|
||||
self.sort_order = Qt.AscendingOrder
|
||||
self.sort_column = 0
|
||||
self.db_file = db_file
|
||||
self.table_name = table_name
|
||||
|
||||
def rowCount(self, parent=None):
|
||||
return self._data.shape[0]
|
||||
|
|
@ -143,6 +176,75 @@ class PandasModel(QAbstractTableModel):
|
|||
except Exception as e:
|
||||
print(f"Error sorting data: {e}")
|
||||
|
||||
def setData(self, index, value, role=Qt.EditRole):
|
||||
if not index.isValid():
|
||||
return False
|
||||
if role == Qt.EditRole:
|
||||
row = index.row()
|
||||
col = index.column()
|
||||
current_value = self._data.iloc[row, col]
|
||||
if current_value != value: # 값이 변경되었는지 확인
|
||||
response = QMessageBox.question(None, "값 업데이트", "변경된 값을 DB에 적용할까요?",
|
||||
QMessageBox.Yes | QMessageBox.No)
|
||||
if response == QMessageBox.Yes:
|
||||
column_name = self._data.columns[col]
|
||||
self._data.iloc[row, col] = value # 데이터프레임 업데이트
|
||||
self.dataChanged.emit(index, index, [role]) # 뷰 업데이트 신호
|
||||
self.update_database(row, column_name, value) # 데이터베이스 업데이트
|
||||
return True
|
||||
else:
|
||||
# 변경 사항 무시
|
||||
return False
|
||||
return True
|
||||
return False
|
||||
|
||||
def update_database(self, row, column_name, value):
|
||||
# 데이터베이스 업데이트 로직
|
||||
logger.debug(f"value : {value}")
|
||||
column_num = 0
|
||||
|
||||
logger.debug(f"self.table_name : {self.table_name}")
|
||||
if self.table_name == 'Keywords':
|
||||
column_num = 4
|
||||
elif self.table_name == 'NaverShopping':
|
||||
column_num = 14
|
||||
|
||||
logger.debug(f"self.db_file : {self.db_file}")
|
||||
primary_key = self._data.columns[column_num] # 첫 번째 열을 기본 키로 가정
|
||||
logger.debug(f"primary_key : {primary_key}")
|
||||
primary_key_value = self._data.iloc[row][primary_key]
|
||||
logger.debug(f"primary_key_value : {primary_key_value}")
|
||||
|
||||
query = f"""
|
||||
UPDATE {self.table_name}
|
||||
SET {column_name} = ?
|
||||
WHERE {primary_key} = ?
|
||||
"""
|
||||
connection = sqlite3.connect(self.db_file)
|
||||
logger.debug(f"connection : {connection}")
|
||||
logger.debug(f"query : {query}")
|
||||
cursor = connection.cursor()
|
||||
logger.debug(f"cursor : {cursor}")
|
||||
|
||||
try:
|
||||
# cursor.execute(f"UPDATE {self.table_name} SET {column_name} = ? WHERE {primary_key} = ?", (value, primary_key_value))
|
||||
|
||||
cursor.execute(query, (value, primary_key_value))
|
||||
connection.commit()
|
||||
except Exception as e:
|
||||
connection.rollback()
|
||||
print(f"Failed to update database: {e}")
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
print(f"Updated {column_name} for {primary_key}={primary_key_value} to {value}")
|
||||
|
||||
def flags(self, index):
|
||||
defaultFlags = super(PandasModel, self).flags(index)
|
||||
if index.isValid():
|
||||
return defaultFlags | Qt.ItemIsEditable
|
||||
return defaultFlags
|
||||
|
||||
|
||||
class CustomWebEnginePage(QWebEnginePage):
|
||||
def __init__(self, profile, parent=None, use_mobile=False):
|
||||
|
|
@ -472,50 +574,6 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
QMessageBox.information(self, "알림", "작업이 완료되었습니다.")
|
||||
|
||||
|
||||
def automatch_clicked_ori(self):
|
||||
logger.debug("automatch_clicked")
|
||||
|
||||
item_count =10
|
||||
sort_order = 1
|
||||
logger.debug(f"automatch_item_count : {item_count}, sort_order : {sort_order}")
|
||||
|
||||
# QMessageBox.information(self, "알림", "타오바오 파싱 중 생성되는 크름브라우저를 종료하지 마세요\n 완료 메세지가 생성될때 까지 [로그인요구], [캡차해결] 이외에는 조작하지 마세요")
|
||||
|
||||
automatch(self.db_name, item_count, sort_order)
|
||||
# logger.debug("타오바오 파싱완료. 이미지 저장 시작")
|
||||
# self.on_tao_image_save_btn_clicked()
|
||||
try:
|
||||
self.on_tao_image_save_btn_clicked()
|
||||
logger.debug("타오 이미지 저장 시작")
|
||||
except Exception as e:
|
||||
logger.debug(f"on_tao_image_save_btn_clicked 실행 중 예외 발생: {e}")
|
||||
|
||||
QMessageBox.information(self, "알림", "타오바오 파싱이 완료되었습니다.이미지 저장중입니다.")
|
||||
|
||||
#return
|
||||
|
||||
# def full_automatch_clicked(self):
|
||||
# # on_ns_scraping_clicked 메서드 실행
|
||||
# try:
|
||||
# self.on_ns_scraping_clicked()
|
||||
# except Exception as e:
|
||||
# logger.debug(f"on_ns_scraping_clicked 실행 중 예외 발생: {e}")
|
||||
# # 여기서 필요한 경우 추가적인 예외 처리 코드를 작성할 수 있습니다.
|
||||
|
||||
# # automatch_clicked 메서드 실행
|
||||
# try:
|
||||
# self.automatch_clicked()
|
||||
# except Exception as e:
|
||||
# logger.debug(f"automatch_clicked 실행 중 예외 발생: {e}")
|
||||
# # 여기서 필요한 경우 추가적인 예외 처리 코드를 작성할 수 있습니다.
|
||||
|
||||
# # on_tao_image_save_btn_clicked 메서드 실행
|
||||
# try:
|
||||
# self.on_tao_image_save_btn_clicked()
|
||||
# except Exception as e:
|
||||
# logger.debug(f"on_tao_image_save_btn_clicked 실행 중 예외 발생: {e}")
|
||||
# # 여기서 필요한 경우 추가적인 예외 처리 코드를 작성할 수 있습니다.
|
||||
|
||||
def updatebranchCountState(self):
|
||||
if self.branch_checkBox.isChecked():
|
||||
self.branchCount.setEnabled(True) # 체크박스가 체크되면 QLineEdit 활성화
|
||||
|
|
@ -817,30 +875,6 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
|
||||
self.update_match_count()
|
||||
|
||||
|
||||
def loadTable_ori(self):
|
||||
table_name = self.comboBox.currentText()
|
||||
self.current_table_name = table_name # 현재 테이블 이름 저장
|
||||
|
||||
#if table_name:
|
||||
# conn = sqlite3.connect(self.db_name)
|
||||
# df = pd.read_sql(f"SELECT * FROM {table_name}", conn)
|
||||
# conn.close()
|
||||
# model = PandasModel(df)
|
||||
# self.dbviewer1.setModel(model)
|
||||
|
||||
if table_name:
|
||||
conn = sqlite3.connect(self.db_name)
|
||||
df = pd.read_sql(f"SELECT * FROM {table_name}", conn)
|
||||
conn.close()
|
||||
self.model = PandasModel(df)
|
||||
self.dbviewer1.setModel(self.model)
|
||||
|
||||
# 셀 선택 변경 이벤트 처리
|
||||
self.dbviewer1.selectionModel().selectionChanged.connect(self.cell_selected)
|
||||
|
||||
self.update_match_count()
|
||||
|
||||
|
||||
def cell_selected(self, selected, deselected):
|
||||
if selected.indexes():
|
||||
|
|
@ -1213,41 +1247,14 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
self.loadTableNames()
|
||||
self.update_match_count()
|
||||
|
||||
|
||||
# def loadExistingDb(self):
|
||||
# # 파일 선택 대화상자를 통해 .db 파일 선택
|
||||
# db_file, _ = QFileDialog.getOpenFileName(self, "Open Database", "", "Database Files (*.db)")
|
||||
# if db_file:
|
||||
# self.loadDataFromDb(db_file)
|
||||
# #self.load_data_into_table_NaverShopping(db_file)
|
||||
|
||||
|
||||
def get_query_for_table_ori(self, table_name):
|
||||
# 각 테이블별 다른 쿼리 실행
|
||||
if table_name == "Keywords":
|
||||
return "SELECT keyword, base_category, MatchingUrl, MatchingCat FROM Keywords"
|
||||
elif table_name == "NaverShopping":
|
||||
return "SELECT keyword_id, keyword, delvFee, packingFee, plusFee, MatchingUrl, MatchingCat, productTitle, price, category1Name, category2Name, category3Name, category4Name FROM NaverShopping"
|
||||
elif table_name == "Taobao":
|
||||
# return "SELECT keyword_id, item_name, price, imageSearchUrl, keywordSearchUrl, rank FROM Taobao"
|
||||
return "SELECT * FROM Taobao"
|
||||
elif table_name == "SubKeywords":
|
||||
# return "SELECT keyword_id, relatedTags FROM SubKeywords"
|
||||
return "SELECT * FROM SubKeywords"
|
||||
elif table_name == "Matching":
|
||||
# return "SELECT keyword_id, naver_id, taobao_id, sub_keyword_id FROM Matching"
|
||||
return "SELECT * FROM Matching"
|
||||
else:
|
||||
return "SELECT * FROM " + table_name # 기본값 또는 예외 처리
|
||||
|
||||
def get_query_for_table(self, table_name):
|
||||
queries = {
|
||||
"Keywords": "SELECT keyword, base_category, MatchingUrl, MatchingCat FROM Keywords",
|
||||
"Keywords": "SELECT keyword, base_category, MatchingUrl, MatchingCat, id FROM Keywords",
|
||||
"NaverShopping": "SELECT keyword_id, keyword, delvFee, packingFee, plusFee, MatchingUrl, MatchingCat, productTitle, price, category1Name, category2Name, category3Name, category4Name, localImagePath, id, cat_code, tao_imageUrl FROM NaverShopping",
|
||||
# "Taobao": "SELECT keyword_id, item_name, price, imageSearchUrl, keywordSearchUrl, rank FROM Taobao",
|
||||
"Taobao": "SELECT * FROM Taobao",
|
||||
"SubKeywords": "SELECT keyword_id, relatedTags FROM SubKeywords",
|
||||
"Matching": "SELECT keyword_id, naver_id, taobao_id, sub_keyword_id FROM Matching"
|
||||
"SubKeywords": "SELECT keyword_id, relatedTags, id FROM SubKeywords",
|
||||
"Matching": "SELECT keyword_id, naver_id, taobao_id, sub_keyword_id, id FROM Matching"
|
||||
}
|
||||
# queries = {
|
||||
# "Keywords": "SELECT * FROM Keywords",
|
||||
|
|
@ -1276,38 +1283,16 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
connection.close()
|
||||
|
||||
# PandasModel로 데이터 설정
|
||||
self.model = PandasModel(df)
|
||||
self.model = PandasModel(df, db_file, table_name) # 모델 초기화에 db_file과 table_name 전달
|
||||
self.dbviewer1.setModel(self.model)
|
||||
|
||||
delegate = EditDelegate()
|
||||
self.dbviewer1.setItemDelegate(delegate)
|
||||
|
||||
# 셀 선택 변경 이벤트 연결
|
||||
self.dbviewer1.selectionModel().selectionChanged.connect(self.cell_selected)
|
||||
self.update_match_count()
|
||||
|
||||
|
||||
|
||||
|
||||
def loadDataFromDb_ori3(self, db_file):
|
||||
table_name = self.comboBox.currentText()
|
||||
query = self.get_query_for_table(table_name)
|
||||
|
||||
# 데이터베이스에서 데이터 로드 및 모델 설정
|
||||
connection = sqlite3.connect(db_file)
|
||||
df = pd.read_sql(query, connection)
|
||||
connection.close()
|
||||
|
||||
self.model = PandasModel(df)
|
||||
self.dbviewer1.setModel(self.model)
|
||||
self.model.setHorizontalHeaderLabels(df.columns.values.tolist())
|
||||
self.update_match_count()
|
||||
|
||||
|
||||
def loadTable_ori2(self):
|
||||
table_name = self.comboBox.currentText()
|
||||
self.current_table_name = table_name
|
||||
|
||||
self.loadDataFromDb(self.db_name)
|
||||
self.dbviewer1.selectionModel().selectionChanged.connect(self.cell_selected)
|
||||
|
||||
def loadTable(self):
|
||||
table_name = self.comboBox.currentText()
|
||||
logger.debug(f"loadTable_table_name : {table_name}")
|
||||
|
|
@ -1316,72 +1301,6 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
self.dbviewer1.selectionModel().selectionChanged.connect(self.cell_selected)
|
||||
|
||||
|
||||
def loadDataFromDb_ori2(self, db_file):
|
||||
# 선택된 테이블 이름 가져오기
|
||||
selected_table = self.comboBox.currentText()
|
||||
|
||||
# 데이터베이스 연결
|
||||
connection = sqlite3.connect(db_file)
|
||||
|
||||
# 테이블별로 다른 쿼리 실행
|
||||
if selected_table == "Keywords":
|
||||
query = "SELECT keyword, base_category, MatchingUrl, MatchingCat FROM Keywords"
|
||||
elif selected_table == "NaverShopping":
|
||||
query = "SELECT keyword, delvFee, packingFee, plusFee, MatchingUrl, MatchingCat, productTitle, price, category1Name, category2Name, category3Name, category4Name FROM NaverShopping"
|
||||
elif selected_table == "Taobao":
|
||||
query = "SELECT keyword_id, item_name, price, imageSearchUrl, keywordSearchUrl, rank FROM Taobao"
|
||||
elif selected_table == "SubKeywords":
|
||||
query = "SELECT keyword_id, relatedTags FROM SubKeywords"
|
||||
elif selected_table == "Matching":
|
||||
query = "SELECT keyword_id, naver_id, taobao_id, sub_keyword_id FROM Matching"
|
||||
else:
|
||||
query = "SELECT * FROM " + selected_table # 기본값
|
||||
|
||||
# SQL 쿼리 실행 및 결과 가져오기
|
||||
result = pd.read_sql_query(query, connection)
|
||||
|
||||
# 결과를 QStandardItemModel에 로드
|
||||
model = QStandardItemModel()
|
||||
for row in range(result.shape[0]):
|
||||
for col in range(result.shape[1]):
|
||||
item = QStandardItem(str(result.iloc[row, col]))
|
||||
model.setItem(row, col, item)
|
||||
|
||||
# QTableView 설정
|
||||
self.dbviewer1.setModel(model)
|
||||
self.dbviewer1.setSortingEnabled(True) # 정렬 활성화
|
||||
model.setHorizontalHeaderLabels(result.columns.values.tolist()) # 열 이름 설정
|
||||
|
||||
# 데이터베이스 연결 종료
|
||||
connection.close()
|
||||
self.update_match_count()
|
||||
|
||||
|
||||
|
||||
def loadDataFromDb_ori(self, db_file):
|
||||
# 데이터베이스에서 데이터를 로드하여 QTableView에 표시
|
||||
connection = sqlite3.connect(db_file)
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT * FROM NaverShopping")
|
||||
rows = cursor.fetchall()
|
||||
|
||||
query = "SELECT * FROM NaverShopping" # Keywords 테이블에서 모든 데이터를 선택하는 쿼리문
|
||||
result = pd.read_sql_query(query, connection) # 쿼리문 실행하고 결과를 pandas DataFrame으로 반환
|
||||
|
||||
model = QStandardItemModel()
|
||||
|
||||
for row in range(result.shape[0]): # 각 행에 대해
|
||||
for col in range(result.shape[1]): # 각 열에 대해
|
||||
item = QStandardItem(str(result.iloc[row, col])) # 데이터를 QStandardItem로 변환
|
||||
model.setItem(row, col, item) # 모델에 아이템 설정
|
||||
|
||||
# QTableView 설정
|
||||
self.dbviewer1.setModel(model)
|
||||
model.setHorizontalHeaderLabels(result.columns.values.tolist()) # 열 이름 설정
|
||||
self.dbviewer1.hideColumn(0) # 첫 번째 열(ID 열)을 숨김
|
||||
|
||||
connection.close()
|
||||
self.update_match_count()
|
||||
|
||||
# searchbtn 클릭 이벤트 처리 함수
|
||||
def on_searchbtn_clicked(self):
|
||||
|
|
@ -1716,8 +1635,10 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
conn.commit()
|
||||
conn.close() # DB 연결 종료
|
||||
|
||||
self.model = PandasModel(df)
|
||||
self.dbviewer1.setModel(self.model)
|
||||
# # self.model = PandasModel(df)
|
||||
# self.model = PandasModel(df, self.db_name, table_name) # 모델 초기화에 db_file과 table_name 전달
|
||||
|
||||
# self.dbviewer1.setModel(self.model)
|
||||
|
||||
self.load_data_into_table_NaverShopping()
|
||||
self.update_match_count()
|
||||
|
|
@ -1815,45 +1736,6 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
logger.debug("클립보드에 이미지가 없습니다.")
|
||||
|
||||
|
||||
def load_images_by_keyword_id_ori(self, keyword_id):
|
||||
logger.debug(keyword_id)
|
||||
|
||||
try:
|
||||
conn = sqlite3.connect(self.db_name)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(f"SELECT imageUrl FROM {self.current_table_name} WHERE keyword_id = ? LIMIT 5", (keyword_id,))
|
||||
image_urls = cursor.fetchall()
|
||||
conn.close()
|
||||
logger.debug("이미지URL 로드완료")
|
||||
logger.debug(image_urls)
|
||||
|
||||
self.load_images([url[0] for url in image_urls if url[0]])
|
||||
except sqlite3.OperationalError as e:
|
||||
logger.debug(e)
|
||||
QtWidgets.QMessageBox.warning(self, "오류", "DB의 유효한 테이블을 선택해주세요.")
|
||||
|
||||
def load_images_ori(self, image_urls):
|
||||
self.scene.clear()
|
||||
y_position = 0
|
||||
for url in image_urls:
|
||||
try:
|
||||
response = requests.get(url)
|
||||
if response.status_code == 200:
|
||||
pixmap = QPixmap()
|
||||
if pixmap.loadFromData(response.content):
|
||||
resized_pixmap = pixmap.scaled(150, 150, Qt.KeepAspectRatio, Qt.SmoothTransformation)
|
||||
pixmap_item = QGraphicsPixmapItem(resized_pixmap)
|
||||
pixmap_item.setPos(0, y_position)
|
||||
self.scene.addItem(pixmap_item)
|
||||
|
||||
y_position += resized_pixmap.height() + 10
|
||||
else:
|
||||
logger.debug(f"Cannot load image from data: {url}")
|
||||
else:
|
||||
logger.debug(f"Failed to download image from {url}, Status code: {response.status_code}")
|
||||
except Exception as e:
|
||||
logger.debug(f"Error loading image from {url}: {e}")
|
||||
|
||||
|
||||
def update_url_for_match(self, q):
|
||||
url_str = q
|
||||
|
|
@ -1890,8 +1772,8 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
conn.commit()
|
||||
conn.close() # DB 연결 종료
|
||||
|
||||
self.model = PandasModel(df)
|
||||
self.dbviewer1.setModel(self.model)
|
||||
# self.model = PandasModel(df)
|
||||
# self.dbviewer1.setModel(self.model)
|
||||
|
||||
self.load_data_into_table_NaverShopping()
|
||||
self.update_match_count()
|
||||
|
|
@ -1976,8 +1858,8 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
conn.commit()
|
||||
conn.close() # DB 연결 종료
|
||||
|
||||
self.model = PandasModel(df)
|
||||
self.dbviewer1.setModel(self.model)
|
||||
# self.model = PandasModel(df)
|
||||
# self.dbviewer1.setModel(self.model)
|
||||
|
||||
self.load_data_into_table_NaverShopping()
|
||||
self.update_match_count()
|
||||
|
|
@ -2006,42 +1888,6 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
self.matchCountbox.setText("0") # 또는 적절한 기본값으로 설정
|
||||
|
||||
|
||||
# def on_ns_scraping_clicked_ori(self):
|
||||
|
||||
# QMessageBox.information(self, "알림", "네이버쇼핑 스크래핑 작업이 시작되었습니다.")
|
||||
|
||||
# # DB 연결 및 cursor 생성
|
||||
# self.count_test1 += 1
|
||||
# logger.debug(f"count_test1 = {self.count_test1}")
|
||||
|
||||
# conn = sqlite3.connect(self.db_name) # 이 부분은 self.db_name이 정의되어 있어야 합니다.
|
||||
# cursor = conn.cursor()
|
||||
|
||||
# # Keywords 테이블에서 keyword_id와 keyword 가져오기
|
||||
# cursor.execute("SELECT id, keyword FROM Keywords")
|
||||
# rows = cursor.fetchall()
|
||||
|
||||
# overPrice = self.overPrice.text()
|
||||
# sortcount = self.sortcount.text()
|
||||
|
||||
# for row in rows:
|
||||
# id = row[0]
|
||||
# keyword = row[1]
|
||||
# logger.debug(row[1]) # 각 행의 내용을 출력하여 구조 확인
|
||||
|
||||
# parse_naver_shopping(id, keyword, conn, overPrice, sortcount) # 함수 호출
|
||||
# self.count_test2 += 1
|
||||
# logger.debug(f"count_test2 = {self.count_test2}")
|
||||
|
||||
# # DB 연결 종료
|
||||
# conn.close()
|
||||
|
||||
# self.imageSave()
|
||||
# #self.trans_chinese()
|
||||
|
||||
# self.load_data_into_table_NaverShopping()
|
||||
|
||||
# QMessageBox.information(self, "알림", "스크래핑 완료!")
|
||||
|
||||
def find_naver_code(self, base_categories):
|
||||
Percenty_SS_code_PATH = os.path.join(BASE_PATH, 'Percenty_SS_code.json')
|
||||
|
|
@ -2271,101 +2117,6 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
|
||||
|
||||
|
||||
def on_ns_scraping_clicked_ori(self):
|
||||
|
||||
self.scraping_thread = ScrapingThread()
|
||||
self.scraping_thread.progress_updated.connect(self.update_progress_bar)
|
||||
self.scraping_thread.start()
|
||||
|
||||
QMessageBox.information(self, "알림", "네이버쇼핑 스크래핑 시작!")
|
||||
|
||||
# DB 연결 및 cursor 생성
|
||||
self.count_test1 += 1
|
||||
logger.debug(f"count_test1 = {self.count_test1}")
|
||||
|
||||
conn = sqlite3.connect(self.db_name)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Keywords 테이블에서 keyword_id와 keyword 가져오기
|
||||
cursor.execute("SELECT id, keyword FROM Keywords")
|
||||
rows = cursor.fetchall()
|
||||
|
||||
# ProgressBar 설정
|
||||
self.sc_progressBar.setMaximum(len(rows))
|
||||
self.sc_progressBar.setValue(0)
|
||||
|
||||
overPrice = self.overPrice.text()
|
||||
sortcount = self.sortcount.text()
|
||||
|
||||
for idx, row in enumerate(rows):
|
||||
id = row[0]
|
||||
keyword = row[1]
|
||||
logger.debug(row[1]) # 각 행의 내용을 출력하여 구조 확인
|
||||
|
||||
parse_naver_shopping(id, keyword, conn, overPrice, sortcount) # 함수 호출
|
||||
self.count_test2 += 1
|
||||
logger.debug(f"count_test2 = {self.count_test2}")
|
||||
|
||||
# ProgressBar 업데이트
|
||||
self.sc_progressBar.setValue(idx + 1)
|
||||
|
||||
# DB 연결 종료
|
||||
conn.close()
|
||||
|
||||
self.imageSave()
|
||||
#self.trans_chinese()
|
||||
|
||||
self.load_data_into_table_NaverShopping()
|
||||
|
||||
QMessageBox.information(self, "알림", "스크래핑 완료!")
|
||||
|
||||
def imageSave_ori(self):
|
||||
|
||||
# 이미지 저장 폴더 설정 ('DB이름_save_images')
|
||||
ori_image_save_folder = f"{self.db_name}_save_images"
|
||||
image_save_folder = os.path.join(BASE_PATH, ori_image_save_folder)
|
||||
|
||||
# DB 연결 및 cursor 생성
|
||||
conn = sqlite3.connect(self.db_name) # 이 부분은 self.db_name이 정의되어 있어야 합니다.
|
||||
cursor = conn.cursor()
|
||||
|
||||
# NaverShopping 테이블에서 해당 keyword_id의 imageUrl을 가져옵니다.
|
||||
cursor.execute("SELECT id, keyword, imageUrl FROM NaverShopping")
|
||||
shopping_rows = cursor.fetchall()
|
||||
|
||||
# ProgressBar 설정
|
||||
self.img_progressBar.setMaximum(len(shopping_rows))
|
||||
self.img_progressBar.setValue(0)
|
||||
|
||||
logger.debug(shopping_rows) # 각 행의 내용을 출력하여 구조 확인
|
||||
#for shopping_row in shopping_rows:
|
||||
for idx, shopping_row in enumerate(shopping_rows):
|
||||
id = shopping_row[0]
|
||||
keyword = shopping_row[1]
|
||||
imageUrl = shopping_row[2] # imageUrl 가져오기
|
||||
logger.debug(imageUrl)
|
||||
|
||||
if imageUrl:
|
||||
# 이미지 이름을 'keyword_id'와 고유 번호를 이용하여 생성
|
||||
image_name = f"{keyword}_{id}.jpg"
|
||||
# 이미지 다운로드 및 로컬에 저장
|
||||
local_image_path = self.download_and_save_image(imageUrl, image_save_folder, image_name)
|
||||
logger.debug(local_image_path) # 각 행의 내용을 출력하여 구조 확인
|
||||
|
||||
if local_image_path:
|
||||
# 데이터베이스에 로컬 이미지 경로를 업데이트
|
||||
cursor.execute("UPDATE NaverShopping SET localImagePath = ? WHERE imageUrl = ?", (local_image_path, imageUrl))
|
||||
|
||||
# ProgressBar 업데이트
|
||||
self.img_progressBar.setValue(idx + 1)
|
||||
|
||||
# 데이터베이스 변경 사항을 커밋하고 연결 종료
|
||||
|
||||
# DB 연결 종료
|
||||
conn.commit() # Commit the transaction
|
||||
conn.close()
|
||||
|
||||
|
||||
|
||||
def trans_chinese(self):
|
||||
# 네이버 API 클라이언트 ID 및 시크릿
|
||||
|
|
@ -2382,63 +2133,6 @@ class Ui_Dialog(QtWidgets.QDialog):
|
|||
conn.close()
|
||||
|
||||
|
||||
# def on_ns_scraping_clicked_file(self):
|
||||
|
||||
# # 이미지 저장 폴더 설정 ('DB이름_save_images')
|
||||
# image_save_folder = f"{self.db_name}_save_images"
|
||||
|
||||
# # DB 연결 및 cursor 생성
|
||||
# conn = sqlite3.connect(self.db_name) # 이 부분은 self.db_name이 정의되어 있어야 합니다.
|
||||
# cursor = conn.cursor()
|
||||
|
||||
# # Keywords 테이블에서 id와 keyword를 가져옵니다.
|
||||
# cursor.execute("SELECT id, keyword FROM Keywords")
|
||||
# keyword_rows = cursor.fetchall()
|
||||
# overPrice = self.overPrice.text()
|
||||
# sortcount = self.sortcount.text()
|
||||
|
||||
# for keyword_row in keyword_rows:
|
||||
# keyword_id = keyword_row[0]
|
||||
# keyword = keyword_row[1]
|
||||
|
||||
# # 중국어로 번역
|
||||
# #chinese_keyword = self.translate_with_papago(keyword)
|
||||
# # 중국어 키워드를 DB에 저장
|
||||
# #cursor.execute("UPDATE NaverShopping SET chinese_keyword = ? WHERE id = ?", (chinese_keyword, keyword_id))
|
||||
|
||||
# parse_naver_shopping(keyword_id, keyword, conn, overPrice, sortcount) # 함수 호출
|
||||
|
||||
# # NaverShopping 테이블에서 해당 keyword_id의 imageUrl을 가져옵니다.
|
||||
# cursor.execute("SELECT id, imageUrl FROM NaverShopping")
|
||||
# shopping_rows = cursor.fetchall()
|
||||
# logger.debug(shopping_rows) # 각 행의 내용을 출력하여 구조 확인
|
||||
|
||||
# for shopping_row in shopping_rows:
|
||||
# id = shopping_row[0]
|
||||
# imageUrl = shopping_row[1] # imageUrl 가져오기
|
||||
# logger.debug(imageUrl)
|
||||
|
||||
# if imageUrl:
|
||||
# # 이미지 이름을 'keyword_id'와 고유 번호를 이용하여 생성
|
||||
# image_name = f"{keyword}_{keyword_id}.jpg"
|
||||
# # 이미지 다운로드 및 로컬에 저장
|
||||
# local_image_path = self.download_and_save_image(imageUrl, image_save_folder, image_name)
|
||||
# logger.debug(local_image_path) # 각 행의 내용을 출력하여 구조 확인
|
||||
|
||||
# if local_image_path:
|
||||
# # 데이터베이스에 로컬 이미지 경로를 업데이트
|
||||
# cursor.execute("UPDATE NaverShopping SET localImagePath = ? WHERE imageUrl = ?", (local_image_path, imageUrl))
|
||||
|
||||
# # 데이터베이스 변경 사항을 커밋하고 연결 종료
|
||||
|
||||
# # DB 연결 종료
|
||||
# conn.commit() # Commit the transaction
|
||||
# conn.close()
|
||||
|
||||
# self.load_data_into_table_NaverShopping()
|
||||
# self.update_match_count()
|
||||
|
||||
|
||||
|
||||
def update_url(self, q):
|
||||
url_str = q.toString() if hasattr(q, 'toString') else q
|
||||
|
|
|
|||
Loading…
Reference in New Issue