import gradio as gr
import pandas as pd
import io
def analyze_excel(file, target_low, low_min, low_max, target_high, high_min, high_max, dwell_time, sample_interval_min):
if file is None or None in [target_low, low_min, low_max, target_high, high_min, high_max]:
return pd.DataFrame(), "請先上傳 Excel 檔案並確認欄位已填寫!"
try:
if hasattr(file, "name"):
file_path_or_bytes = file.name
else:
file_path_or_bytes = io.BytesIO(file)
try:
df_raw = pd.read_excel(file_path_or_bytes, header=None)
except Exception:
df_raw = pd.read_csv(file_path_or_bytes, header=None)
header_idx = None
for idx, row in df_raw.iterrows():
row_str_list = [str(val) for val in row.values]
if any('Date' in s for s in row_str_list) and any('Time' in s for s in row_str_list):
header_idx = idx
break
if header_idx is None:
return pd.DataFrame(), "❌ 找不到 'Date' 或 'Time' 欄位,請確認檔案格式!"
headers = df_raw.iloc[header_idx].values
clean_headers = []
for i, h in enumerate(headers):
h_str = str(h).strip()
if pd.isna(h) or h_str in ['nan', 'None', '']:
clean_headers.append(f"Col_{i}")
else:
clean_headers.append(h_str)
data = df_raw.iloc[header_idx + 1:].copy().reset_index(drop=True)
data.columns = clean_headers
temp_cols = [col for col in clean_headers if col not in ['Date', 'Time'] and not col.startswith('Col_')]
if not temp_cols:
return pd.DataFrame(), "❌ 未找到有效的溫度 Channel 欄位!"
for col in temp_cols:
data[col] = pd.to_numeric(data[col], errors='coerce')
matched_indices = []
low_min_f, low_max_f = float(low_min), float(low_max)
high_min_f, high_max_f = float(high_min), float(high_max)
for idx, row in data[temp_cols].iterrows():
vals = [v for v in row.values if pd.notna(v) and isinstance(v, (int, float))]
in_low = any(low_min_f <= v <= low_max_f for v in vals)
in_high = any(high_min_f <= v <= high_max_f for v in vals)
if in_low or in_high:
matched_indices.append(idx)
filtered_df = data.loc[matched_indices].copy()
filtered_df = filtered_df.fillna("")
status_msg = f"✅ 分析成功!共撈出 {len(filtered_df)} 筆符合高低溫區間的數據。"
return filtered_df, status_msg
except Exception as e:
return pd.DataFrame(), f"❌ 處理時發生錯誤:{str(e)}"
with gr.Blocks(title="Thermal Cycle 熱循環數據分析工具") as demo:
gr.Markdown("## 🌡️ Thermal Cycle 熱循環數據分析工具")
with gr.Row():
file_input = gr.File(label="上傳 Excel 或 CSV 檔案", file_types=[".xlsx", ".xls", ".csv"])
gr.Markdown("### ⚙️ 溫度條件設定")
with gr.Row():
target_low_input = gr.Number(label="低溫設定目標", value=-40)
low_min_input = gr.Number(label="低溫下限值", value=-47)
low_max_input = gr.Number(label="低溫上限值", value=-37)
with gr.Row():
target_high_input = gr.Number(label="高溫設定目標", value=100)
high_min_input = gr.Number(label="高溫下限值", value=97)
high_max_input = gr.Number(label="高溫上限值", value=103)
with gr.Row():
dwell_time_input = gr.Number(label="持溫時間 (min)", value=30)
sample_interval_input = gr.Number(label="採樣間隔 (min)", value=1)
status_output = gr.Textbox(label="執行狀態", interactive=False)
gr.Markdown("### 🔍 極限溫度過濾結果資料表")
table_output = gr.Dataframe(label="符合條件的數據明細", interactive=False)
inputs = [
file_input,
target_low_input, low_min_input, low_max_input,
target_high_input, high_min_input, high_max_input,
dwell_time_input, sample_interval_input
]
for inp in inputs:
inp.change(fn=analyze_excel, inputs=inputs, outputs=[table_output, status_output])
demo.launch()