first commit

This commit is contained in:
PinforYou 2025-05-28 14:26:49 +09:00
commit 89dd48a364
2943 changed files with 244316 additions and 0 deletions

8
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

28
.idea/deployment.xml generated Normal file
View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PublishConfigData" remoteFilesAllowedToDisappearOnAutoupload="false">
<serverData>
<paths name="pi@192.168.0.41:22">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="pi@192.168.0.41:22 (2)">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
<paths name="pi@192.168.0.41:22 password">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
</serverData>
</component>
</project>

8
.idea/english_project.iml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.10" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

4
.idea/misc.xml generated Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/english_project.iml" filepath="$PROJECT_DIR$/.idea/english_project.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

BIN
DungGeunMo.ttf Normal file

Binary file not shown.

Binary file not shown.

0
PyAudio Normal file
View File

0
README.md Normal file
View File

100
apa102.py Normal file
View File

@ -0,0 +1,100 @@
import time
import random
from PIL import Image, ImageDraw
from luma.led_matrix.device import max7219
from luma.core.interface.serial import spi, noop
# SPI 인터페이스 설정
serial = spi(port=0, device=0, gpio=noop())
device = max7219(serial, width=32, height=16, block_orientation=-90, blocks_arranged_in_reverse_order=False)
# 매트릭스 크기
matrix_width = 32
matrix_height = 16
# 눈동자 이미지 생성
eye_width = 8
eye_height = 8
eye_color = 255 # 흰색
eye_image = Image.new("1", (matrix_width, matrix_height), color=0) # 도트 매트릭스 크기로 이미지 생성
eye_draw = ImageDraw.Draw(eye_image)
eye_draw.rectangle([0, 0, eye_width, eye_height], fill=eye_color)
# 시작 위치
current_position = [matrix_width // 2 - eye_width // 2, matrix_height // 2 - eye_height // 2]
# 눈동자 이동 속도 (초 단위)
movement_speed = 0.1
try:
while True:
# 눈동자 위치 랜덤으로 이동
new_position = [random.randint(0, matrix_width - eye_width), random.randint(0, matrix_height - eye_height)]
print(type(new_position))
# 이동 방향 계산
dx = 1 if new_position[0] > current_position[0] else -1
dy = 1 if new_position[1] > current_position[1] else -1
# 눈동자 부드럽게 이동
while current_position != new_position:
# 이동 방향으로 한 픽셀씩 이동
current_position[0] += dx
current_position[1] += dy
print(current_position)
# 매트릭스에 이미지 표시
device.clear()
device.display(eye_image)
device.show()
time.sleep(movement_speed)
# 잠시 멈춤
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
device.clear()
#타이머
# import time
# from datetime import datetime, timedelta
# from PIL import Image, ImageDraw, ImageFont
# from luma.led_matrix.device import max7219
# from luma.core.interface.serial import spi, noop
#
# # SPI 인터페이스 설정
# serial = spi(port=0, device=0, gpio=noop())
# device = max7219(serial,width=32, height=16,block_orientation=-90, blocks_arranged_in_reverse_order=False)
#
# # 타이머 설정 (초 단위)
# timer_duration = 300 # 5분 타이머 예시
# end_time = datetime.now() + timedelta(seconds=timer_duration)
#
# try:
# while datetime.now() < end_time:
# remaining_time = end_time - datetime.now()
# seconds = int(remaining_time.total_seconds())
#
# # 분과 초 분리
# minutes, seconds = divmod(seconds, 60)
#
# # 이미지 생성
# image = Image.new("1", (device.width, device.height), color=0)
# draw = ImageDraw.Draw(image)
# font = ImageFont.load_default()
#
# # 텍스트 그리기
# text = f"{minutes:02d}:{seconds:02d}"
# draw.text((2, 2), text, font=font, fill=255)
#
# # 매트릭스에 이미지 표시
# device.display(image)
# time.sleep(1) # 1초마다 갱신
#
# finally:
# device.clear()

22
boot_start.py Normal file
View File

@ -0,0 +1,22 @@
import os
import json
routes = json.loads(os.popen("ip -j -4 route").read())
ip=''
for r in routes:
if r.get("dev") == "wlan0" and r.get("prefsrc"):
ip = r['prefsrc']
continue
if ip == "":
print('초기설정')
elif ip == "10.42.0.1":
print('초기설정')
else:
stream = os.popen('sudo nmcli connection up HOTSPOT')
output = stream.read()
print(output)

129
daum_english.py Normal file
View File

@ -0,0 +1,129 @@
import pymysql
import requests
from bs4 import BeautifulSoup
import random
import time
import json
def fetch_random_words(connection, limit=1):
with connection.cursor() as cursor:
sql = "SELECT word FROM ew_word ORDER BY RAND() LIMIT %s"
cursor.execute(sql, (limit,))
result = cursor.fetchall()
return [row['word'] for row in result]
def fetch_search_results(search_term, session):
# URL 설정
base_url = 'https://dic.daum.net/search.do?q='
url = f"{base_url}{search_term}"
# HTTP GET 요청을 보내고 응답을 가져옴
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1"
}
response = session.get(url, headers=headers)
response.raise_for_status()
return response.text
def parse_results(html):
soup = BeautifulSoup(html, 'html.parser')
results = {}
# <span class="txt_emph1"> 값 추출
emph_span = soup.find('span', class_='txt_emph1')
results['txt_emph1'] = emph_span.get_text(strip=True) if emph_span else 'N/A'
# <ul class="list_search"> 텍스트 내용 추출 및 JSON 변환
list_search = soup.find('ul', class_='list_search')
if list_search:
list_items = list_search.find_all('li')
list_search_data = [li.get_text(strip=True) for li in list_items]
results['list_search'] = json.dumps(list_search_data, ensure_ascii=False)
else:
results['list_search'] = 'N/A'
# <div class="wrap_listen"> 텍스트 내용 추출 및 "듣기" 이후 텍스트 제거
wrap_listen = soup.find('div', class_='wrap_listen')
if wrap_listen:
wrap_listen_text = wrap_listen.get_text(strip=True)
if "듣기" in wrap_listen_text:
wrap_listen_text = wrap_listen_text.split("듣기")[0]
results['wrap_listen'] = wrap_listen_text
else:
results['wrap_listen'] = 'N/A'
# <div name="searchWords" class="search_box" data-initamount="3"> 다차원 JSON 변환
search_box = soup.find('div', {'name': 'searchWords', 'class': 'search_box', 'data-initamount': '3'})
if search_box:
search_items = search_box.find_all('div', class_='searchItem')
search_box_data = []
for item in search_items:
search_word = item.find('a', class_='search_word')
list_search_item = item.find('ul', class_='list_search')
wrap_listen_item = item.find('div', class_='wrap_listen')
search_box_data.append({
'search_word': search_word.get_text(strip=True) if search_word else 'N/A',
'list_search': [li.get_text(strip=True) for li in list_search_item.find_all('li')] if list_search_item else 'N/A',
'wrap_listen': wrap_listen_item.get_text(strip=True).split("듣기")[0] if wrap_listen_item and "듣기" in wrap_listen_item.get_text(strip=True) else (wrap_listen_item.get_text(strip=True) if wrap_listen_item else 'N/A')
})
results['search_box'] = json.dumps(search_box_data, ensure_ascii=False)
else:
results['search_box'] = 'N/A'
return results
def display_results(word, results):
print(f"\nResults for '{word}':")
print(f"1. txt_emph1: {results['txt_emph1']}")
print(f"2. list_search: {results['list_search']}")
print(f"3. wrap_listen: {results['wrap_listen']}")
print(f"4. search_box: {results['search_box']}")
def main():
# MySQL 연결 설정
connection = pymysql.connect(
host="syye.net",
user="pythonUser",
password="Tjekdfl1324%^",
db="English_words",
charset='utf8mb4',
autocommit=True,
cursorclass=pymysql.cursors.DictCursor
)
session = requests.Session()
try:
# 무작위로 단어 가져오기
words = fetch_random_words(connection)
print(f"Fetched words: {words}")
# 각 단어에 대해 검색 및 결과 표시
for word in words:
print(f"\nSearching for '{word}'...")
html = fetch_search_results(word, session)
results = parse_results(html)
display_results(word, results)
# 랜덤 대기 시간 추가
time.sleep(random.uniform(1, 3))
finally:
connection.close()
print("Database connection closed")
if __name__ == '__main__':
main()

