SPARC64/HERMES-XP-2025
0
1import gradio as gr2import re3import os4import base645import time6from datetime import datetime, timedelta, timezone7 8# 設定9SUPPORT_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/main/README.md"10HELP_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/Q%26A/README.md"11COPYRIGHT_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/copyright/README.md"12CONTACT_URL = "https://forms.gle/mAUj1CdhufHFbiWs7"13TS_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/troubleshooting/README.md"14MANUAL_URL = "https://youtu.be/j2GJtO5BydA"15JST = timezone(timedelta(hours=9))16 17def load_log_file(file, progress=gr.Progress()):18 """ログファイルを読み込む(プログレスバー付き)"""19 if not file:20 return None, "エラー(FILE-001): ファイルが選択されていません。"21 22 if not file.name.endswith(".txt"):23 return None, "エラー(FILE-005): TXTファイルを選択してください。"24 25 try:26 with open(file.name, "r", encoding="utf-8") as f:27 content = f.readlines()28 29 for _ in progress.tqdm(range(1, 101), desc="ログファイルを読み込み中..."):30 time.sleep(0.01)31 32 return content, None33 except Exception as e:34 return None, f"エラー(FILE-002): ファイルの読み込みに失敗しました ({str(e)})"35 36def extract_date_range_logs(lines, start_date, end_date):37 """指定された日付範囲のログを抽出"""38 results = []39 current_date = None40 41 for line in lines:42 date_match = re.match(r"(\d{4}/\d{1,2}/\d{1,2})", line)43 if date_match:44 try:45 current_date = datetime.strptime(date_match.group(1), "%Y/%m/%d")46 except ValueError:47 continue # 無効な日付フォーマットはスキップ48 49 if current_date and start_date <= current_date < end_date:50 results.append(line.strip())51 52 return results53 54def search_logs(file, keyword, year, month, day, progress=gr.Progress()):55 """ログ検索(プログレスバー付き)"""56 log_lines, error = load_log_file(file)57 if error:58 return "", error, None59 60 if not log_lines:61 return "", "エラー(FILE-003): ファイルが空です。", None62 63 is_word_search = bool(keyword.strip())64 is_date_search = year != "----" and month != "----" and day != "----"65 66 if is_word_search and is_date_search:67 return "", "エラー(SEARCH-001): ワード検索と日付検索は同時に行えません。", None68 69 search_condition = "検索条件: なし"70 results = []71 72 if is_word_search:73 search_condition = f"検索条件: ワード[{keyword}]"74 for line in progress.tqdm(log_lines, desc="検索中..."):75 if keyword in line:76 results.append(f"- {line.strip()}")77 78 elif is_date_search:79 try:80 search_date = f"{year}/{month}/{day}"81 start_date = datetime.strptime(search_date, "%Y/%m/%d")82 end_date = start_date + timedelta(days=1)83 search_condition = f"検索条件: 日付[{search_date}]"84 results = extract_date_range_logs(log_lines, start_date, end_date)85 results = [f"- {line.strip()}" for line in results]86 except ValueError:87 return "", "エラー(SEARCH-002): 無効な日付形式です。", None88 89 formatted_results = "\n".join(results) if results else "エラー(SEARCH-003): 一致する結果が見つかりませんでした。"90 return formatted_results, f"{len(results)} 件の結果が見つかりました。", search_condition91 92def generate_download_link(results, search_condition, progress=gr.Progress()):93 """エクスポート処理(プログレスバー付き)"""94 if not results:95 return "エラー(EXPORT-001): エクスポートするデータがありません。"96 97 execution_time = datetime.now(JST).strftime("%Y%m%d_%H%M%S")98 JPN_date = datetime.now(JST).strftime("%Y/%m/%d %H:%M:%S")99 100 if "ワード" in search_condition:101 condition_text = search_condition.replace("検索条件: ワード[", "").replace("]", "").replace(" ", "_")102 elif "日付" in search_condition:103 condition_text = search_condition.replace("検索条件: 日付[", "").replace("]", "").replace("/", "_")104 else:105 condition_text = "検索条件なし"106 107 file_name = f"{execution_time}_LINE-Log-Manager-search-Export-{condition_text}.txt"108 109 file_content = (110 "プログラム名: LINEログマネージャー\n"111 f"検索実行日: {JPN_date}\n"112 f"{search_condition}\n"113 f"ヒット件数: {len(results.splitlines())} 件\n"114 + "-" * 40 + "\n"115 + results + "\n"116 )117 118 encoded_file = base64.b64encode(file_content.encode()).decode()119 120 for _ in progress.tqdm(range(1, 101), desc="エクスポート処理中..."):121 time.sleep(0.01)122 123 href = f'<a href="data:text/plain;base64,{encoded_file}" download="{file_name}">結果をダウンロード</a>'124 return href125 126with gr.Blocks() as demo:127 gr.HTML("<h1>LINEログマネージャー</h1>")128 gr.Markdown(f"使い方は[こちら]({MANUAL_URL})")129 130 file_input = gr.File(label="ログファイルをアップロード")131 132 search_word = gr.Textbox(label="ユーザー検索ワード")133 134 year = gr.Dropdown(choices=["----"] + [str(y) for y in range(2020, 2041)], value="----", label="年")135 month = gr.Dropdown(choices=["----"] + [str(m) for m in range(1, 13)], value="----", label="月")136 day = gr.Dropdown(choices=["----"] + [str(d) for d in range(1, 32)], value="----", label="日")137 138 search_button = gr.Button("検索")139 result_table = gr.Textbox(label="検索結果", interactive=False, lines=10)140 result_message = gr.Textbox(label="ステータス", interactive=False)141 142 search_condition_state = gr.State()143 144 export_button = gr.Button("TXTをエクスポートする")145 export_output = gr.HTML()146 export_status = gr.Textbox(label="エクスポートメッセージ", interactive=False)147 148 search_button.click(search_logs, inputs=[file_input, search_word, year, month, day], outputs=[result_table, result_message, search_condition_state])149 export_button.click(generate_download_link, inputs=[result_table, search_condition_state], outputs=[export_output])150 151 gr.Markdown(f"[📖 ヘルプページ]({HELP_URL})")152 gr.Markdown(f"[⚠ トラブルシューティング]({TS_URL})")153 gr.Markdown(f"[❓ 問い合わせフォーム]({CONTACT_URL})")154 gr.Markdown(f"[🛠 サポート]({SUPPORT_URL})")155 gr.Markdown(f"[© コピーライト&作成者情報]({COPYRIGHT_URL})")156 gr.Markdown("---")157 gr.Markdown("This project code was partially generated with assistance from [OpenAI's ChatGPT.](https://chatgpt.com/)")158 gr.Markdown("This Application is Confidential.")159 gr.Markdown("パヤ爺/Studio MARX,2025. All rights reserved.")160 gr.Markdown("---")161 gr.Markdown("LINE Log Manager Hugging Face Edition Ver.2.1.0")162demo.launch()163 