Spaces:
Sleeping
Sleeping
File size: 3,974 Bytes
552723f 6f8cb3a 552723f 6f8cb3a c38832e 4a35344 6f8cb3a 552723f 6f8cb3a 4a35344 6f8cb3a 4a35344 552723f 6f8cb3a 4a35344 6f8cb3a 4a35344 6f8cb3a 4a35344 6f8cb3a 4a35344 6f8cb3a 552723f 6f8cb3a 4a35344 6f8cb3a 4a35344 6f8cb3a 4a35344 6f8cb3a b9a0715 4a35344 6f8cb3a c38832e 552723f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
import gradio as gr
import google.generativeai as genai
import os
import json
import re
from pathlib import Path
def load_prompt(prompt_file):
"""從檔案讀取 prompt.txt 的內容。"""
try:
with open(prompt_file, 'r', encoding='utf-8') as f:
prompt = f.read()
return prompt
except FileNotFoundError:
print(f"FileNotFoundError: Prompt file not found at {prompt_file}")
return f"Error: Prompt file not found at {prompt_file}"
except Exception as e:
print(f"Error loading prompt file: {e}")
return f"Error: An unexpected error occurred when processing the prompt. Detail: {e}"
def load_dictionary(dictionary_file):
"""從檔案讀取 dictionary.txt 的內容。"""
try:
with open(dictionary_file, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print(f"FileNotFoundError: Dictionary file not found at {dictionary_file}")
return f"Error: Dictionary file not found at {dictionary_file}"
except json.JSONDecodeError as e:
print(f"JSONDecodeError: {e}")
return f"Error: Invalid JSON format in dictionary file. JSONDecodeError: {e}"
except Exception as e:
print(f"Error loading dictionary JSON: {e}")
return f"Error: An unexpected error occurred when processing the JSON. Detail: {e}"
def process_article(api_key, article_content, dictionary_file="dictionary.txt", prompt_file="prompt.txt"):
"""處理文章,將結果送給 Google AI 並返回回應。"""
try:
genai.configure(api_key=api_key)
model = genai.GenerativeModel("gemini-1.5-flash")
# 讀取文章檔案內容
if not article_content:
return "Error: No article provided.", "", ""
prompt_template = load_prompt(prompt_file)
if isinstance(prompt_template, str) and prompt_template.startswith("Error:"):
return prompt_template, "", ""
dictionary_data = load_dictionary(dictionary_file)
if isinstance(dictionary_data, str) and dictionary_data.startswith("Error:"):
return dictionary_data, "", ""
prompt = prompt_template.format(article=article_content)
response = model.generate_content(prompt)
token_text = response.text # 保存原始斷詞結果
modified_article = response.text
report = []
for item in dictionary_data:
if 'usecase' in item and 'original' in item and 'modified' in item:
original = item['original']
modified = item['modified']
for usecase_word in item['usecase']:
while usecase_word in modified_article:
modified_article = re.sub(re.escape(usecase_word), usecase_word.replace(original, modified), modified_article, 1) # 只替換第一次出現
report.append({"original": original, "modified": modified, "word": usecase_word})
modified_article = modified_article.replace('^', '')
#return modified_article, json.dumps(report, ensure_ascii=False, indent=2), token_text # 返回結果和報告
return modified_article, json.dumps(report, ensure_ascii=False, indent=2), token_text
except Exception as e:
print(f"Error generating content: {e}")
return f"Error: An unexpected error occurred: {e}", "", ""
iface = gr.Interface(
fn=process_article,
inputs=[
gr.Textbox(label="請貼上 Google AI API 金鑰"),
gr.Textbox(label="請輸入需修改的文本"),
],
outputs=[
gr.Textbox(label="處理後的文章"),
gr.Textbox(label="處理過的詞彙 (JSON)"),
gr.Textbox(label="斷詞結果"),
],
title="多音字替換",
description="請輸入文章文本,並獲得 Google AI 的斷詞結果、處理後的文章和詞彙處理報告。",
)
if __name__ == "__main__":
iface.launch() |