126
englishtokorea.py Normal file
View File

@ -0,0 +1,126 @@
import os
import requests
import pandas as pd
from bs4 import BeautifulSoup
def fetch_search_results(search_term):
# URL 설정
base_url = 'http://aha-dic.com/View.asp?word='
url = f"{base_url}{search_term}"
# HTTP GET 요청을 보내고 응답을 가져옴
response = requests.get(url)
response.raise_for_status()
return response.text
def parse_results(html, download_folder):
soup = BeautifulSoup(html, 'html.parser')
results = []
# 결과를 포함하는 div를 찾기
result_div = soup.find('div', id='result')
if result_div:
# class 'word' 텍스트 추출
word_span = result_div.find('span', class_='word')
word = word_span.get_text(strip=True) if word_span else ''
# class 'phoneticKor' 텍스트 추출
phonetic_kor_span = result_div.find('span', class_='phoneticKor')
phonetic_kor = phonetic_kor_span.get_text(strip=True) if phonetic_kor_span else ''
# class 'playSound middle'에서 mp3 url 추출
play_sound = result_div.find('span', class_='playSound middle')
mp3_url = play_sound['mp3'] if play_sound else ''
if mp3_url:
full_mp3_url = f"http://aha-dic.com{mp3_url}"
mp3_filename = os.path.join(download_folder, os.path.basename(mp3_url))
download_file(full_mp3_url, mp3_filename)
else:
full_mp3_url = ''
# ul li HTML 코드 추출 및 예제 품사 추출
ul = result_div.find('ul')
li_elements = ul.find_all('li') if ul else []
meanings = [li.get_text(strip=True) for li in li_elements]
# 예문 및 품사 패널 내용 추출
panels = result_div.find_all('fieldset', class_='panel')
example_sentence = ''
part_of_speech = ''
for panel in panels:
legend = panel.find('legend')
span = panel.find('span')
if legend and span:
if '예문' in legend.get_text(strip=True):
example_sentence = span.get_text(strip=True)
elif '품사' in legend.get_text(strip=True):
part_of_speech = span.get_text(strip=True)
results.append({
'Word': word,
'PhoneticKor': phonetic_kor,
'MP3_URL': full_mp3_url,
'Meanings': '; '.join(meanings),
'ExampleSentence': example_sentence,
'PartOfSpeech': part_of_speech
})
return results
def download_file(url, local_filename):
# MP3 파일을 다운로드하여 지정된 경로에 저장
try:
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Downloaded: {local_filename}")
except Exception as e:
print(f"Failed to download {url}: {e}")
def main():
# 검색어가 포함된 CSV 파일 경로
search_terms_file = 'search_terms.csv' # CSV 파일 경로 설정
download_folder = 'D:\\downloads' # 다운로드할 폴더 경로 설정
if not os.path.exists(download_folder):
os.makedirs(download_folder)
# CSV 파일에서 검색어 불러오기
search_terms_df = pd.read_csv(search_terms_file)
print("CSV 파일의 내용:")
print(search_terms_df.head()) # CSV 파일 내용 확인
if 'search_term' not in search_terms_df.columns:
raise KeyError("CSV 파일에 'search_term' 열이 없습니다.")
search_terms = search_terms_df['search_term'].tolist()[:5] # 테스트용으로 첫 5개의 검색어만 가져옴
all_results = []
# 검색어 루프 돌면서 검색 및 결과 저장
for i, search_term in enumerate(search_terms, start=1):
print(f"Processing {i}/{len(search_terms)}: {search_term}")
try:
html = fetch_search_results(search_term)
results = parse_results(html, download_folder)
all_results.extend(results)
print(f"Finished processing {search_term}")
except Exception as e:
print(f"Error processing {search_term}: {e}")
# 결과를 CSV 파일로 저장
output_filename = 'search_results.csv'
df = pd.DataFrame(all_results)
df.to_csv(output_filename, index=False, encoding='utf-8')
print(f'All results have been saved to {output_filename}')
if __name__ == '__main__':
main()

