import gradio as gr
import pandas as pd
import json
import os
import math
import matplotlib.pyplot as plt
from datetime import datetime
# --- 系統變數與檔案設定 ---
COMPANY_NAME = "RZF Laser Tech"
CONFIG_JSON = "rzf_config.json"
ORDERS_CSV = "rzf_orders.csv"
DEFAULT_WAVELENGTHS = ["650nm", "532nm", "405nm", "850nm"]
# --- 1. 核心邏輯與計算函數 ---
def load_rzf_config():
if os.path.exists(CONFIG_JSON):
try:
with open(CONFIG_JSON, "r", encoding="utf-8") as f:
data = json.load(f)
return data.get("wavelengths", DEFAULT_WAVELENGTHS)
except:
return DEFAULT_WAVELENGTHS
return DEFAULT_WAVELENGTHS
def save_rzf_config(w_list):
with open(CONFIG_JSON, "w", encoding="utf-8") as f:
json.dump({"company": COMPANY_NAME, "wavelengths": w_list, "last_update": str(datetime.now())}, f, indent=4, ensure_ascii=False)
# 獲取訂單報表資料
def get_order_data():
if os.path.exists(ORDERS_CSV):
try:
return pd.read_csv(ORDERS_CSV, encoding="utf-8-sig")
except:
return pd.DataFrame({"錯誤": ["無法讀取 CSV 檔案"]})
return pd.DataFrame(columns=["提示"], data=[["目前尚無訂單紀錄"]])
# 獲取備份檔案路徑
def get_backup_files():
files = []
if os.path.exists(ORDERS_CSV): files.append(ORDERS_CSV)
if os.path.exists(CONFIG_JSON): files.append(CONFIG_JSON)
return files
# --- 新增:取得光斑樣式的 SVG 圖示 ---
def get_spot_icon(style):
base_svg = ''
def submit_rzf_order(w, p, s, q, focus, spot, coaxial, ellipse, dim_d, dim_l, wire_m, wire_l, wire_c, connector):
if not w: return "❌ 錯誤:未選取波長規格", "⚠️ 尚未提交有效訂單"
if focus < 0: return "❌ 錯誤:焦距不能為負值!", "⚠️ 尚未提交有效訂單"
new_data = {
"訂單編號": datetime.now().strftime("RZF%Y%m%d%H%M%S"),
"提交時間": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"波長": w, "功率(mW)": p, "光斑樣式": s, "數量": q,
"焦距(mm)": focus, "光點大小/長度": spot, "同軸度(mRad/°)": coaxial, "橢圓率": ellipse,
"機構尺寸(D*L)": f"{dim_d}*{dim_l}", "線材材質": wire_m, "線材長度(mm)": wire_l, "線材顏色": wire_c, "連接器規格": connector
}
df = pd.DataFrame([new_data])
if not os.path.isfile(ORDERS_CSV):
df.to_csv(ORDERS_CSV, index=False, encoding="utf-8-sig")
else:
df.to_csv(ORDERS_CSV, mode='a', index=False, header=False, encoding="utf-8-sig")
order_msg = f"🚀 {COMPANY_NAME} 訂單已受理!\n編號:{new_data['訂單編號']}"
# 產生對應光斑 SVG 圖示
svg_icon = get_spot_icon(s)
# 產生圖文並茂且包含表格的規格說明
spec_summary = f"""
### 📝 最新訂單規格書 (編號:`{new_data['訂單編號']}`)
{svg_icon}
光斑樣式:{s}雷射
中心波長:{w} | 輸出功率:{p} mW
#### 📊 詳細規格參數表
| 參數類別 | 項目名稱 | 規格設定 |
| :--- | :--- | :--- |
| 🔦 **光學核心** | 雷射波長 | **{w}** |
| | 輸出功率 | **{p} mW** |
| | 光斑樣式 | **{s}** |
| | 焦距 | {focus} mm |
| | 光點大小/長度 | {spot} |
| | 同軸度 | {coaxial} |
| | 橢圓率 | {ellipse} |
| 🔩 **機構與線材** | 機構尺寸 (D×L) | {dim_d} × {dim_l} mm |
| | 線材材質 | {wire_m} |
| | 線材長度 | {wire_l} mm |
| | 線材顏色 | {wire_c} |
| | 連接器規格 | {connector if connector else '未指定'} |
| 📦 **訂購資訊** | 訂購數量 | **{q}** |
| | 提交時間 | {new_data['提交時間']} |
"""
return order_msg, spec_summary
# --- 同軸度與繪圖邏輯 ---
def draw_coaxiality_plot(distance, r):
# 將繪圖顯示用的數值改為「度數」
rad = math.atan(r / distance)
deg = math.degrees(rad)
fig, ax = plt.subplots(figsize=(6, 4), dpi=100)
ax.set_title(f"{COMPANY_NAME} - Coaxiality Diagram", fontsize=12)
ax.set_xlim(-0.1 * distance, 1.1 * distance)
ax.set_ylim(-0.2 * r, 1.2 * r)
ax.axis('off')
# 繪製三角形
triangle_coords = [[0, 0], [distance, 0], [distance, r]]
poly = plt.Polygon(triangle_coords, closed=True, facecolor='#F1F8E9', edgecolor='#388E3C', linewidth=2)
ax.add_patch(poly)
# 標註參數
ax.plot([0, distance], [0, r], color='#D32F2F', linestyle='--', linewidth=1.5)
ax.text(distance / 2, -0.1 * r, f"L = {distance:.2f} mm", ha='center', color='#2E7D32')
ax.text(distance * 1.05, r / 2, f"r = {r:.3f} mm", va='center', rotation=90, color='#2E7D32')
# 圖表上的標註改為顯示度數
ax.text(distance * 0.15, r * 0.05, f"θ ≈ {deg:.4f}°", fontsize=11, color='#C62828', fontweight='bold')
plt.tight_layout()
return fig
def calc_angle_from_offset(distance, dist_unit, offset, off_type, off_unit):
if distance <= 0: return "❌ 距離必須大於 0", None, gr.update()
# 統一將測試距離轉換為 mm 計算
if dist_unit == "公分 (cm)":
distance_mm = distance * 10.0
elif dist_unit == "公尺 (m)":
distance_mm = distance * 1000.0
else:
distance_mm = distance
# 統一將偏移量轉換為 mm 計算
offset_mm = offset if off_unit == "毫米 (mm)" else offset / 1000.0
# 半徑直接使用,直徑則除以 2
r = offset_mm if off_type == "半徑 (Radius)" else offset_mm / 2.0
rad = math.atan(r / distance_mm)
deg = math.degrees(rad)
mrad = (r / distance_mm) * 1000
text_result = (
f"### 💡 偏移量計算角度:\n"
f"- 輸入條件: 距離 **{distance} {dist_unit}** ({distance_mm:.2f} mm), 偏移 **{offset} {off_unit}** ({off_type})\n"
f"- 實際半徑偏移 (r): **{r:.4f} mm**\n"
f"- 偏移角度: **{deg:.4f}°**\n"
f"- 同軸度: **{mrad:.4f} mRad**\n\n"
f"*(✨ 同軸度參數已自動同步至「產品訂購」表單!)*"
)
fig = draw_coaxiality_plot(distance_mm, r)
return text_result, fig, f"{mrad:.4f} mRad"
def calc_offset_from_angle(distance, dist_unit, angle, ang_type):
if distance <= 0: return "❌ 距離必須大於 0", None, gr.update()
# 統一將測試距離轉換為 mm 計算
if dist_unit == "公分 (cm)":
distance_mm = distance * 10.0
elif dist_unit == "公尺 (m)":
distance_mm = distance * 1000.0
else:
distance_mm = distance
# 根據角度單位計算半徑長度 (mm)
if ang_type == "mRad":
r = (angle / 1000.0) * distance_mm
mrad = angle
else:
rad = math.radians(angle)
r = math.tan(rad) * distance_mm
mrad = (r / distance_mm) * 1000
diameter = r * 2
# 轉換為 um 方便顯示
r_um = r * 1000
diameter_um = diameter * 1000
text_result = (
f"### 💡 角度計算偏移量:\n"
f"- 輸入條件: 距離 **{distance} {dist_unit}** ({distance_mm:.2f} mm), 角度 **{angle}** ({ang_type})\n"
f"- **半徑長度** (半徑偏移): **{r:.4f} mm** / **{r_um:.2f} µm**\n"
f"- **直徑長度** (直徑偏移): **{diameter:.4f} mm** / **{diameter_um:.2f} µm**\n"
f"- 等效 mRad: **{mrad:.4f} mRad**\n\n"
f"*(✨ 同軸度參數已自動同步至「產品訂購」表單!)*"
)
fig = draw_coaxiality_plot(distance_mm, r)
return text_result, fig, f"{mrad:.4f} mRad"
# --- 光束發散 (Beam Divergence) 邏輯 ---
def calculate_and_plot_divergence(z1, d1, z2, d2, size_type):
if z1 >= z2: return "❌ 錯誤:第二個位置 (z2) 必須大於第一個位置 (z1)", None, gr.update()
if d1 < 0 or d2 < 0: return "❌ 錯誤:光斑尺寸不能為負數", None, gr.update()
delta_L = z2 - z1
# 轉換為半徑 (作為直角三角形的高度)
r1 = d1 if size_type == "半徑 (Radius)" else d1 / 2.0
r2 = d2 if size_type == "半徑 (Radius)" else d2 / 2.0
delta_r = r2 - r1
# 計算半角 (Half-Angle)
half_rad = math.atan(delta_r / delta_L)
half_deg = math.degrees(half_rad)
half_mrad = (delta_r / delta_L) * 1000
# 計算全角 (Full-Angle)
full_rad = half_rad * 2
full_deg = half_deg * 2
full_mrad = half_mrad * 2
# 結果文字
text_result = (
f"### 💡 光束發散計算結果:\n"
f"- 測量距離差 (${{\\Delta L}}$): **{delta_L:.2f} mm**\n"
f"- 半徑尺寸差 (${{\\Delta r}}$): **{delta_r:.4f} mm**\n\n"
f"#### 📐 角度結果\n"
f"- **半角發散 (Half-Angle, ${{\\theta/2}}$)**: **{half_deg:.4f}°** / **{half_mrad:.4f} mRad**\n"
f"- **全角發散 (Full-Angle, ${{\\theta}}$)**: **{full_deg:.4f}°** / **{full_mrad:.4f} mRad**\n\n"
f"*(✨ 光點大小已自動同步至「產品訂購」表單!)*"
)
# 繪製圖表
fig, ax = plt.subplots(figsize=(6, 4), dpi=100)
ax.set_title(f"{COMPANY_NAME} - Beam Divergence", fontsize=12)
# 繪製光束形狀 (多邊形)
beam_coords = [[z1, r1], [z2, r2], [z2, -r2], [z1, -r1]]
poly = plt.Polygon(beam_coords, closed=True, facecolor='#FFF9C4', edgecolor='#FBC02D', linewidth=2, alpha=0.6)
ax.add_patch(poly)
# 畫中心線
ax.plot([z1 - delta_L*0.1, z2 + delta_L*0.1], [0, 0], color='#9E9E9E', linestyle='-.', linewidth=1)
# 標註參數
ax.plot([z1, z1], [-r1, r1], color='#1976D2', linewidth=2)
ax.plot([z2, z2], [-r2, r2], color='#1976D2', linewidth=2)
ax.text(z1, r1 * 1.1 + 0.1, f"size 1: {d1}", ha='center', color='#1976D2', fontsize=9)
ax.text(z2, r2 * 1.1 + 0.1, f"size 2: {d2}", ha='center', color='#1976D2', fontsize=9)
# 標註距離長度 (加入絕對偏移量與 va='top' 避免與標示線重疊)
dim_y = -max(r1, r2) * 1.2 - 0.2
ax.plot([z1, z2], [dim_y, dim_y], color='#555', linestyle='-', linewidth=1)
ax.plot([z1, z1], [dim_y + 0.1, dim_y - 0.1], color='#555', linewidth=1)
ax.plot([z2, z2], [dim_y + 0.1, dim_y - 0.1], color='#555', linewidth=1)
ax.text((z1 + z2) / 2, dim_y - 0.1, f"ΔL = {delta_L:.1f} mm", ha='center', va='top', color='#555')
# 標註角度 (顯示全角與 mRad)
ax.text(z2 * 1.02, r2 / 2, f"Θ ≈ {full_deg:.4f}°\n({full_mrad:.4f} mRad)", color='#D32F2F', fontweight='bold', fontsize=11)
# 調整圖表邊界
ax.set_xlim(z1 - delta_L*0.2, z2 + delta_L*0.3)
ax.set_ylim(dim_y - 0.8, max(r1, r2)*1.5 + 0.5)
ax.axis('off')
plt.tight_layout()
return text_result, fig, str(d2)
# --- 光束焦距收斂 (Focus Beam Divergence) 邏輯 ---
def calculate_and_plot_focus_divergence(focal_length, dist_unit, d1, d2, spot_unit, size_type):
if focal_length <= 0: return "❌ 錯誤:焦距必須大於 0", None, gr.update(), gr.update()
if d1 < 0 or d2 < 0: return "❌ 錯誤:光斑尺寸不能為負數", None, gr.update(), gr.update()
# 單位轉換至 mm
focal_length_mm = focal_length * 10.0 if dist_unit == "公分 (cm)" else (focal_length * 1000.0 if dist_unit == "公尺 (m)" else focal_length)
# 將光斑尺寸統一轉換至 mm
d1_mm = d1 if spot_unit == "毫米 (mm)" else d1 / 1000.0
d2_mm = d2 if spot_unit == "毫米 (mm)" else d2 / 1000.0
# 轉換為半徑 (作為直角三角形的高度)
r1 = d1_mm if size_type == "半徑 (Radius)" else d1_mm / 2.0
r2 = d2_mm if size_type == "半徑 (Radius)" else d2_mm / 2.0
delta_r = r1 - r2
# 計算半角 (Half-Angle)
half_rad = math.atan(delta_r / focal_length_mm)
half_deg = math.degrees(half_rad)
half_mrad = (delta_r / focal_length_mm) * 1000
# 計算全角 (Full-Angle)
full_rad = half_rad * 2
full_deg = half_deg * 2
full_mrad = half_mrad * 2
# 結果文字
unit_label = "mm" if spot_unit == "毫米 (mm)" else "µm"
text_result = (
f"### 💡 光束焦距收斂計算結果:\n"
f"- 焦距 ($L$): **{focal_length_mm:.2f} mm**\n"
f"- 雷射出光半徑 ($r_1$): **{r1:.4f} mm**\n"
f"- 焦距光斑半徑 ($r_2$): **{r2:.4f} mm**\n"
f"- 半徑收斂差 ($r_1 - r_2$): **{delta_r:.4f} mm**\n\n"
f"#### 📐 收斂角度結果\n"
f"- **半收斂角 (Half-Angle, ${{\\theta/2}}$)**: **{half_deg:.4f}°** / **{half_mrad:.4f} mRad**\n"
f"- **全收斂角 (Full-Angle, ${{\\theta}}$)**: **{full_deg:.4f}°** / **{full_mrad:.4f} mRad**\n\n"
f"*(✨ 焦距與光點大小已自動同步至「產品訂購」表單!)*"
)
# 繪製圖表
fig, ax = plt.subplots(figsize=(6, 4), dpi=100)
ax.set_title(f"{COMPANY_NAME} - Focus Beam Convergence", fontsize=12)
# 繪製光束形狀 (多邊形)
beam_coords = [[0, r1], [focal_length_mm, r2], [focal_length_mm, -r2], [0, -r1]]
poly = plt.Polygon(beam_coords, closed=True, facecolor='#E3F2FD', edgecolor='#1976D2', linewidth=2, alpha=0.6)
ax.add_patch(poly)
# 畫中心線
ax.plot([-focal_length_mm*0.1, focal_length_mm*1.1], [0, 0], color='#9E9E9E', linestyle='-.', linewidth=1)
# 標註參數 (避免使用中文體,解決伺服器顯示框框的問題)
ax.plot([0, 0], [-r1, r1], color='#388E3C', linewidth=2)
ax.plot([focal_length_mm, focal_length_mm], [-r2, r2], color='#388E3C', linewidth=2)
ax.text(0, r1 * 1.1 + 0.1, f"d1: {d1} {unit_label}", ha='center', color='#388E3C', fontsize=9)
ax.text(focal_length_mm, r2 * 1.1 + 0.1, f"d2: {d2} {unit_label}", ha='center', color='#388E3C', fontsize=9)
# 標註焦距長度 (加入絕對偏移量與 va='top' 避免與標示線重疊)
dim_y = -max(r1, r2) * 1.2 - 0.2
ax.plot([0, focal_length_mm], [dim_y, dim_y], color='#555', linestyle='-', linewidth=1)
ax.plot([0, 0], [dim_y + 0.1, dim_y - 0.1], color='#555', linewidth=1)
ax.plot([focal_length_mm, focal_length_mm], [dim_y + 0.1, dim_y - 0.1], color='#555', linewidth=1)
ax.text(focal_length_mm / 2, dim_y - 0.1, f"L = {focal_length_mm:.1f} mm", ha='center', va='top', color='#555')
# 標註角度 (顯示全角與 mRad)
ax.text(focal_length_mm * 1.05, 0, f"Θ ≈ {full_deg:.4f}°\n({full_mrad:.4f} mRad)", color='#1976D2', fontweight='bold', fontsize=11, va='center')
# 調整圖表邊界,確保下方的文字 L 不會被切除
ax.set_xlim(-focal_length_mm*0.1, focal_length_mm*1.3)
ax.set_ylim(dim_y - 0.8, max(r1, r2)*1.5 + 0.5)
ax.axis('off')
plt.tight_layout()
# 將轉換為 mm 的結果轉為字串並回填表單
d2_sync_str = f"{d2_mm:g} mm"
return text_result, fig, round(focal_length_mm, 2), d2_sync_str
# --- 線光斑長度與角度 (Line Laser Angle) 邏輯 ---
def calculate_and_plot_line_angle(distance, dist_unit, line_length, length_unit):
if distance <= 0: return "❌ 錯誤:距離必須大於 0", None, gr.update(), gr.update()
if line_length < 0: return "❌ 錯誤:線長不能為負數", None, gr.update(), gr.update()
# 單位轉換至 mm
dist_mm = distance * 10.0 if dist_unit == "公分 (cm)" else (distance * 1000.0 if dist_unit == "公尺 (m)" else distance)
len_mm = line_length * 10.0 if length_unit == "公分 (cm)" else (line_length * 1000.0 if length_unit == "公尺 (m)" else line_length)
# 半線長
half_l = len_mm / 2.0
# 計算半角
half_rad = math.atan(half_l / dist_mm)
half_deg = math.degrees(half_rad)
# 計算全角
full_deg = half_deg * 2
text_result = (
f"### 💡 線斑角度計算結果:\n"
f"- 測試距離 ($L$): **{dist_mm:.2f} mm**\n"
f"- 線光斑總長 ($l$): **{len_mm:.2f} mm**\n"
f"- 半線長 ($l/2$): **{half_l:.2f} mm**\n\n"
f"#### 📐 發散角度結果\n"
f"- **半角 (Half-Angle, ${{\\theta/2}}$)**: **{half_deg:.4f}°**\n"
f"- **發散全角 (Full-Angle, ${{\\theta}}$)**: **{full_deg:.4f}°**\n\n"
f"*(✨ 光斑樣式、尺寸與角度已自動同步至「產品訂購」表單!)*"
)
# 繪製圖表
fig, ax = plt.subplots(figsize=(6, 4), dpi=100)
ax.set_title(f"{COMPANY_NAME} - Line Laser Angle", fontsize=12)
# 繪製等腰三角形 (模擬線光斑展開)
triangle_coords = [[0, 0], [dist_mm, half_l], [dist_mm, -half_l]]
poly = plt.Polygon(triangle_coords, closed=True, facecolor='#FFEBEE', edgecolor='#D32F2F', linewidth=2, alpha=0.6)
ax.add_patch(poly)
# 中心線
ax.plot([0, dist_mm*1.1], [0, 0], color='#9E9E9E', linestyle='-.', linewidth=1)
# 標註雷射光線 (紅線)
ax.plot([dist_mm, dist_mm], [-half_l, half_l], color='#B71C1C', linewidth=3)
# 文字標註
ax.text(dist_mm / 2, -half_l * 0.1, f"L = {dist_mm:.1f} mm", ha='center', va='top', color='#424242')
ax.text(dist_mm * 1.05, 0, f"l = {len_mm:.1f} mm", va='center', rotation=90, color='#B71C1C')
ax.text(dist_mm * 0.15, half_l * 0.05, f"Θ ≈ {full_deg:.2f}°", fontsize=11, color='#D32F2F', fontweight='bold')
# 動態調整邊界避免圖形過於狹長被裁切
y_limit = max(half_l, dist_mm * 0.2) * 1.2
ax.set_xlim(-0.1 * dist_mm, 1.3 * dist_mm)
ax.set_ylim(-y_limit, y_limit)
ax.axis('off')
plt.tight_layout()
# 回傳光斑樣式「線狀」與光點大小「長度 mm (角度°)」以供連動
return text_result, fig, "線狀", f"{len_mm:.2f} mm ({full_deg:.2f}°)"
# --- 更新輸入框標籤函數 ---
def update_offset_label(unit):
if unit == "毫米 (mm)":
return gr.update(label="光斑偏移量 (mm)")
else:
return gr.update(label="光斑偏移量 (um)")
def update_dist_label(unit):
if unit == "公分 (cm)":
return gr.update(label="測試距離 L (cm)")
elif unit == "公尺 (m)":
return gr.update(label="測試距離 L (m)")
else:
return gr.update(label="測試距離 L (mm)")
def update_focal_label(unit):
if unit == "公分 (cm)":
return gr.update(label="焦距長度 (cm)")
elif unit == "公尺 (m)":
return gr.update(label="焦距長度 (m)")
else:
return gr.update(label="焦距長度 (mm)")
def update_focus_spot_labels(unit):
if unit == "毫米 (mm)":
return gr.update(label="雷射出光尺寸 d1 (mm)"), gr.update(label="焦距光斑尺寸 d2 (mm)")
else:
return gr.update(label="雷射出光尺寸 d1 (um)"), gr.update(label="焦距光斑尺寸 d2 (um)")
def update_line_length_label(unit):
if unit == "公分 (cm)":
return gr.update(label="線光斑長度 l (cm)")
elif unit == "公尺 (m)":
return gr.update(label="線光斑長度 l (m)")
else:
return gr.update(label="線光斑長度 l (mm)")
# --- 新增:動態切換光點大小/光線長度標籤 ---
def update_spot_input_label(style):
if style in ["線狀", "十字線"]:
return gr.update(label="光線長度")
else:
return gr.update(label="光點大小")
# --- 2. Gradio 介面設計 ---
init_ws = load_rzf_config()
with gr.Blocks(title=COMPANY_NAME) as demo:
ws_state = gr.State(init_ws)
gr.Markdown(f"# 🛰️ {COMPANY_NAME} 專業系統")
with gr.Tab("🛒 產品訂購"):
with gr.Row():
with gr.Column():
gr.Markdown("### 🔦 光學核心參數")
w_select = gr.Dropdown(choices=init_ws, label="雷射波長", value=init_ws[0] if init_ws else None)
p_slider = gr.Slider(1, 1000, label="輸出功率 (mW)", value=5)
s_radio = gr.Radio(["點狀", "線狀", "十字線", "DOE"], label="光斑樣式", value="點狀")
with gr.Row():
focus_in = gr.Number(label="焦距 (mm)", value=0)
spot_in = gr.Textbox(label="光點大小") # 標籤會動態改變
with gr.Row():
coaxial_in = gr.Dropdown(choices=["≤ 1 mRad", "≤ 3 mRad", "≤ 5 mRad", "≤ 8 mRad", "≤ 10 mRad"], label="同軸度 (mRad/°)", value="≤ 3 mRad", allow_custom_value=True)
ellipse_in = gr.Textbox(label="橢圓率", value="0")
with gr.Column():
gr.Markdown("### 🔩 機構與線材規格")
with gr.Row(): dim_d = gr.Number(label="直徑", value=10); dim_l = gr.Number(label="長度", value=30)
wire_m = gr.Dropdown(["PVC", "矽膠線", "鐵氟龍線"], label="材質", value="PVC")
with gr.Row(): wire_l = gr.Number(label="長度(mm)", value=100); wire_c = gr.ColorPicker(label="顏色", value="#FF0000")
connector = gr.Textbox(label="連接器規格"); q_input = gr.Number(label="數量", value=1)
submit_btn = gr.Button("✅ 提交 RZF 訂單", variant="primary")
order_status = gr.Textbox(label="通知", interactive=False)
with gr.Tab("🎯 光束焦距收斂計算"):
gr.Markdown(r"""## 🎯 計算焦距光斑收斂角度 (Focus Beam Convergence)""")
# 加入焦距光斑雷射模組示意圖 (內建 SVG)
gr.HTML("""
""")
with gr.Row():
with gr.Column():
gr.Markdown("### 輸入焦距與光斑參數")
with gr.Row():
size_type_focus = gr.Radio(["直徑 (Diameter)", "半徑 (Radius)"], label="光斑尺寸類型", value="直徑 (Diameter)")
spot_unit_focus = gr.Radio(["毫米 (mm)", "微米 (um)"], label="光斑尺寸單位", value="毫米 (mm)")
with gr.Row():
focal_input = gr.Number(label="焦距長度 (mm)", value=50.0)
focal_unit = gr.Radio(["毫米 (mm)", "公分 (cm)", "公尺 (m)"], label="距離單位", value="毫米 (mm)")
with gr.Row():
d1_focus_in = gr.Number(label="雷射出光尺寸 d1 (mm)", value=3.0)
d2_focus_in = gr.Number(label="焦距光斑尺寸 d2 (mm)", value=0.5)
focus_calc_btn = gr.Button("開始計算收斂角度", variant="primary")
focus_out_text = gr.Markdown("等待輸入...")
with gr.Column():
focus_out_plot = gr.Plot(label="Focus Beam Convergence Plot")
gr.Markdown(r"""
**計算原理說明**:
1. 設定雷射出光為起始點,焦平面光斑為終點,測試距離為焦距 $L$。
2. 計算光束半徑收斂差:${\Delta r = r_1 - r_2}$
3. **半收斂角**:$\theta_{half} = \arctan(\frac{\Delta r}{L})$
4. **全收斂角**:$\theta_{full} = 2 \times \theta_{half}$
""")
with gr.Tab("📐 同軸度計算"):
gr.Markdown("## 📐 雷射同軸度與 mRad 雙向換算")
# 加入同軸度雷射模組示意圖 (內建 SVG)
gr.HTML("""
""")
with gr.Tabs():
with gr.Tab("已知偏移量 ➜ 求角度"):
with gr.Row():
with gr.Column():
with gr.Row():
dist_input_1 = gr.Number(label="測試距離 L (mm)", value=1000)
dist_unit_1 = gr.Radio(["毫米 (mm)", "公分 (cm)", "公尺 (m)"], label="距離單位", value="毫米 (mm)")
with gr.Row():
off_input = gr.Number(label="光斑偏移量 (mm)", value=1)
off_unit = gr.Radio(["毫米 (mm)", "微米 (um)"], label="偏移量單位", value="毫米 (mm)")
off_type = gr.Radio(["半徑 (Radius)", "直徑 (Diameter)"], label="偏移量類型", value="半徑 (Radius)")
calc_btn_1 = gr.Button("計算角度與 mRad", variant="primary")
calc_output_text_1 = gr.Markdown("等待輸入...")
with gr.Column():
calc_output_plot_1 = gr.Plot(label="Coaxiality Plot")
with gr.Tab("已知角度 ➜ 求偏移量"):
with gr.Row():
with gr.Column():
with gr.Row():
dist_input_2 = gr.Number(label="測試距離 L (mm)", value=1000)
dist_unit_2 = gr.Radio(["毫米 (mm)", "公分 (cm)", "公尺 (m)"], label="距離單位", value="毫米 (mm)")
with gr.Row():
angle_input = gr.Number(label="角度數值", value=1)
ang_type = gr.Radio(["mRad", "度 (Degree)"], label="角度單位", value="mRad")
calc_btn_2 = gr.Button("計算半徑與直徑長度", variant="primary")
calc_output_text_2 = gr.Markdown("等待輸入...")
with gr.Column():
calc_output_plot_2 = gr.Plot(label="Coaxiality Plot")
with gr.Tab("🔦 光束發散計算"):
gr.Markdown(r"""## 🔦 測量兩點計算光束發散角 (Beam Divergence)""")
# 加入光束發散雷射模組示意圖 (內建 SVG)
gr.HTML("""
""")
with gr.Row():
with gr.Column():
gr.Markdown("### 輸入測量數據")
size_type_div = gr.Radio(["直徑 (Diameter)", "半徑 (Radius)"], label="光斑尺寸類型", value="直徑 (Diameter)")
with gr.Row():
z1_in = gr.Number(label="位置 1 距離 (z1) mm", value=100)
d1_in = gr.Number(label="位置 1 尺寸 (d1) mm", value=2.0)
with gr.Row():
z2_in = gr.Number(label="位置 2 距離 (z2) mm", value=1000)
d2_in = gr.Number(label="位置 2 尺寸 (d2) mm", value=4.0)
div_calc_btn = gr.Button("開始計算發散角", variant="primary")
div_out_text = gr.Markdown("等待輸入...")
with gr.Column():
div_out_plot = gr.Plot(label="Beam Divergence Plot")
gr.Markdown(r"""
**計算原理說明**:
1. 測量距離差:${\Delta L = z_2 - z_1}$
2. 光束半徑差:${\Delta r = r_2 - r_1}$ (直角三角形高度)
3. **半角發散**:$\theta_{half} = \arctan(\frac{\Delta r}{\Delta L})$
4. **全角發散** (業界標準):$\theta_{full} = 2 \times \theta_{half}$
""")
# 新增:線斑角度計算分頁
with gr.Tab("📏 線斑角度計算"):
gr.Markdown(r"""## 📏 測量線光斑長度計算發散角度 (Line Laser Angle)""")
# 加入雷射模組與線斑示意圖 (內建 SVG)
gr.HTML("""
""")
with gr.Row():
with gr.Column():
with gr.Row():
dist_input_line = gr.Number(label="測試距離 L (mm)", value=100)
dist_unit_line = gr.Radio(["毫米 (mm)", "公分 (cm)", "公尺 (m)"], label="距離單位", value="毫米 (mm)")
with gr.Row():
length_input_line = gr.Number(label="線光斑長度 l (mm)", value=100)
length_unit_line = gr.Radio(["毫米 (mm)", "公分 (cm)", "公尺 (m)"], label="長度單位", value="毫米 (mm)")
calc_btn_line = gr.Button("開始計算角度", variant="primary")
calc_output_text_line = gr.Markdown("等待輸入...")
with gr.Column():
calc_output_plot_line = gr.Plot(label="Line Laser Angle Plot")
gr.Markdown(r"""
**計算原理說明**:
1. 將打出的線光斑切半,與光源形成直角三角形:對邊為半線長 $l / 2$,鄰邊為測試距離 $L$。
2. **半角**:$\theta_{half} = \arctan(\frac{l / 2}{L})$
3. **全角 (發散角)**:$\theta_{full} = 2 \times \theta_{half}$
""")
with gr.Tab("📖 規格說明"):
gr.Markdown("### 📘 術語定義\n- **mRad**: 毫弧度,雷射發散角與同軸度常用的專業單位。\n- **發散角**: 光束隨距離擴散的程度,通常以全角 (Full-Angle) 標示。\n- **收斂角**: 光束通過透鏡聚焦後,逐漸匯聚變小的角度。")
gr.Markdown("---")
latest_spec_md = gr.Markdown("### 📝 最新訂單規格確認\n*尚未提交任何訂單,提交後將顯示於此處。*")
with gr.Tab("📋 訂單報表"):
refresh_table_btn = gr.Button("🔄 重新整理")
order_table = gr.DataFrame(value=get_order_data())
with gr.Tab("⚙️ 系統設定"):
with gr.Row():
new_w_input = gr.Textbox(label="新增波長"); add_w_btn = gr.Button("新增規格")
download_btn = gr.Button("🔄 生成下載連結")
file_output = gr.File(label="下載資料", file_count="multiple")
# --- 邏輯綁定 ---
# 訂單與系統
submit_btn.click(submit_rzf_order, [w_select, p_slider, s_radio, q_input, focus_in, spot_in, coaxial_in, ellipse_in, dim_d, dim_l, wire_m, wire_l, wire_c, connector], [order_status, latest_spec_md])
refresh_table_btn.click(get_order_data, outputs=order_table)
add_w_btn.click(lambda n, c: (gr.update(choices=c+[n], value=n), c+[n], f"已新增: {n}"), [new_w_input, ws_state], [w_select, ws_state, order_status])
download_btn.click(get_backup_files, outputs=file_output)
# 動態變更光點大小/光線長度標籤
s_radio.change(update_spot_input_label, inputs=s_radio, outputs=spot_in)
# 同軸度計算 (連動同軸度參數至表單)
dist_unit_1.change(update_dist_label, inputs=dist_unit_1, outputs=dist_input_1)
dist_unit_2.change(update_dist_label, inputs=dist_unit_2, outputs=dist_input_2)
off_unit.change(update_offset_label, inputs=off_unit, outputs=off_input)
calc_btn_1.click(calc_angle_from_offset, [dist_input_1, dist_unit_1, off_input, off_type, off_unit], [calc_output_text_1, calc_output_plot_1, coaxial_in])
calc_btn_2.click(calc_offset_from_angle, [dist_input_2, dist_unit_2, angle_input, ang_type], [calc_output_text_2, calc_output_plot_2, coaxial_in])
# 光束發散計算 (連動光點大小至表單)
div_calc_btn.click(calculate_and_plot_divergence, [z1_in, d1_in, z2_in, d2_in, size_type_div], [div_out_text, div_out_plot, spot_in])
# 焦距收斂計算 (連動焦距與光點大小至表單)
focal_unit.change(update_focal_label, inputs=focal_unit, outputs=focal_input)
spot_unit_focus.change(update_focus_spot_labels, inputs=spot_unit_focus, outputs=[d1_focus_in, d2_focus_in])
focus_calc_btn.click(calculate_and_plot_focus_divergence, [focal_input, focal_unit, d1_focus_in, d2_focus_in, spot_unit_focus, size_type_focus], [focus_out_text, focus_out_plot, focus_in, spot_in])
# 線斑角度計算 (連動光斑樣式與長度尺寸至表單)
dist_unit_line.change(update_dist_label, inputs=dist_unit_line, outputs=dist_input_line)
length_unit_line.change(update_line_length_label, inputs=length_unit_line, outputs=length_input_line)
calc_btn_line.click(calculate_and_plot_line_angle, [dist_input_line, dist_unit_line, length_input_line, length_unit_line], [calc_output_text_line, calc_output_plot_line, s_radio, spot_in])
# 部署在 Hugging Face Spaces 時不需加 share=True
demo.launch(theme=gr.themes.Soft())