Spaces:
Runtime error
Runtime error
Upload 3 files
Browse filesFiles changed (3)
- index.htmlAdded+44
- script.jsAdded+174
- style.cssAdded+232
1234567891011121314151617181920212223242526272829303132333435363738394041424344<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>預測詐騙訊息</title>
<link rel="stylesheet" href="style.css"><!-- 引入外部 CSS 樣式 -->
<script src="script.js"></script> <!-- 引入 JavaScript 檔案 -->
</head>
<body>
<h1>檢查可疑訊息</h1><!-- <h1>字體最大標題,最小<h6>-->
<div class="main-container">
<!-- 使用者輸入區塊。textarea文字輸入的區塊。placeholder文字尚未輸入時,預設的顯示內容,無法在網頁端編輯。maxlength限制最大自數-->
<section id="input_area" class="panel">
<textarea id="predict_info" placeholder="請輸入內容 (最多5000字)" maxlength="5000" ></textarea>
<div class="button-group">
<button id="detect_button" type="submit">檢測</button><!---->
<button id="clear_button" type="reset">清除</button>
<!-- 圖片上傳與檢測功能 -->
<div class="image-upload-group" style="margin-top: 20px;">
<label for="imageInput">或上傳圖片進行詐騙檢測:</label><br>
<input type="file" id="imageInput" accept="image/*" />
<button id="image_button" type="button" style="margin-left: 10px;">圖片檢測</button>
</div>
</div>
</section>
<!-- 顯示模型預測結果的區塊 -->
<section id="output_area" class="panel">
<h2>檢測結果</h2>
<!--<p>是一般的文字標籤。<strong>包住的文字會變粗體</strong>。span行內元素(inline),這裡用途顯示後端輸出內容-->
<p><strong>是否為詐騙訊息:</strong> <span id="is_scam">待檢測</span></p>
<p><strong>模型預測可疑度:</strong> <span id="confidence_score">待檢測</span></p>
<p><strong>可疑詞句分析:</strong></p>
<div id="suspicious_phrases"><!--div和span一樣功用,差別在div能自動換行-->
<p>請輸入訊息並點擊「檢測」按鈕。</p>
</div>
</section>
</div>
</body>
</html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174// frontend/script.js
// 當 DOM (文件物件模型) 完全載入後才執行裡面的程式碼
document.addEventListener('DOMContentLoaded', () => {
// 取得 HTML 元素:輸入、按鈕、顯示區塊。document.getElementById('對應的html元素id')
const inputTextArea = document.getElementById('predict_info'); // 輸入訊息的文字區域
const inputButton = document.getElementById('detect_button'); // 檢測按鈕
const clearButton = document.getElementById('clear_button'); // 清除按鈕
// 取得圖片上傳欄位與圖片按鈕
const imageInput = document.getElementById('imageInput');
const imageButton = document.getElementById('image_button');
// 取得顯示結果的 HTML 元素
const normalOrScam = document.getElementById('is_scam'); // 顯示正常或詐騙
const confidenceScoreSpan = document.getElementById('confidence_score'); // 顯示模型預測可信度
const suspiciousPhrasesDiv = document.getElementById('suspicious_phrases'); // 顯示可疑詞句列表
/*
後端 FastAPI API 的 URL
在開發階段,通常是 http://127.0.0.1:8000 或 http://localhost:8000
請根據你實際運行 FastAPI 的位址和 Port 進行設定
*/
const API_URL = "http://127.0.0.1:8000/predict";
const API_IMAGE_URL = "http://127.0.0.1:8000/predict-image"
// --- 檢測按鈕點擊事件監聽器 ---
// 當檢測按鈕被點擊時,執行非同步函數
//addEventListener('click', async () => {...})
// click 是一種 DOM 事件,代表使用者點擊按鈕。
// async 是「非同步函數」的關鍵字,允許你在函數中使用 await。它讓你可以像同步一樣撰寫非同步程式(例如網路請求)。
inputButton.addEventListener('click', async () => {
const message = inputTextArea.value.trim(); //.value取得<textarea>的輸入內容。
//.trim()刪掉文字開頭和結尾的空白,避免誤判空訊息。
// 檢查輸入框是否為空
if (message.length === 0) {//alert("輸出內容")是瀏覽器內建的彈出提示。視窗屬於 JavaScript 提供的「視覺提示方法」
alert('請輸入您想檢測的訊息內容。'); // alert彈出提示
return; // 終止函數執行
}
// 顯示載入中的狀態,給使用者視覺回饋
normalOrScam.textContent = '檢測中...'; //.textContent->插入純文字
normalOrScam.style.color = 'gray'; //styly.color改變顏色,style可以想為UI設計
confidenceScoreSpan.textContent = '計算中...';//.innerHTML->插入 HTML 語法
suspiciousPhrasesDiv.innerHTML = '<p>正在分析訊息,請稍候...</p>';//<></>大部分html語法長這樣
try {//try...catch處理程式錯誤。
//fetch(API_URL, {...})。API_URL第17段的變數。method:為html方法,POST送出請求。headers告訴伺服器傳送的資料格式是什麼。
//這段是用 fetch 來呼叫後端 API,送出 POST 請求:
const response = await fetch(API_URL, {
method: 'POST', // 指定 HTTP 方法為 POST
headers: { // 告訴伺服器發送的資料是 JSON 格式。選JSON原因:
//我們使用前端(JavaScript)與後端(Python FastAPI)是兩種不同的語言,而JSON是前後端通訊的「共通語言」,交換最通用、最方便、最安全的格式。
'Content-Type': 'application/json'
},
//把JavaScript物件{text:message}轉換成JSON格式字串,字串作為請求的主體 (body)
body: JSON.stringify({ text: message}),
});
// 檢查 HTTP 回應是否成功 (例如:狀態碼 200 OK)
if (!response.ok) { // 如果回應狀態碼不是 2xx (成功),則拋出錯誤
//建立一個錯誤對象並丟出來,強制跳到catch{}區塊。response.status:HTTP狀態碼(如500)。
throw new Error(`伺服器錯誤: ${response.status} ${response.statusText} `);
}
// 變數data,儲存後端成功回傳的資料。
const data = await response.json();
// 因為後端回傳的欄位名稱status、confidence、suspicious_keywords跟傳進去的參數一致,所以拿的到後端回傳的資料。
updateResults( //呼叫function,分別對應function的
data.status, //isScam,輸出正常或詐騙
data.confidence, //confidence,輸出信心值
data.suspicious_keywords,//suspiciousParts,可疑關鍵字
data.highlighted_text
);
} catch (error) {// 捕獲並處理任何在 fetch 過程中發生的錯誤 (例如網路問題、CORS 錯誤)
console.error('訊息檢測失敗:', error);// 在開發者工具的控制台顯示錯誤
alert(`訊息檢測失敗,請檢查後端服務是否運行或網路連線。\n錯誤詳情: ${error.message}`); // 彈出錯誤提示
resetResults(); // 將介面恢復到初始狀態
}
});
imageButton.addEventListener('click', async()=>{
const file = imageInput.files[0]; //取得上傳相片
if (!file){
alert("請先選擇圖片");
return;
}
// 顯示載入中提示
normalOrScam.textContent = '圖片分析中...';
normalOrScam.style.color = 'gray';
confidenceScoreSpan.textContent = '計算中...';
suspiciousPhrasesDiv.innerHTML = '<p>正在從圖片擷取文字與分析中...</p>';
try{
const formData = new FormData();
formData.append("file", file); // 附加圖片檔案給後端
const response = await fetch(API_IMAGE_URL,{
method : "POST",
body : formData
});
if (!response.ok){
throw new Error(`圖片分析失敗: ${response.status} ${response.statusText}`);
}
const data = await response.json();
updateResults(
data.status,
data.confidence,
data.suspicious_keywords,
data.highlighted_text
)
}catch(error) {
console.error("圖片上傳失敗",error);
alert("圖片分析失敗")
resetResults();
}
});
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/*
function highlightSuspiciousWords(text, suspiciousParts) {
let highlighted = text;
suspiciousParts.forEach(word => {
if (word.length < 2) return; // 避免標記太短詞(如單個字或符號)
const pattern = new RegExp(escapeRegExp(word), 'g');
highlighted = highlighted.replace(pattern, `<span class="highlight">${word}</span>`);
});
return highlighted;
}
*/
// --- 清除按鈕點擊事件監聽器 ---
// 當清除按鈕被點擊時,執行函數
clearButton.addEventListener('click', () => {
inputTextArea.value = '';// 清空輸入框內容
resetResults(); // 重置顯示結果
});
// --- 清除按鈕點擊事件監聽器 ---
// 當清除按鈕被點擊時,執行函數
clearButton.addEventListener('click', () => {
inputTextArea.value = '';// 清空輸入框內容
resetResults(); // 重置顯示結果
});
/**這是 JSDoc 註解格式,給開發者與編輯器看的,不會執行。
* 更新結果顯示的輔助函數
* @param {string} isScam - 是否為詐騙訊息 (從後端獲取)(原始要得"@"param {string} isScam )
* @param {number} confidence - 模型預測可信度 (從後端獲取)
* @param {string[]} suspiciousParts - 可疑詞句陣列 (從後端獲取)
*/
//回傳輸出給index.html顯示
function updateResults(isScam, confidence, suspiciousParts, highlightedText) {
normalOrScam.textContent = isScam;
confidenceScoreSpan.textContent = confidence;
if (confidence < 15) {
suspiciousPhrasesDiv.innerHTML = '<p>此訊息為低風險,未發現可疑詞句。</p>';
} else {
suspiciousPhrasesDiv.innerHTML = highlightedText;
}
}
/**
* 重置所有顯示結果為初始狀態的輔助函數
*/
function resetResults() {
normalOrScam.textContent = '待檢測';
normalOrScam.style.color = 'inherit'; // 恢復預設顏色
confidenceScoreSpan.textContent = '待檢測';
suspiciousPhrasesDiv.innerHTML = '<p>請輸入訊息並點擊「檢測!」按鈕。</p>';
}
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232/* style.css */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0; /* 將 body 的 margin 設為 0,讓內容可以更貼近邊緣 */
padding: 20px; /* 內邊距留點空間 */
background-color: #f4f7f6;
color: #333;
line-height: 1.6;
display: flex; /* 讓 body 成為 flex 容器 */
flex-direction: column; /* 內容垂直排列 */
min-height: 100vh; /* 讓 body 至少佔滿整個視窗高度 */
align-items: center; /* 讓 h1 居中 */
}
.highlight {
background-color: #fc9c9cd5;
color: #000000;
font-weight: bold;
padding: 2px 4px;
border-radius: 4px;
}
.yellow-highlight {
background-color: #ffeb3b85; /* 半透明黃色 */
color: #000000;
font-weight: bold;
padding: 2px 4px;
border-radius: 4px;
}
.red-highlight {
background-color: #fc9c9cd5;
color: #000000;
font-weight: bold;
padding: 2px 4px;
border-radius: 4px;
}
h1 {
color: #2c3e50;
text-align: center;
margin-bottom: 30px; /* 增加標題下方的間距 */
font-size: 2.5em; /* 讓標題更大一點 */
}
h2 { /* 針對檢測結果的 h2 */
color: #2c3e50;
text-align: center;
margin-top: 0; /* 移除頂部 margin,讓它更靠近 panel 頂部 */
margin-bottom: 20px;
font-size: 1.8em;
}
/* --- 主容器 Flexbox 佈局 --- */
.main-container {
display: flex; /* 啟用 Flexbox */
flex-direction: row; /* 預設就是 row,讓子元素水平排列 */
gap: 30px; /* 左右兩個 panel 之間的間距 */
width: 100%; /* 佔滿可用寬度 */
max-width: 1200px; /* 設定最大寬度,避免在寬螢幕上過於分散 */
justify-content: center; /* 內容居中 */
flex-wrap: wrap; /* 當螢幕太小時,允許換行 */
}
.panel {
background-color: #ffffff;
padding: 30px; /* 增加內邊距 */
border-radius: 8px;
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1); /* 更明顯的陰影 */
flex: 1; /* 讓兩個 panel 平均分配空間 */
min-width: 380px; /* 設定每個 panel 的最小寬度,避免縮得太小 */
box-sizing: border-box; /* 確保 padding 和 border 不會增加元素總寬度 */
display: flex; /* 讓 panel 內部內容也是 flex 容器 */
flex-direction: column; /* 內部內容垂直排列 */
}
#input_area {
/* 特定於 input_area 的樣式,如果需要 */
align-items: center; /* 讓輸入框和按鈕在 input_area 中居中 */
}
textarea {
width: 100%; /* 佔滿 panel 寬度 */
height: 250px; /* 增加高度 */
padding: 15px;
margin-bottom: 25px; /* 增加與按鈕的間距 */
border: 1px solid #ddd;
border-radius: 5px;
font-size: 1.1rem; /* 稍微放大字體 */
box-sizing: border-box;
resize: vertical;
outline: none; /* 移除 focus 時的藍色邊框 */
transition: border-color 0.3s ease;
}
textarea:focus {
border-color: #4CAF50; /* focus 時邊框變色 */
}
.button-group {
display: flex;
gap: 20px; /* 按鈕間距 */
justify-content: center; /* 按鈕在 group 內部居中 */
width: 100%; /* 佔滿寬度 */
}
button {
padding: 12px 30px; /* 稍微增加按鈕大小 */
font-size: 1.1rem;
cursor: pointer;
border: none;
border-radius: 5px;
transition: background-color 0.3s ease, transform 0.2s ease; /* 增加 transform 過渡效果 */
font-weight: bold; /* 字體加粗 */
}
button[type="submit"] {
background-color: #4CAF50;
color: white;
}
button[type="submit"]:hover {
background-color: #45a049;
transform: translateY(-2px); /* 懸停時向上輕微移動 */
}
button[type="reset"] {
background-color: #f44336;
color: white;
}
button[type="reset"]:hover {
background-color: #da190b;
transform: translateY(-2px);
}
#output_area p {
font-size: 1.15rem; /* 稍微放大結果文字 */
margin-bottom: 12px;
}
#output_area strong {
color: #555;
font-weight: bold;
}
#is_scam, #confidence_score {
font-weight: bold; /* 結果狀態字體加粗 */
}
#suspicious_phrases {
background-color: #fffafa; /* 給可疑詞句區塊一個淺色背景 */
border: 1px dashed #e0baba; /* 虛線邊框 */
padding: 15px;
border-radius: 5px;
margin-top: 15px;
min-height: 80px; /* 確保高度,避免內容少時高度變化 */
}
#suspicious_phrases ul {
list-style-type: '🚨 '; /* 使用表情符號作為列表標記 */
padding-left: 20px;
margin: 0; /* 移除預設 margin */
}
#suspicious_phrases li {
margin-bottom: 8px;
color: #c0392b;
font-weight: 500;
}
#suspicious_phrases p {
font-style: italic;
color: #666;
margin: 0; /* 移除預設 margin */
}
label[for="modeSelect"] {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: #495057;
font-size: 15px;
}
#modeSelect {
width: 100%;
padding: 10px;
font-size: 15px;
border-radius: 6px;
border: 1px solid #adb5bd;
background-color: #ffffff;
margin-bottom: 20px;
transition: 0.2s;
}
#modeSelect:focus {
border-color: #74c0fc;
box-shadow: 0 0 0 0.1rem rgba(116, 192, 252, 0.25);
outline: none;
}
/* --- 響應式設計:當螢幕較小時,垂直排列 --- */
@media (max-width: 768px) {
.main-container {
flex-direction: column; /* 小螢幕時改為垂直堆疊 */
gap: 20px; /* 垂直間距 */
padding: 0 15px; /* 左右邊距 */
}
.panel {
flex: none; /* 取消 flex 比例,讓他們各自佔據 100% 寬度 */
width: 100%;
max-width: none; /* 移除最大寬度限制 */
}
h1 {
font-size: 2em;
}
h2 {
font-size: 1.5em;
}
textarea {
height: 200px;
}
}index.htmlAdded+44
script.jsAdded+174
style.cssAdded+232