Ryomaaa commited on
Commit
8036226
·
verified ·
1 Parent(s): 829c04e

Upload app.py.txt

Browse files
Files changed (1) hide show
  1. app.py.txt +173 -0
app.py.txt ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import os
5
+ from openai import OpenAI
6
+
7
+ # --- 設定 ---
8
+ api_key = os.getenv("OPENAI_API_KEY")
9
+
10
+ # 固定ファイル名
11
+ MASTER_FILE = "master.csv"
12
+ PLM_FILE = "plm.csv"
13
+
14
+ def robust_read_csv(path, target_columns):
15
+ """
16
+ タイトル行や空行をスキップし、特定のカラム名が含まれる行をヘッダーとして自動認識して読み込む。
17
+ """
18
+ if not os.path.exists(path):
19
+ return None, f"ファイル '{path}' が見つかりません。"
20
+
21
+ encodings = ['cp932', 'utf-8', 'shift_jis']
22
+ for enc in encodings:
23
+ try:
24
+ # まずはヘッダーなしで全行読み込む
25
+ raw_df = pd.read_csv(path, encoding=enc, header=None, on_bad_lines='skip', engine='python')
26
+
27
+ # ターゲットとなるカラム名が含まれる行を探す
28
+ header_idx = None
29
+ for i, row in raw_df.iterrows():
30
+ row_values = [str(x) for x in row.values]
31
+ # target_columnsのいずれかが含まれている行をヘッダーとみなす
32
+ if any(col in row_values for col in target_columns):
33
+ header_idx = i
34
+ break
35
+
36
+ if header_idx is not None:
37
+ # 特定した行をヘッダーとして再読み込み
38
+ df = pd.read_csv(path, encoding=enc, skiprows=header_idx)
39
+ # カラム名に含まれる改行コードなどを除去
40
+ df.columns = [str(c).replace('\n', '').strip() for c in df.columns]
41
+ return df, None
42
+ else:
43
+ return None, f"ヘッダー行({target_columns})が見つかりませんでした。"
44
+
45
+ except UnicodeDecodeError:
46
+ continue
47
+ except Exception as e:
48
+ return None, str(e)
49
+
50
+ return None, "文字コードの判定に失敗しました。"
51
+
52
+ # データの読み込み(起動時に実行)
53
+ # 原紙マスタは「品番」、PLMは「代表銘柄」をキーにヘッダーを探索
54
+ M_DF, M_ERR = robust_read_csv(MASTER_FILE, ["品番", "親品番", "銘柄名"])
55
+ P_DF, P_ERR = robust_read_csv(PLM_FILE, ["代表銘柄", "品名", "材料名"])
56
+
57
+ def analyze_cd_logic(target_brand):
58
+ # エラーチェック
59
+ if M_DF is None: return f"❌ マスタ読み込みエラー: {M_ERR}"
60
+ if P_DF is None: return f"❌ PLMデータ読み込みエラー: {P_ERR}"
61
+ if not api_key: return "❌ OpenAI APIキーが未設定です。"
62
+ if not target_brand: return "⚠️ 銘柄名または親品番を入力してください。"
63
+
64
+ client = OpenAI(api_key=api_key)
65
+
66
+ try:
67
+ # 1. 銘柄検索ロジック (親品番、銘柄名、一般名称銘柄)
68
+ # カラム名の揺れに対応(マスタ側)
69
+ brand_mask = (M_DF['親品番'].astype(str) == target_brand) | \
70
+ (M_DF['銘柄名'].astype(str) == target_brand)
71
+
72
+ # 3列目(一般名称銘柄)も検索対象に
73
+ if M_DF.shape[1] > 2:
74
+ brand_mask |= (M_DF.iloc[:, 2].astype(str) == target_brand)
75
+
76
+ brand_data = M_DF[brand_mask]
77
+
78
+ if brand_data.empty:
79
+ return f"❌ 銘柄「{target_brand}」はマスタに見つかりません。"
80
+
81
+ spec = brand_data.iloc[0]
82
+
83
+ # 2. 製品紐付け(PLM側)
84
+ related_prods = P_DF[P_DF['代表銘柄'].astype(str) == target_brand]
85
+ prod_names = related_prods['品名'].unique()[:5] if not related_prods.empty else ["紐付けなし"]
86
+
87
+ # 3. CDロジック判定(資材1G戦略に基づく)
88
+ findings = []
89
+
90
+ # A. 共用銘柄化(メーカー集約)
91
+ all_variants = M_DF[M_DF['親品番'] == spec['親品番']].copy()
92
+ all_variants['price'] = pd.to_numeric(all_variants['仕入単価(新)'], errors='coerce')
93
+ if all_variants['製紙会社'].nunique() > 1:
94
+ p_max = all_variants['price'].max()
95
+ p_min = all_variants['price'].min()
96
+ if p_max > p_min:
97
+ findings.append(f"【共用銘柄化】同一品番内で複数メーカー混在。単価差 {p_max - p_min:.1f}円/kg。安値メーカーへの全量集約。")
98
+
99
+ # B. 環境対応(1Gナレッジ)
100
+ if str(spec.get('古紙使用フラグ')) == '1':
101
+ findings.append("【環境対応見直し】古紙配合品からFSC認証紙へのスペック変更。1G事例(▲18M/年)に基づくコスト構造の改善。")
102
+
103
+ # C. 価値の再定義(一般品化)
104
+ if '1' in [str(spec.get('特抄フラグ')), str(spec.get('特寸フラグ'))]:
105
+ findings.append("【価値の再定義】特注仕様(特抄・特寸)を廃止し、一般流通品へ集約。供給ソース固定化の解消と相見積の実施。")
106
+
107
+ # D. 仕様変更(薄物化)
108
+ gram = pd.to_numeric(spec['坪量 g/㎡'], errors='coerce')
109
+ if not np.isnan(gram) and gram > 70:
110
+ findings.append(f"【仕様変更】現行{gram}g/㎡。オーバースペックの可能性。一段階下の米坪(薄物化)による原資コスト低減。")
111
+
112
+ if not findings:
113
+ return "💡 明確な自動判定ロジックに該当する施策は見つかりませんでした。市場市況に基づく価格交渉、または物流商流の効率化を検討してください。"
114
+
115
+ # 4. AIによる具体的施策の肉付け
116
+ prompt = f"""
117
+ あなたは製造業の戦略調達プロフェッショナルです。以下のデータ分析結果に基づき、実務に即した「CD施策シート」を作成してください。
118
+
119
+ 【対象銘柄情報】
120
+ 銘柄: {spec['銘柄名']}
121
+ 製紙会社: {spec['製紙会社']} / 現行単価: {spec['仕入単価(新)']}円
122
+ 主要使用製品: {', '.join(prod_names)}
123
+ 検出された論理: {" / ".join(findings)}
124
+
125
+ 【出力ルール】
126
+ - 交渉メール案、反論対策、導入文、挨拶は一切含めないでください。
127
+ - 以下の4項目を1セットとして、各切り口ごとに鋭く、論理的なアクションを出力してください。
128
+
129
+ 1. 切り口
130
+ 2. 具体的な方法
131
+ 3. 現状の課題(データからの根拠)
132
+ 4. 提案内容と期待効果(具体的アクションプラン)
133
+ """
134
+
135
+ response = client.chat.completions.create(
136
+ model="gpt-4o",
137
+ messages=[{"role": "system", "content": "あなたは論理的で実務に厳しい調達分析官です。"},
138
+ {"role": "user", "content": prompt}],
139
+ temperature=0.3
140
+ )
141
+ return response.choices[0].message.content
142
+
143
+ except Exception as e:
144
+ return f"🚨 解析エラー: {str(e)}"
145
+
146
+ # --- Gradio UI ---
147
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
148
+ gr.Markdown("# 🛡️ CDG AI Strategist - 論理分析特化版")
149
+ gr.Markdown("不規則なCSV形式にも対応した強化版読み込みエンジンを搭載しています。")
150
+
151
+ with gr.Row():
152
+ with gr.Column(scale=1):
153
+ brand_input = gr.Textbox(label="銘柄名 / 親品番 を入力", placeholder="例: Jウメ70AC")
154
+ btn = gr.Button("CD戦略を生成", variant="primary")
155
+
156
+ # ステータス表示
157
+ if M_DF is not None:
158
+ gr.Markdown(f"✅ 原紙マスタ: {len(M_DF)}行 読み込み完了")
159
+ else:
160
+ gr.Markdown(f"❌ 原紙マスタ: {M_ERR}")
161
+
162
+ if P_DF is not None:
163
+ gr.Markdown(f"✅ PLMデータ: {len(P_DF)}行 読み込み完了")
164
+ else:
165
+ gr.Markdown(f"❌ PLMデータ: {P_ERR}")
166
+
167
+ with gr.Column(scale=2):
168
+ output = gr.Markdown(label="CD施策詳細レポート")
169
+
170
+ btn.click(fn=analyze_cd_logic, inputs=brand_input, outputs=output)
171
+
172
+ if __name__ == "__main__":
173
+ demo.launch()