TimeCapsuleX commited on
Commit
c83108e
·
verified ·
1 Parent(s): 27e368f

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +117 -0
  2. requirements.txt +6 -0
  3. syn5000.csv +0 -0
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import faiss
3
+ from sentence_transformers import SentenceTransformer
4
+ from transformers import T5ForConditionalGeneration, T5Tokenizer
5
+ import numpy as np
6
+ import gradio as gr
7
+
8
+ # --- 1. Load Models and Data (runs only once when the app starts) ---
9
+ print("Loading models and data... This may take a moment.")
10
+
11
+ # Load the dataset
12
+ df = pd.read_csv('syn5000.csv')
13
+ df.rename(columns={
14
+ 'System / Subsystem Components': 'system',
15
+ 'What is the item that you are focusing on?': 'item',
16
+ 'What function does the item have?': 'function',
17
+ 'What are you trying to achieve (Product Requirement)?': 'requirement',
18
+ 'How could you get the requirements wrong (Failure Mode)?': 'failure_mode',
19
+ 'Action Taken (Risk Mitigation)': 'mitigation'
20
+ }, inplace=True)
21
+
22
+ df['input_text'] = (
23
+ "System: " + df['system'] + "; " +
24
+ "Item: " + df['item'] + "; " +
25
+ "Requirement: " + df['requirement'] + "; " +
26
+ "Failure: " + df['failure_mode']
27
+ )
28
+
29
+ # Load the embedding model
30
+ embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
31
+
32
+ # Create and index embeddings using FAISS
33
+ corpus_embeddings = embedding_model.encode(df['input_text'].tolist())
34
+ embedding_dimension = corpus_embeddings.shape[1]
35
+ index = faiss.IndexFlatL2(embedding_dimension)
36
+ index.add(corpus_embeddings)
37
+
38
+ # Load the generator model and tokenizer
39
+ tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-base")
40
+ generator_model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-base")
41
+
42
+ print("Models and data loaded successfully!")
43
+
44
+
45
+ # --- 2. The Core AI Logic ---
46
+
47
+ def retrieve_similar_examples(query_text, top_k=3):
48
+ query_embedding = embedding_model.encode([query_text])
49
+ distances, indices = index.search(query_embedding, top_k)
50
+ return df.iloc[indices[0]].to_dict('records')
51
+
52
+ def generate_mitigation_text(prompt):
53
+ inputs = tokenizer(prompt, return_tensors="pt", max_length=1024, truncation=True)
54
+ outputs = generator_model.generate(**inputs, max_length=128, num_beams=4, early_stopping=True)
55
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
56
+
57
+ # This is the main function that Gradio will call
58
+ def suggest_mitigation_from_ui(system, item, requirement, failure_mode):
59
+ """
60
+ Takes individual text inputs from the UI and returns a suggested mitigation.
61
+ """
62
+ query_text = (
63
+ f"System: {system}; "
64
+ f"Item: {item}; "
65
+ f"Requirement: {requirement}; "
66
+ f"Failure: {failure_mode}"
67
+ )
68
+
69
+ similar_examples = retrieve_similar_examples(query_text)
70
+
71
+ prompt = "You are an expert risk analysis engineer.\n\n"
72
+ prompt += "Based on the following similar past examples, write a specific risk mitigation action for the new failure described at the end.\n\n"
73
+ prompt += "--- EXAMPLES ---\n"
74
+ for ex in similar_examples:
75
+ prompt += f"Failure Description: {ex['input_text']}\n"
76
+ prompt += f"Mitigation Action: {ex['mitigation']}\n---\n"
77
+
78
+ prompt += "\n--- NEW FAILURE ---\n"
79
+ prompt += f"Failure Description: {query_text}\n"
80
+ prompt += "Mitigation Action:"
81
+
82
+ generated_text = generate_mitigation_text(prompt)
83
+
84
+ # We can also return the examples it used, for transparency
85
+ retrieved_info = "--- Retrieved Similar Examples ---\n"
86
+ for i, ex in enumerate(similar_examples):
87
+ retrieved_info += f"{i+1}. {ex['input_text'][:150]}...\n"
88
+
89
+ return generated_text, retrieved_info
90
+
91
+ # --- 3. Create the Gradio Web Interface ---
92
+
93
+ with gr.Blocks() as demo:
94
+ gr.Markdown("# AI Risk Mitigation Assistant")
95
+ gr.Markdown("Enter the details of a potential failure to get an AI-generated mitigation suggestion based on historical data.")
96
+
97
+ with gr.Row():
98
+ with gr.Column():
99
+ system_input = gr.Textbox(label="System / Subsystem")
100
+ item_input = gr.Textbox(label="Item in Focus")
101
+ requirement_input = gr.Textbox(label="Product Requirement")
102
+ failure_mode_input = gr.Textbox(label="Failure Mode")
103
+ submit_btn = gr.Button("Suggest Mitigation", variant="primary")
104
+
105
+ with gr.Column():
106
+ output_mitigation = gr.Textbox(label="✅ AI-Generated Mitigation Suggestion", lines=5)
107
+ output_examples = gr.Textbox(label="Retrieved Examples", lines=5)
108
+
109
+ submit_btn.click(
110
+ fn=suggest_mitigation_from_ui,
111
+ inputs=[system_input, item_input, requirement_input, failure_mode_input],
112
+ outputs=[output_mitigation, output_examples]
113
+ )
114
+
115
+ # This launches the app. On Hugging Face, it will be served automatically.
116
+ if __name__ == "__main__":
117
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ pandas
2
+ faiss-cpu
3
+ sentence-transformers
4
+ transformers
5
+ torch
6
+ gradio
syn5000.csv ADDED
The diff for this file is too large to render. See raw diff