s880453 commited on
Commit
5ac2b99
·
verified ·
1 Parent(s): a866508

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -3
app.py CHANGED
@@ -2,6 +2,8 @@ import gradio as gr
2
  import pandas as pd
3
  import plotly.express as px
4
  import plotly.graph_objects as go
 
 
5
 
6
  def create_plot(df, chart_type, x_col, y_col, group_col):
7
  if df is None or x_col not in df.columns or y_col not in df.columns:
@@ -66,13 +68,26 @@ with gr.Blocks(title="雙圖比較") as demo:
66
 
67
  def load_csv(file_obj):
68
  try:
69
- df = pd.read_csv(file_obj.name)
70
- return df, f"成功載入 {len(df)} 筆資料"
 
 
 
 
 
 
 
 
 
 
 
71
  except Exception as e:
72
  return None, f"讀取錯誤: {e}"
73
-
74
  file.change(fn=load_csv, inputs=[file], outputs=[df_state, status])
75
 
 
 
76
  gr.Markdown("### 📌 圖表設定")
77
 
78
  with gr.Row():
 
2
  import pandas as pd
3
  import plotly.express as px
4
  import plotly.graph_objects as go
5
+ import chardet
6
+
7
 
8
  def create_plot(df, chart_type, x_col, y_col, group_col):
9
  if df is None or x_col not in df.columns or y_col not in df.columns:
 
68
 
69
  def load_csv(file_obj):
70
  try:
71
+ # 嘗試自動偵測編碼
72
+ raw = file_obj.read()
73
+ file_obj.seek(0) # 重設檔案指標
74
+ detected = chardet.detect(raw)
75
+ encoding = detected['encoding'] or 'utf-8'
76
+ df = pd.read_csv(file_obj.name, encoding=encoding, engine='python')
77
+ return df, f"成功載入 {len(df)} 筆資料(偵測編碼: {encoding})"
78
+ except UnicodeDecodeError:
79
+ try:
80
+ df = pd.read_csv(file_obj.name, encoding='big5', engine='python')
81
+ return df, f"成功載入 {len(df)} 筆資料(big5 編碼)"
82
+ except Exception as e:
83
+ return None, f"仍然失敗:{e}"
84
  except Exception as e:
85
  return None, f"讀取錯誤: {e}"
86
+
87
  file.change(fn=load_csv, inputs=[file], outputs=[df_state, status])
88
 
89
+
90
+
91
  gr.Markdown("### 📌 圖表設定")
92
 
93
  with gr.Row():