109
fetch_first_phonetic.py Normal file
View File

@ -0,0 +1,109 @@
import pymysql
import requests
from bs4 import BeautifulSoup
def fetch_words_batch(connection, start_pid, limit=100):
with connection.cursor() as cursor:
sql = "SELECT pid, word FROM ew_word WHERE pid >= %s ORDER BY pid ASC LIMIT %s"
cursor.execute(sql, (start_pid, limit))
result = cursor.fetchall()
return result # 결과를 사전의 리스트로 반환
def fetch_page(word):
# URL 설정
base_url = 'http://aha-dic.com/View.asp?word='
url = f"{base_url}{word}"
# HTTP GET 요청을 보내고 응답을 가져옴
response = requests.get(url)
response.raise_for_status()
return response.text
def parse_phonetic(html):
soup = BeautifulSoup(html, 'html.parser')
phonetic_div = soup.find('div', class_='phonetic')
if phonetic_div:
# 'phonetic_div' 내의 텍스트 노드와 첫 번째 발음기호 추출
phonetic_text = ''
for element in phonetic_div:
if isinstance(element, str):
phonetic_text = element.strip()
if phonetic_text:
break
if phonetic_text:
return phonetic_text
return 'N/A'
def update_phonetic_symbol(connection, pid, phonetic_symbol):
with connection.cursor() as cursor:
sql = "UPDATE ew_word SET phonetic_symbol = %s WHERE pid = %s"
cursor.execute(sql, (phonetic_symbol, pid))
connection.commit()
def main():
# MySQL 연결 설정
connection = pymysql.connect(
host="syye.net",
user="pythonUser",
password="Tjekdfl1324%^",
db="English_words",
charset='utf8mb4',
autocommit=True,
cursorclass=pymysql.cursors.DictCursor
)
start_pid = 0
batch_size = 100
not_updated_words = []
try:
while True:
# 100개의 단어 가져오기
words = fetch_words_batch(connection, start_pid, batch_size)
if not words:
break
print(f"Fetched {len(words)} words from database starting from pid {start_pid}")
# 각 단어에 대해 발음기호 추출 및 업데이트
for word_entry in words:
pid = word_entry['pid']
word = word_entry['word']
print(f"\nFetching phonetic for '{word}' (pid: {pid})...")
html = fetch_page(word)
first_phonetic = parse_phonetic(html)
print(f"The first phonetic symbol for '{word}' is: {first_phonetic}")
# 발음기호를 데이터베이스에 업데이트
if first_phonetic == 'N/A':
not_updated_words.append(word)
else:
update_phonetic_symbol(connection, pid, first_phonetic)
print(f"Updated phonetic symbol for '{word}' (pid: {pid}) to '{first_phonetic}'")
# 다음 배치를 위해 start_pid 업데이트
start_pid = words[-1]['pid'] + 1
finally:
connection.close()
print("Database connection closed")
# 업데이트되지 않은 단어 출력
if not_updated_words:
print("\nWords that were not updated:")
for word in not_updated_words:
print(word)
else:
print("\nAll words were successfully updated.")
if __name__ == '__main__':
main()

