Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,28 @@
|
|
| 1 |
import os, csv, requests, gradio as gr
|
| 2 |
from huggingface_hub import hf_hub_download, upload_file
|
|
|
|
| 3 |
|
| 4 |
-
#
|
|
|
|
|
|
|
|
|
|
| 5 |
REPO_ID = os.getenv("REPO_ID", "YuShen1124/youtube-tags-tool")
|
| 6 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 7 |
YOUTUBE_API_KEY = os.getenv("AIzaSyCvgpJMhcrDao6Li4qMUbFcifFSobbcIZw")
|
| 8 |
DATA_DIR = "./data"
|
| 9 |
-
os.makedirs(DATA_DIR, exist_ok=True)
|
| 10 |
CSV_FILE = os.path.join(DATA_DIR, "tags_data.csv")
|
| 11 |
COUNTER_FILE = os.path.join(DATA_DIR, "counter.txt")
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
def init_file(remote, local):
|
| 15 |
try:
|
| 16 |
hf_hub_download(repo_id=REPO_ID, filename=remote, local_dir=DATA_DIR, token=HF_TOKEN)
|
|
|
|
| 17 |
except Exception:
|
| 18 |
open(local, "a", encoding="utf-8").close()
|
|
|
|
| 19 |
|
| 20 |
init_file("tags_data.csv", CSV_FILE)
|
| 21 |
init_file("counter.txt", COUNTER_FILE)
|
|
@@ -23,37 +30,55 @@ init_file("counter.txt", COUNTER_FILE)
|
|
| 23 |
# 讀取 CSV
|
| 24 |
def read_csv_data():
|
| 25 |
data = {}
|
| 26 |
-
|
| 27 |
with open(CSV_FILE, encoding='utf-8', newline='') as f:
|
| 28 |
for tag, count in csv.reader(f):
|
| 29 |
data[tag] = int(count)
|
|
|
|
|
|
|
| 30 |
return data
|
| 31 |
|
| 32 |
-
# 寫入
|
| 33 |
def write_csv_data(data):
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
path_or_fileobj=CSV_FILE,
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
|
| 43 |
-
# 呼叫 YouTube API 取得 tags
|
| 44 |
def get_video_tags(keyword):
|
| 45 |
-
params = {'part':'snippet','q':keyword,'type':'video','maxResults':10,'key':YOUTUBE_API_KEY}
|
| 46 |
-
resp = requests.get("https://www.googleapis.com/youtube/v3/search", params=params).json()
|
| 47 |
tags_count = {}
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
return tags_count
|
| 58 |
|
| 59 |
# 更新並分析標籤
|
|
@@ -61,20 +86,25 @@ def update_and_analyze_tags(keyword):
|
|
| 61 |
if not keyword.strip():
|
| 62 |
return "未輸入關鍵字", "", ""
|
| 63 |
new_tags = get_video_tags(keyword)
|
|
|
|
|
|
|
| 64 |
agg = read_csv_data()
|
| 65 |
for t, c in new_tags.items(): agg[t] = agg.get(t, 0) + c
|
| 66 |
write_csv_data(agg)
|
| 67 |
|
| 68 |
-
# 更新
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
| 70 |
with open(COUNTER_FILE, 'w', encoding='utf-8') as f:
|
| 71 |
f.write(str(cnt))
|
| 72 |
-
|
| 73 |
-
path_or_fileobj=COUNTER_FILE,
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
|
| 79 |
sorted_tags = sorted(agg.items(), key=lambda x: x[1], reverse=True)
|
| 80 |
full = "\n".join(f"{t}: {c}" for t, c in sorted_tags)
|
|
@@ -94,4 +124,4 @@ with gr.Blocks() as demo:
|
|
| 94 |
inp.submit(update_and_analyze_tags, inputs=inp, outputs=[out1, out2, out3])
|
| 95 |
|
| 96 |
if __name__ == "__main__":
|
| 97 |
-
demo.launch()
|
|
|
|
| 1 |
import os, csv, requests, gradio as gr
|
| 2 |
from huggingface_hub import hf_hub_download, upload_file
|
| 3 |
+
import logging
|
| 4 |
|
| 5 |
+
# 設定日誌等級
|
| 6 |
+
logging.basicConfig(level=logging.INFO)
|
| 7 |
+
|
| 8 |
+
# -- 環境變數 & 路徑 --
|
| 9 |
REPO_ID = os.getenv("REPO_ID", "YuShen1124/youtube-tags-tool")
|
| 10 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 11 |
YOUTUBE_API_KEY = os.getenv("AIzaSyCvgpJMhcrDao6Li4qMUbFcifFSobbcIZw")
|
| 12 |
DATA_DIR = "./data"
|
|
|
|
| 13 |
CSV_FILE = os.path.join(DATA_DIR, "tags_data.csv")
|
| 14 |
COUNTER_FILE = os.path.join(DATA_DIR, "counter.txt")
|
| 15 |
|
| 16 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
# 初始化遠端檔案,若不存在則本地建立
|
| 19 |
def init_file(remote, local):
|
| 20 |
try:
|
| 21 |
hf_hub_download(repo_id=REPO_ID, filename=remote, local_dir=DATA_DIR, token=HF_TOKEN)
|
| 22 |
+
logging.info(f"Downloaded {remote} from Hub")
|
| 23 |
except Exception:
|
| 24 |
open(local, "a", encoding="utf-8").close()
|
| 25 |
+
logging.info(f"Initialized empty {local}")
|
| 26 |
|
| 27 |
init_file("tags_data.csv", CSV_FILE)
|
| 28 |
init_file("counter.txt", COUNTER_FILE)
|
|
|
|
| 30 |
# 讀取 CSV
|
| 31 |
def read_csv_data():
|
| 32 |
data = {}
|
| 33 |
+
try:
|
| 34 |
with open(CSV_FILE, encoding='utf-8', newline='') as f:
|
| 35 |
for tag, count in csv.reader(f):
|
| 36 |
data[tag] = int(count)
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logging.error(f"Error reading CSV: {e}")
|
| 39 |
return data
|
| 40 |
|
| 41 |
+
# 寫入並上傳 CSV
|
| 42 |
def write_csv_data(data):
|
| 43 |
+
try:
|
| 44 |
+
with open(CSV_FILE, 'w', encoding='utf-8', newline='') as f:
|
| 45 |
+
csv.writer(f).writerows(data.items())
|
| 46 |
+
upload_file(path_or_fileobj=CSV_FILE, path_in_repo="tags_data.csv",
|
| 47 |
+
repo_id=REPO_ID, token=HF_TOKEN)
|
| 48 |
+
logging.info("CSV uploaded to Hub")
|
| 49 |
+
except Exception as e:
|
| 50 |
+
logging.error(f"Error writing/uploading CSV: {e}")
|
| 51 |
|
| 52 |
+
# 呼叫 YouTube API 取得 tags,附加 timeout 與錯誤處理
|
| 53 |
def get_video_tags(keyword):
|
|
|
|
|
|
|
| 54 |
tags_count = {}
|
| 55 |
+
try:
|
| 56 |
+
resp = requests.get(
|
| 57 |
+
"https://www.googleapis.com/youtube/v3/search",
|
| 58 |
+
params={'part':'snippet','q':keyword,'type':'video','maxResults':10,'key':YOUTUBE_API_KEY},
|
| 59 |
+
timeout=10
|
| 60 |
+
)
|
| 61 |
+
resp.raise_for_status()
|
| 62 |
+
items = resp.json().get('items', [])
|
| 63 |
+
except Exception as e:
|
| 64 |
+
logging.error(f"Search API error: {e}")
|
| 65 |
+
return tags_count
|
| 66 |
+
|
| 67 |
+
for item in items:
|
| 68 |
+
vid = item['id'].get('videoId')
|
| 69 |
+
if not vid: continue
|
| 70 |
+
try:
|
| 71 |
+
info = requests.get(
|
| 72 |
+
"https://www.googleapis.com/youtube/v3/videos",
|
| 73 |
+
params={'part':'snippet','id':vid,'key':YOUTUBE_API_KEY},
|
| 74 |
+
timeout=10
|
| 75 |
+
)
|
| 76 |
+
info.raise_for_status()
|
| 77 |
+
for v in info.json().get('items', []):
|
| 78 |
+
for tag in v['snippet'].get('tags', []):
|
| 79 |
+
tags_count[tag] = tags_count.get(tag, 0) + 1
|
| 80 |
+
except Exception as e:
|
| 81 |
+
logging.warning(f"Video API error for {vid}: {e}")
|
| 82 |
return tags_count
|
| 83 |
|
| 84 |
# 更新並分析標籤
|
|
|
|
| 86 |
if not keyword.strip():
|
| 87 |
return "未輸入關鍵字", "", ""
|
| 88 |
new_tags = get_video_tags(keyword)
|
| 89 |
+
if not new_tags:
|
| 90 |
+
logging.info("No tags found for keyword")
|
| 91 |
agg = read_csv_data()
|
| 92 |
for t, c in new_tags.items(): agg[t] = agg.get(t, 0) + c
|
| 93 |
write_csv_data(agg)
|
| 94 |
|
| 95 |
+
# 計數器讀取、更新與上傳
|
| 96 |
+
try:
|
| 97 |
+
cnt = int(open(COUNTER_FILE, encoding='utf-8').read().strip() or 0) + 1
|
| 98 |
+
except:
|
| 99 |
+
cnt = 1
|
| 100 |
with open(COUNTER_FILE, 'w', encoding='utf-8') as f:
|
| 101 |
f.write(str(cnt))
|
| 102 |
+
try:
|
| 103 |
+
upload_file(path_or_fileobj=COUNTER_FILE, path_in_repo="counter.txt",
|
| 104 |
+
repo_id=REPO_ID, token=HF_TOKEN)
|
| 105 |
+
logging.info("Counter uploaded")
|
| 106 |
+
except Exception as e:
|
| 107 |
+
logging.error(f"Error uploading counter: {e}")
|
| 108 |
|
| 109 |
sorted_tags = sorted(agg.items(), key=lambda x: x[1], reverse=True)
|
| 110 |
full = "\n".join(f"{t}: {c}" for t, c in sorted_tags)
|
|
|
|
| 124 |
inp.submit(update_and_analyze_tags, inputs=inp, outputs=[out1, out2, out3])
|
| 125 |
|
| 126 |
if __name__ == "__main__":
|
| 127 |
+
demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", 7860)))
|