fudii0921 commited on
Commit
68a83b7
·
verified ·
1 Parent(s): 04d48b2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -0
app.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cohere
3
+ import psycopg2
4
+ from psycopg2.extras import RealDictCursor
5
+ import os
6
+
7
+ # 環境変数の設定
8
+ os.environ["PYTHONIOENCODING"] = "utf-8"
9
+
10
+ # --- 設定 ---
11
+ COHERE_API_KEY = "qdDleuYthEdxdoxvxXs137NDuuE94kfYVrWb23fZ"
12
+ DB_CONFIG = {
13
+ "host": "www.ryhintl.com",
14
+ "dbname": "smair",
15
+ "user": "smairuser",
16
+ "password": "smairuser",
17
+ "port": 10629,
18
+ "connect_timeout": 15
19
+ }
20
+
21
+ co = cohere.Client(COHERE_API_KEY)
22
+
23
+ def generate_ai_advice(query, results):
24
+ context = ""
25
+ for res in results:
26
+ context += f"- 事例: {res['title']}\n 現象: {res['phenomenon']}\n 原因: {res['cause']}\n 処置: {res['action']}\n 防止策: {res['prevention']}\n\n"
27
+
28
+ prompt = f"""
29
+ あなたはベテランの工場管理者です。以下の「ユーザーからの相談内容」に対し、提供された「過去の類似事例」を参考にして、現場で今すぐ取るべき行動と、長期的な対策をプロの視点で要約・アドバイスしてください。
30
+
31
+ # ユーザーからの相談内容:
32
+ {query}
33
+
34
+ # 過去の類似事例:
35
+ {context}
36
+
37
+ # 回答の指針:
38
+ 1. 過去事例から共通する原因を特定してください。
39
+ 2. 現場担当者が優先して確認すべき点(チェックポイント)を3つ挙げてください。
40
+ 3. 再発防止のための改善提案を簡潔に述べてください。
41
+ 回答は日本語で、現場で読みやすいように箇条書きを活用してください。
42
+ """
43
+ # model名を安定した名称に変更(command-r-plusなど)
44
+ response = co.chat(
45
+ message=prompt,
46
+ model='command-a-03-2025'
47
+ )
48
+ return response.text
49
+
50
+ def search_troubles(query):
51
+ if not query.strip():
52
+ return "⚠️ トラブル事象を入力してください。"
53
+
54
+ conn = None
55
+ try:
56
+ # 1. ベクトル化
57
+ res = co.embed(
58
+ texts=[query],
59
+ model='embed-multilingual-v3.0',
60
+ input_type='search_query'
61
+ )
62
+ query_embedding = res.embeddings[0]
63
+
64
+ # 2. DB接続
65
+ conn = psycopg2.connect(**DB_CONFIG, client_encoding='utf8')
66
+ cur = conn.cursor(cursor_factory=RealDictCursor)
67
+
68
+ search_query = """
69
+ SELECT id, occurrence_date, process_name, equipment_name, title,
70
+ phenomenon, cause, action, prevention, severity,
71
+ 1 - (embedding <=> %s::vector) AS similarity
72
+ FROM factory_troubles
73
+ ORDER BY similarity DESC
74
+ LIMIT 3;
75
+ """
76
+ cur.execute(search_query, (query_embedding,))
77
+ results = cur.fetchall()
78
+
79
+ if not results:
80
+ return "該当する事例が見つかりませんでした。"
81
+
82
+ # 3. AIによるアドバイス生成
83
+ ai_advice = generate_ai_advice(query, results)
84
+
85
+ # 4. フォーマット
86
+ output = "## 🤖 AIからのトラブルシューティング・アドバイス\n\n"
87
+ output += f"{ai_advice}\n\n"
88
+ output += "---\n"
89
+ output += "## 🔍 参考にした過去の類似事例\n\n"
90
+
91
+ for i, res in enumerate(results):
92
+ output += f"### {i+1}. {res['title']} (類似度: {res['similarity']:.4f})\n"
93
+ output += f"**【処置】**: {res['action']}\n\n"
94
+ output += f"""
95
+ <details>
96
+ <summary><b>📄 元のデータ(出典詳細)を表示</b></summary>
97
+ <div style="background-color: #f9f9f9; padding: 10px; border-radius: 5px; border: 1px solid #ddd; color: #333;">
98
+ <p><b>発生日:</b> {res['occurrence_date']} | <b>工程:</b> {res['process_name']}</p>
99
+ <p><b>現象:</b> {res['phenomenon']}</p>
100
+ <p><b>原因:</b> {res['cause']}</p>
101
+ <p><b>防止策:</b> {res['prevention']}</p>
102
+ </div>
103
+ </details>\n\n---\n"""
104
+ return output
105
+
106
+ except Exception as e:
107
+ return f"### ⚠️ エラーが発生しました\n詳細: `{repr(e)}`"
108
+ finally:
109
+ if conn: conn.close()
110
+
111
+ # --- Gradio Blocks UI ---
112
+ with gr.Blocks(title="AI工場トラブル・コンシェルジュ", css=".gradio-container {background-color: #f5f7f9}") as demo:
113
+ gr.Markdown("# 🛠 AI工場トラブル・コンシェルジュ")
114
+ gr.Markdown("過去の知見に基づき、AIが現場の課題解決に向けたアドバイスを生成します。")
115
+
116
+ with gr.Row():
117
+ with gr.Column():
118
+ input_text = gr.Textbox(
119
+ label="現在のトラブル状況を入力",
120
+ info="例: コンベアのモーターが高温になっており、焦げたような臭いがする。 加工面の焼け発生している。 末端のシール部からの液漏れがある。",
121
+ lines=3
122
+ )
123
+ # ボタンクリック時に非活性化するように設定可能
124
+ search_btn = gr.Button("🔍 知見を検索してAIアドバイスを受ける", variant="primary")
125
+
126
+ with gr.Row():
127
+ # ステータス表示用のコンポーネント(任意ですが、標準機能で十分カバーされます)
128
+ output_markdown = gr.Markdown(value="ここに結果が表示されます。")
129
+
130
+ # .click の際に、検索中はボタンを無効化し、ローディングを表示する設定
131
+ search_btn.click(
132
+ fn=search_troubles,
133
+ inputs=input_text,
134
+ outputs=output_markdown,
135
+ show_progress="full", # "full"にすることで画面全体にローディングインジケータを表示
136
+ scroll_to_output=True # 完了時に結果へスクロール
137
+ )
138
+
139
+ if __name__ == "__main__":
140
+ demo.launch()