53
find_missing_words.py Normal file
View File

@ -0,0 +1,53 @@
import pymysql
import pandas as pd
def fetch_words_from_db(connection):
with connection.cursor() as cursor:
sql = "SELECT word FROM ew_word"
cursor.execute(sql)
result = cursor.fetchall()
return [row['word'] for row in result]
def fetch_words_from_csv(file_path):
search_terms_df = pd.read_csv(file_path)
if 'search_term' not in search_terms_df.columns:
raise KeyError("CSV 파일에 'search_term' 열이 없습니다.")
return search_terms_df['search_term'].tolist()
def find_missing_words(db_words, csv_words):
return [word for word in csv_words if word not in db_words]
def main():
# MySQL 연결 설정
connection = pymysql.connect(
host="syye.net",
user="pythonUser",
password="Tjekdfl1324%^",
db="English_words",
charset='utf8mb4',
autocommit=True,
cursorclass=pymysql.cursors.DictCursor
)
try:
# 데이터베이스에서 단어 목록 가져오기
db_words = fetch_words_from_db(connection)
print(f"데이터베이스에서 {len(db_words)}개의 단어를 가져왔습니다.")
# CSV 파일에서 단어 목록 가져오기
csv_file_path = 'search_terms.csv'
csv_words = fetch_words_from_csv(csv_file_path)
print(f"CSV 파일에서 {len(csv_words)}개의 단어를 가져왔습니다.")
# 존재하지 않는 단어 찾기
missing_words = find_missing_words(db_words, csv_words)
print(f"데이터베이스에 존재하지 않는 단어 {len(missing_words)}개를 찾았습니다:")
for word in missing_words:
print(word)
finally:
connection.close()
print("Database connection closed")
if __name__ == '__main__':
main()

27
first.py Normal file
View File

@ -0,0 +1,27 @@
import subprocess
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def scan_wifi_networks():
try:
result = subprocess.run(['sudo', 'iwlist', 'wlan0', 'scan'], capture_output=True, text=True)
networks = parse_iwlist_output(result.stdout)
return networks # 이 부분이 Wi-Fi 목록을 반환하도록 보장해야 함
except Exception as e:
print(f"Error scanning Wi-Fi networks: {e}")
return [] # 오류가 발생하면 빈 리스트 반환
def parse_iwlist_output(output):
# 여기에 iwlist 출력을 파싱하여 네트워크 리스트를 생성하는 코드를 추가합니다.
# 예: 네트워크 이름 (ESSID) 및 기타 세부 정보를 추출합니다.
pass
def index():
networks = scan_wifi_networks()
return render_template('index.html', networks=networks)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')

172
main.py Normal file
View File

@ -0,0 +1,172 @@
import os
import requests
import pandas as pd
from bs4 import BeautifulSoup
import pymysql
def fetch_search_results(search_term):
# URL 설정
base_url = 'http://aha-dic.com/View.asp?word='
url = f"{base_url}{search_term}"
# HTTP GET 요청을 보내고 응답을 가져옴
response = requests.get(url)
response.raise_for_status()
return response.text
def parse_results(html, download_folder):
soup = BeautifulSoup(html, 'html.parser')
results = {}
# 결과를 포함하는 div를 찾기
result_div = soup.find('div', id='container_result')
if result_div:
# class 'word' 텍스트 추출
word_span = result_div.find('span', class_='word')
results['Word'] = word_span.get_text(strip=True) if word_span else ''
# class 'phoneticKor' 텍스트 추출 및 HTML 수정
phonetic_kor_span = result_div.find('span', class_='phoneticKor')
if phonetic_kor_span:
for accent_span in phonetic_kor_span.find_all('span', class_='accent'):
accent_span.name = 'b' # <span class="accent"> 태그를 <b> 태그로 변경
accent_span.attrs = {} # 모든 속성을 제거
phonetic_kor_html = str(phonetic_kor_span)
phonetic_kor_html = phonetic_kor_html.replace('<span class="phoneticKor">', '').replace('</span>', '')
results['PhoneticKor'] = phonetic_kor_html
else:
results['PhoneticKor'] = ''
# class 'playSound middle'에서 mp3 url 추출
play_sound = result_div.find('span', class_='playSound middle')
mp3_url = play_sound['mp3'] if play_sound else ''
if mp3_url:
full_mp3_url = f"http://aha-dic.com{mp3_url}"
mp3_filename = os.path.basename(mp3_url)
download_file(full_mp3_url, os.path.join(download_folder, mp3_filename))
results['MP3_File'] = mp3_filename
else:
results['MP3_File'] = ''
# 여러 개의 ul li HTML 코드 추출
meanings = []
ul_elements = result_div.find_all('ul')
for ul in ul_elements:
li_elements = ul.find_all('li')
for li in li_elements:
meanings.append(li.get_text(strip=True))
results['Meanings'] = '; '.join(meanings)
# 예문 및 품사 패널 내용 추출
example_sentence = ''
part_of_speech = ''
panels = result_div.find_all('fieldset', class_='panel')
for panel in panels:
legend = panel.find('legend')
span = panel.find('span')
if legend and span:
if '예문' in legend.get_text(strip=True):
example_sentence = span.decode_contents().replace('<br><br>', '\n').strip()
elif '품사' in legend.get_text(strip=True):
part_of_speech = span.get_text(strip=True)
results['ExampleSentence'] = BeautifulSoup(example_sentence, 'html.parser').get_text(strip=True)
results['PartOfSpeech'] = part_of_speech
return results
def download_file(url, local_filename):
# MP3 파일을 다운로드하여 지정된 경로에 저장
try:
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Downloaded: {local_filename}")
except Exception as e:
print(f"Failed to download {url}: {e}")
def save_to_database(data, connection):
with connection.cursor() as cursor:
sql = """
INSERT INTO ew_word (level, word, phonetic_kor, phonetic_symbol, mp3_file, meanings, examplesentence, partofspeech)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""
values = (
'1', # level은 1로 고정
data['Word'],
data['PhoneticKor'],
'', # phonetic_symbol은 빈 값으로 설정
data['MP3_File'],
data['Meanings'],
data['ExampleSentence'],
data['PartOfSpeech']
)
cursor.execute(sql, values)
connection.commit()
def main():
# 검색어가 포함된 CSV 파일 경로
search_terms_file = 'search_terms.csv' # CSV 파일 경로 설정
download_folder = r'D:\_SUNGRO_DEV\python_project\english_project\mp3' # 다운로드할 폴더 경로 설정
if not os.path.exists(download_folder):
os.makedirs(download_folder)
# MySQL 연결 설정
connection = pymysql.connect(
host="syye.net",
user="pythonUser",
password="Tjekdfl1324%^",
db="English_words",
charset='utf8mb4',
autocommit=True
)
failed_words = []
try:
# CSV 파일에서 검색어 불러오기
search_terms_df = pd.read_csv(search_terms_file)
print("CSV 파일의 내용:")
print(search_terms_df.head()) # CSV 파일 내용 확인
if 'search_term' not in search_terms_df.columns:
raise KeyError("CSV 파일에 'search_term' 열이 없습니다.")
search_terms = search_terms_df['search_term']
all_results = []
# 검색어 루프 돌면서 검색 및 결과 저장
for i, search_term in enumerate(search_terms, start=1):
print(f"Processing {i}/{len(search_terms)}: {search_term}")
try:
html = fetch_search_results(search_term)
result = parse_results(html, download_folder)
result['SearchTerm'] = search_term # 검색어도 결과에 포함
all_results.append(result)
print(f"Finished processing {search_term}")
# 데이터베이스에 저장
save_to_database(result, connection)
print(f"Saved {search_term} to database")
except Exception as e:
print(f"Error processing {search_term}: {e}")
failed_words.append({'word': search_term, 'error': str(e)})
finally:
connection.close()
print("Database connection closed")
# 저장하지 못한 단어 출력
if failed_words:
print("\nFailed to save the following words:")
for entry in failed_words:
print(f"Word: {entry['word']}, Error: {entry['error']}")
if __name__ == '__main__':
main()

202
main_backup.py Normal file
View File

@ -0,0 +1,202 @@
import pymysql
import pygame
import time
import RPi.GPIO as GPIO
import requests
import json
import psutil
from datetime import datetime
from gtts import gTTS
from mutagen.mp3 import MP3
from luma.core.interface.serial import spi, noop
from luma.core.render import canvas
from luma.core.legacy import text, show_message
from luma.core.virtual import viewport
from luma.led_matrix.device import max7219
from PIL import ImageFont
from luma.core.legacy.font import proportional, CP437_FONT, TINY_FONT
timedisplay = False
# 밝기센서 핀 설정
light_sensor_pin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(light_sensor_pin, GPIO.IN)
#밝기체크 gpio
def brightness():
return GPIO.input(light_sensor_pin)
# 폰트설정
font = ImageFont.truetype("/home/pi/python_project/NeoDunggeunmoPro-Regular.ttf", size=16)
font2 = ImageFont.truetype("/home/pi/python_project/pixelmix.ttf", size=6)
font3 = ImageFont.truetype("/home/pi/python_project/DungGeunMo.ttf", size=8)
#max7219 클래스 초기화
serial = spi(port=0, device=0, gpio=noop())
device = max7219(serial,width=32, height=16,block_orientation=-90, blocks_arranged_in_reverse_order=False)
#데이터베이스 세팅
class db_con:
host="syye.net"
user="pythonUser"
password="Tjekdfl1324%^"
database="pythonDB"
char='utf8'
# MySQL 서버 연결 설정
conn = pymysql.connect(
host="syye.net",
user="pythonUser",
password="Tjekdfl1324%^",
db="pythonDB",
charset='utf8',
autocommit=True)
# mysql 커서 생성
curs = conn.cursor(pymysql.cursors.DictCursor)
def byte_transform(bytes, to, bsize=1024):
a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 }
r = float(bytes)
for i in range(a[to]):
r = r / bsize
return round(r,2)
#현제시간 / 날씨d
def animation(device):
#openweathermap api 데이터 호출
api = "https://api.openweathermap.org/data/2.5/weather?lat=35.8242238&lon=127.1479532&appid=00eb2155e51742aa2856a69da0f6dc61&lang=kr&units=metric"
result = requests.get(api)
result = json.loads(result.text)
weather = result['weather'][0]['description'] #날씨
temperature = result['main']['temp'] # 현제온도
feels_like = result['main']['feels_like'] # 체감온도
humidity = result['main']['humidity'] # 습도
toggle = False # Toggle the second indicator every second
while True:
memory = psutil.virtual_memory()
total_memory = byte_transform(memory.total,'m')
used_memory = byte_transform(memory.used,'m')
free_memory = byte_transform(memory.available,'m')
print(f"Total Memory: {total_memory} M")
print(f"Used Memory: {used_memory} M")
print(f"Free Memory: {free_memory} M")
toggle = not toggle
hours = datetime.now().strftime('%H')
minutes = datetime.now().strftime('%M')
month = datetime.now().strftime('%m')
day = datetime.now().strftime('%d')
sec = datetime.now().second
print(sec)
if sec == 1:
# 조회
sql = "SELECT * FROM chet where stat='0' order by id asc limit 1"
curs.execute(sql)
rows = curs.fetchall()
cnt = curs.rowcount
print(cnt)
if cnt > 0:
dataload(device,rows)
break
elif sec == 20:
weathertext = "전주 오늘날씨 : " + weather + ", 온도:" + str(temperature) + "도, 체감온도:" + str(
feels_like) + "도, 습도:" + str(humidity) + "%"
virtual = viewport(device, height=device.width, width=len(weathertext) * 14)
with canvas(virtual) as draw:
draw.rectangle(device.bounding_box)
draw.text((32, 1), weathertext, fill="white", font=font)
for offset in range(virtual.width - device.width):
# Led밝기
device.contrast(255) if brightness() == 0 else device.contrast(10)
virtual.set_position((offset, 0))
time.sleep(0.03)
elif sec == 40:
api = "https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWUSD"
result = requests.get(api)
result = json.loads(result.text)
name = result[0]['name']
times = result[0]['time']
basePrice = result[0]['basePrice']
provider = result[0]['provider']
pricetext = name+" 환율 : 1$ / " + str(basePrice) + " 시간:" + str(times) + " 자료:" + str(provider)
virtual = viewport(device, height=device.width, width=len(pricetext) * 13)
with canvas(virtual) as draw:
draw.rectangle(device.bounding_box)
draw.text((32, 1), pricetext, fill="white", font=font)
for offset in range(virtual.width - device.width):
# Led밝기
device.contrast(255) if brightness() == 0 else device.contrast(10)
virtual.set_position((offset, 0))
time.sleep(0.03)
else:
with canvas(device) as draw:
text(draw, (1, 8), hours, fill="white", font=proportional(CP437_FONT))
text(draw, (16, 8), ":" if toggle else " ", fill="white", font=proportional(TINY_FONT))
text(draw, (18, 8), minutes, fill="white", font=proportional(CP437_FONT))
draw.text((2, 1),month+". "+day, fill="white", font=font2)
if sec%3 == 0:
device.contrast(255) if brightness() == 0 else device.contrast(10)
time.sleep(0.5)
def dataload(device,rows):
# 가져온 데이터를 처리하거나 출력할 수 있습니다.
for data in rows:
title = data['mess']
author = data['name']
idx = data['id']
# 출력한 데이터 업데이트
update_query = "UPDATE chet set stat=%s where id=%s"
data = ("1", idx)
curs.execute(update_query, data)
# 음성으로 작성할 문구
script = author + "가 보낸메세지 "
script += title
# mp3파일 생성
tts_ko = gTTS(text=script, lang='ko')
tts_ko.save('./temp.mp3')
# mp3파일 재생
audio = MP3("./temp.mp3")
times = audio.info.length
pygame.mixer.init()
pygame.mixer.music.load("./temp.mp3")
pygame.mixer.music.play()
time.sleep(1)
virtual = viewport(device, height=device.width, width=len(title) * 16)
with canvas(virtual) as draw:
draw.rectangle(device.bounding_box)
draw.text((32, 1), "mess : " + title, fill="white", font=font)
for offset in range(virtual.width - device.width):
# Led밝기
device.contrast(255) if brightness() == 0 else device.contrast(10)
virtual.set_position((offset, 0))
time.sleep(0.03)
time.sleep(times) # wait and let the sound play for 1 second
pygame.mixer.music.stop()
print('end')
animation(device)
animation(device)

BIN
mp3/_ARM.mp3 Normal file

Binary file not shown.

BIN
mp3/_American.mp3 Normal file

Binary file not shown.

BIN
mp3/_I.mp3 Normal file

Binary file not shown.

BIN
mp3/_OK.mp3 Normal file

Binary file not shown.

BIN
mp3/_Pm.mp3 Normal file

Binary file not shown.

BIN
mp3/_TV.mp3 Normal file

Binary file not shown.

BIN
mp3/_a.mp3 Normal file

Binary file not shown.

BIN
mp3/_ability.mp3 Normal file

Binary file not shown.

BIN
mp3/_able.mp3 Normal file

Binary file not shown.

BIN
mp3/_about.mp3 Normal file

Binary file not shown.

BIN
mp3/_above.mp3 Normal file

Binary file not shown.

BIN
mp3/_accept.mp3 Normal file

Binary file not shown.

BIN
mp3/_according.mp3 Normal file

Binary file not shown.

BIN
mp3/_account.mp3 Normal file

Binary file not shown.

BIN
mp3/_across.mp3 Normal file

Binary file not shown.

BIN
mp3/_act.mp3 Normal file

Binary file not shown.

BIN
mp3/_action.mp3 Normal file

Binary file not shown.

BIN
mp3/_activity.mp3 Normal file

Binary file not shown.

BIN
mp3/_actually.mp3 Normal file

Binary file not shown.

BIN
mp3/_add.mp3 Normal file

Binary file not shown.

BIN
mp3/_address.mp3 Normal file

Binary file not shown.

BIN
mp3/_administration.mp3 Normal file

Binary file not shown.

BIN
mp3/_admit.mp3 Normal file

Binary file not shown.

BIN
mp3/_adult.mp3 Normal file

Binary file not shown.

BIN
mp3/_affect.mp3 Normal file

Binary file not shown.

BIN
mp3/_after.mp3 Normal file

Binary file not shown.

BIN
mp3/_again.mp3 Normal file

Binary file not shown.

BIN
mp3/_against.mp3 Normal file

Binary file not shown.

BIN
mp3/_age.mp3 Normal file

Binary file not shown.

BIN
mp3/_agency.mp3 Normal file

Binary file not shown.

BIN
mp3/_agent.mp3 Normal file

Binary file not shown.

BIN
mp3/_ago.mp3 Normal file

Binary file not shown.

BIN
mp3/_agree.mp3 Normal file

Binary file not shown.

BIN
mp3/_agreement.mp3 Normal file

Binary file not shown.

BIN
mp3/_ahead.mp3 Normal file

Binary file not shown.

BIN
mp3/_air.mp3 Normal file

Binary file not shown.

BIN
mp3/_all.mp3 Normal file

Binary file not shown.

BIN
mp3/_allow.mp3 Normal file

Binary file not shown.

BIN
mp3/_almost.mp3 Normal file

Binary file not shown.

BIN
mp3/_alone.mp3 Normal file

Binary file not shown.

BIN
mp3/_along.mp3 Normal file

Binary file not shown.

BIN
mp3/_already.mp3 Normal file

Binary file not shown.

BIN
mp3/_also.mp3 Normal file

Binary file not shown.

BIN
mp3/_although.mp3 Normal file

Binary file not shown.

BIN
mp3/_always.mp3 Normal file

Binary file not shown.

BIN
mp3/_among.mp3 Normal file

Binary file not shown.

BIN
mp3/_amount.mp3 Normal file

Binary file not shown.

BIN
mp3/_analysis.mp3 Normal file

Binary file not shown.

BIN
mp3/_and.mp3 Normal file

Binary file not shown.

BIN
mp3/_animal.mp3 Normal file

Binary file not shown.

BIN
mp3/_another.mp3 Normal file

Binary file not shown.

BIN
mp3/_answer.mp3 Normal file

Binary file not shown.

BIN
mp3/_any.mp3 Normal file

Binary file not shown.

BIN
mp3/_anyone.mp3 Normal file

Binary file not shown.

BIN
mp3/_anything.mp3 Normal file

Binary file not shown.

BIN
mp3/_appear.mp3 Normal file

Binary file not shown.

BIN
mp3/_apply.mp3 Normal file

Binary file not shown.

BIN
mp3/_approach.mp3 Normal file

Binary file not shown.

BIN
mp3/_area.mp3 Normal file

Binary file not shown.

BIN
mp3/_argue.mp3 Normal file

Binary file not shown.

BIN
mp3/_around.mp3 Normal file

Binary file not shown.

BIN
mp3/_arrive.mp3 Normal file

Binary file not shown.

BIN
mp3/_art.mp3 Normal file

Binary file not shown.

BIN
mp3/_article.mp3 Normal file

Binary file not shown.

BIN
mp3/_artist.mp3 Normal file

Binary file not shown.

BIN
mp3/_as.mp3 Normal file

Binary file not shown.

BIN
mp3/_ask.mp3 Normal file

Binary file not shown.

BIN
mp3/_assume.mp3 Normal file

Binary file not shown.

BIN
mp3/_at.mp3 Normal file

Binary file not shown.

BIN
mp3/_attack.mp3 Normal file

Binary file not shown.

BIN
mp3/_attention.mp3 Normal file

Binary file not shown.

BIN
mp3/_attorney.mp3 Normal file

Binary file not shown.

BIN
mp3/_audience.mp3 Normal file

Binary file not shown.

BIN
mp3/_author.mp3 Normal file

Binary file not shown.

BIN
mp3/_authority.mp3 Normal file

Binary file not shown.

BIN
mp3/_available.mp3 Normal file

Binary file not shown.

BIN
mp3/_avoid.mp3 Normal file

Binary file not shown.

BIN
mp3/_away.mp3 Normal file

Binary file not shown.

BIN
mp3/_baby.mp3 Normal file

Binary file not shown.

BIN
mp3/_back.mp3 Normal file

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More