Spaces:
Sleeping
Sleeping
Commit Β·
fdbfbee
1
Parent(s): 3914cd6
Add application file
Browse filesFiles changed (2)
12345618 unmodified lines25262728293011 unmodified lines424344454647484950515253545556575859606162636426 unmodified lines9192939495969798991001011021031041051061071081093 unmodified lines11311411511611711811912012112212315 unmodified lines1391401411421431441451461471484 unmodified lines1531541551561571581591604 unmodified lines1651661671681691701715 unmodified lines17717817918018118218321 unmodified lines2052062072082092105 unmodified lines21621721821922022122222322422522622722822923023138 unmodified lines2702712722732742752762771 unmodified line27928028128228328428528620 unmodified lines307308309310311312313import osimport jsonimport reimport torchimport gradio as grimport pandas as pd18 unmodified linesRETRIEVER = NoneLLM = NonePROMPT = Nonefeedback_vector_store = Noneembeddings = None11 unmodified linesfeedback_df = pd.read_csv(FEEDBACK_FILE)if feedback_df.empty:return {}stats = feedback_df.groupby('action')['rating'].agg(['mean', 'count']).to_dict('index')return statsexcept pd.errors.EmptyDataError:return {}def save_feedback(action, rating, display_df):if not action:return "Please select a recommendation from the table first.", display_dfnorm_action = normalize_action(action)new_feedback = pd.DataFrame([{'action': norm_action, 'rating': int(rating)}])if not os.path.exists(FEEDBACK_FILE):new_feedback.to_csv(FEEDBACK_FILE, index=False)else:new_feedback.to_csv(FEEDBACK_FILE, mode='a', header=False, index=False)build_feedback_db()msg = f"β Rating of {rating}/10 saved for: {action}"# Update the displayed table dynamicallyif display_df is not None and not display_df.empty:26 unmodified linesfeedback_vector_store = FAISS.from_texts(highly_rated_actions, embeddings)print("β Feedback vector store is ready.")# --- build_rag_chain ---def build_rag_chain():global QA_CHAIN, RETRIEVER, LLM, PROMPT, embeddingstry:print("Initializing local HuggingFace embedding model...")embeddings = HuggingFaceEmbeddings(model_name='all-MiniLM-L6-v2',model_kwargs={'device': DEVICE})print("β Local embedding model loaded.")build_feedback_db()print(f"Loading FMEA data from {FMEA_DATA_FILE}...")fmea_df = pd.read_csv(FMEA_DATA_FILE).fillna("")documents = []3 unmodified linesif "Failure_Mode" in fmea_df.columns:metadata["source"] = str(row["Failure_Mode"])documents.append(Document(page_content=page_content, metadata=metadata))print(f"β Successfully loaded {len(documents)} records.")print("Creating embeddings and building main FAISS vector store...")main_vector_store = FAISS.from_documents(documents, embeddings)print("β Main vector store created successfully.")# --- UPDATED TO USE LLAMA 3.3 VIA GROQ ---llm = ChatGroq(model_name="llama-3.3-70b-versatile", temperature=0.2)15 unmodified linesINSTRUCTIONS:Format your entire response as a single, valid JSON object with a key "recommendations" which is a list of 3 objects.Each object must have these keys: "rank", "action", "department", "ai_score", "new_S", "new_O", "new_D".- "rank": The rank of the recommendation (1, 2, 3).- "action": The recommended action text.- "department": The most likely responsible department.- "ai_score": Confidence score (1-100) for this recommendation.- "new_S": Your estimated new Severity score (1-10).4 unmodified lines"""PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])# Included the token-saving "k": 2 limitRETRIEVER = main_vector_store.as_retriever(search_kwargs={"k": 2})LLM = llmQA_CHAIN = Trueprint("β RAG model is ready.")4 unmodified lines# --- 3. Gradio Interface Logic ---def fmea_rag_interface(mode, effect, cause, severity, occurrence, detection):if QA_CHAIN is None or RETRIEVER is None or LLM is None or PROMPT is None:return "RAG Model is not initialized.", pd.DataFrame(), ""rpn = severity * occurrence * detection5 unmodified linesf"The current scores are: Severity={severity}, Occurrence={occurrence}, Detection={detection}.")docs = RETRIEVER.invoke(query)context_from_history = "\n---\n".join([doc.page_content for doc in docs])context_from_feedback = ""21 unmodified linesdata = json.loads(json_text)output_df = pd.DataFrame(data['recommendations'])feedback_stats = load_feedback_stats()default_stat = {'mean': 0, 'count': 0}5 unmodified linesoutput_df['new_O'] = output_df['new_O'].astype(int)output_df['new_D'] = output_df['new_D'].astype(int)output_df['new_RPN'] = output_df['new_S'] * output_df['new_O'] * output_df['new_D']rpn_change_list = [f"{int(rpn)} β {int(new_rpn)}" for new_rpn in output_df['new_RPN']]display_df = pd.DataFrame({"Rank": output_df['rank'],"Recommended Action": output_df['action'],"Department": output_df['department'],"AI Confidence": [f"{score}%" for score in output_df['ai_score']],"Avg. Feedback": [f"{avg:.2f}/10 ({int(count)})" for avg, count in zip(output_df['avg_feedback'], output_df['feedback_count'])],"Revised RPN": rpn_change_list})except Exception as e:38 unmodified linesgr.Markdown("## π‘ Top 3 AI-Generated Recommendations")rpn_output = gr.Textbox(label="Current RPN", interactive=False)recommendations_output = gr.DataFrame(headers=["Rank", "Recommended Action", "Department", "AI Confidence", "Avg. Feedback", "Revised RPN"],datatype=["number", "str", "str", "str", "str", "str"])df_state = gr.State()1 unmodified linegr.Markdown("## β Provide Feedback")gr.Markdown("Click a row in the table above to select it, then submit your rating.")selected_action_text = gr.Textbox(label="Selected for Feedback", interactive=False)rating_slider = gr.Slider(minimum=1, maximum=10, step=1, value=8, label="Your Rating (1-10)")submit_feedback_btn = gr.Button("Submit Rating")feedback_status = gr.Textbox(label="Feedback Status", interactive=False)# FIX 1: Safer update_selection function20 unmodified linessubmit_feedback_btn.click(fn=save_feedback,inputs=[selected_action_text, rating_slider, recommendations_output],outputs=[feedback_status, recommendations_output])123456718 unmodified lines262728293031323311 unmodified lines4546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110226 unmodified lines1291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581593 unmodified lines16316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219315 unmodified lines2092102112122132142152162172182194 unmodified lines2242252262272282294 unmodified lines2342352362372382392405 unmodified lines24624724824925025125225325425521 unmodified lines2772782792802812822832845 unmodified lines29029129229329429529629729829930030130230330430530630730838 unmodified lines3473483493503513523533541 unmodified line35635735835936036136236336436536636720 unmodified lines388389390391392393394import osimport jsonimport refrom datetime import datetime, timezoneimport torchimport gradio as grimport pandas as pd18 unmodified linesRETRIEVER = NoneLLM = NonePROMPT = NoneFMEA_DF = NoneDOCUMENTS = Nonefeedback_vector_store = Noneembeddings = None11 unmodified linesfeedback_df = pd.read_csv(FEEDBACK_FILE)if feedback_df.empty:return {}if "rating" not in feedback_df.columns:return {}stats = feedback_df.groupby('action')['rating'].agg(['mean', 'count']).to_dict('index')return statsexcept pd.errors.EmptyDataError:return {}def ensure_feedback_schema():target_cols = ["action", "rating", "feedback_type", "timestamp_utc"]if not os.path.exists(FEEDBACK_FILE):returntry:existing_df = pd.read_csv(FEEDBACK_FILE)if existing_df.empty:pd.DataFrame(columns=target_cols).to_csv(FEEDBACK_FILE, index=False)returnchanged = Falsefor col in target_cols:if col not in existing_df.columns:existing_df[col] = ""changed = Trueif changed:existing_df = existing_df[target_cols]existing_df.to_csv(FEEDBACK_FILE, index=False)except pd.errors.EmptyDataError:pd.DataFrame(columns=target_cols).to_csv(FEEDBACK_FILE, index=False)def save_feedback(action, feedback_choice, display_df):if not action:return "Please select a recommendation from the table first.", display_dfchoice_map = {"π Thumbs Up": ("thumbs_up", 10),"π Thumbs Down": ("thumbs_down", 3)}feedback_type, rating = choice_map.get(feedback_choice, ("thumbs_up", 10))timestamp_utc = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")norm_action = normalize_action(action)new_feedback = pd.DataFrame([{'action': norm_action,'rating': int(rating),'feedback_type': feedback_type,'timestamp_utc': timestamp_utc}])if not os.path.exists(FEEDBACK_FILE):new_feedback.to_csv(FEEDBACK_FILE, index=False)else:ensure_feedback_schema()new_feedback.to_csv(FEEDBACK_FILE, mode='a', header=False, index=False)build_feedback_db()msg = f"β Feedback saved ({feedback_choice}) for: {action} at {timestamp_utc}"# Update the displayed table dynamicallyif display_df is not None and not display_df.empty:26 unmodified linesfeedback_vector_store = FAISS.from_texts(highly_rated_actions, embeddings)print("β Feedback vector store is ready.")def keyword_retrieve_documents(search_query: str, k: int = 2):if FMEA_DF is None or DOCUMENTS is None or FMEA_DF.empty:return []tokens = [tok for tok in re.findall(r"[a-z0-9]+", str(search_query).lower()) if len(tok) >= 3]if not tokens:return DOCUMENTS[:k]scores = []for idx, text in enumerate(FMEA_DF["__search_text"]):token_hits = sum(1 for tok in tokens if tok in text)if token_hits:scores.append((token_hits, idx))if not scores:return DOCUMENTS[:k]scores.sort(key=lambda x: x[0], reverse=True)top_indices = [idx for _, idx in scores[:k]]return [DOCUMENTS[idx] for idx in top_indices]# --- build_rag_chain ---def build_rag_chain():global QA_CHAIN, RETRIEVER, LLM, PROMPT, FMEA_DF, DOCUMENTS, feedback_vector_store, embeddingstry:print(f"Loading FMEA data from {FMEA_DATA_FILE}...")fmea_df = pd.read_csv(FMEA_DATA_FILE).fillna("")documents = []3 unmodified linesif "Failure_Mode" in fmea_df.columns:metadata["source"] = str(row["Failure_Mode"])documents.append(Document(page_content=page_content, metadata=metadata))search_cols = [c for c in ["Failure_Mode", "Effect", "Cause", "Recommended_Action", "Responsible_Department"] if c in fmea_df.columns]fmea_df["__search_text"] = fmea_df[search_cols].astype(str).agg(" ".join, axis=1).str.lower()FMEA_DF = fmea_dfDOCUMENTS = documentsprint(f"β Successfully loaded {len(documents)} records.")print("Initializing local HuggingFace embedding model...")try:embeddings = HuggingFaceEmbeddings(model_name='all-MiniLM-L6-v2',model_kwargs={'device': DEVICE})print("β Local embedding model loaded.")build_feedback_db()print("Creating embeddings and building main FAISS vector store...")main_vector_store = FAISS.from_documents(documents, embeddings)RETRIEVER = main_vector_store.as_retriever(search_kwargs={"k": 2})print("β Main vector store created successfully.")except Exception as embed_error:embeddings = NoneRETRIEVER = Nonefeedback_vector_store = Noneprint(f"β οΈ Embedding setup failed, using keyword retrieval fallback. Details: {embed_error}")# --- UPDATED TO USE LLAMA 3.3 VIA GROQ ---llm = ChatGroq(model_name="llama-3.3-70b-versatile", temperature=0.2)15 unmodified linesINSTRUCTIONS:Format your entire response as a single, valid JSON object with a key "recommendations" which is a list of 3 objects.Each object must have these keys: "rank", "action", "action_details", "department", "ai_score", "new_S", "new_O", "new_D".- "rank": The rank of the recommendation (1, 2, 3).- "action": The recommended action text.- "action_details": 2-3 sentences explaining why this action works and practical implementation notes.- "department": The most likely responsible department.- "ai_score": Confidence score (1-100) for this recommendation.- "new_S": Your estimated new Severity score (1-10).4 unmodified lines"""PROMPT = PromptTemplate(template=prompt_template, input_variables=["context", "question"])LLM = llmQA_CHAIN = Trueprint("β RAG model is ready.")4 unmodified lines# --- 3. Gradio Interface Logic ---def fmea_rag_interface(mode, effect, cause, severity, occurrence, detection):if QA_CHAIN is None or LLM is None or PROMPT is None:return "RAG Model is not initialized.", pd.DataFrame(), ""rpn = severity * occurrence * detection5 unmodified linesf"The current scores are: Severity={severity}, Occurrence={occurrence}, Detection={detection}.")if RETRIEVER is not None:docs = RETRIEVER.invoke(query)else:docs = keyword_retrieve_documents(f"{mode} {effect} {cause}", k=2)context_from_history = "\n---\n".join([doc.page_content for doc in docs])context_from_feedback = ""21 unmodified linesdata = json.loads(json_text)output_df = pd.DataFrame(data['recommendations'])if 'action_details' not in output_df.columns:output_df['action_details'] = "No additional details provided."feedback_stats = load_feedback_stats()default_stat = {'mean': 0, 'count': 0}5 unmodified linesoutput_df['new_O'] = output_df['new_O'].astype(int)output_df['new_D'] = output_df['new_D'].astype(int)output_df['new_RPN'] = output_df['new_S'] * output_df['new_O'] * output_df['new_D']output_df['generated_at'] = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")rpn_change_list = [f"{int(rpn)} β {int(new_rpn)}" for new_rpn in output_df['new_RPN']]display_df = pd.DataFrame({"Rank": output_df['rank'],"Recommended Action": output_df['action'],"Action Details": output_df['action_details'],"Department": output_df['department'],"AI Confidence": [f"{score}%" for score in output_df['ai_score']],"Avg. Feedback": [f"{avg:.2f}/10 ({int(count)})" for avg, count in zip(output_df['avg_feedback'], output_df['feedback_count'])],"Revised RPN": rpn_change_list,"Generated At (UTC)": output_df['generated_at']})except Exception as e:38 unmodified linesgr.Markdown("## π‘ Top 3 AI-Generated Recommendations")rpn_output = gr.Textbox(label="Current RPN", interactive=False)recommendations_output = gr.DataFrame(headers=["Rank", "Recommended Action", "Action Details", "Department", "AI Confidence", "Avg. Feedback", "Revised RPN", "Generated At (UTC)"],datatype=["number", "str", "str", "str", "str", "str", "str", "str"])df_state = gr.State()1 unmodified linegr.Markdown("## β Provide Feedback")gr.Markdown("Click a row in the table above to select it, then submit your rating.")selected_action_text = gr.Textbox(label="Selected for Feedback", interactive=False)feedback_choice = gr.Radio(choices=["π Thumbs Up", "π Thumbs Down"],value="π Thumbs Up",label="Your Feedback")submit_feedback_btn = gr.Button("Submit Feedback")feedback_status = gr.Textbox(label="Feedback Status", interactive=False)# FIX 1: Safer update_selection function20 unmodified linessubmit_feedback_btn.click(fn=save_feedback,inputs=[selected_action_text, feedback_choice, recommendations_output],outputs=[feedback_status, recommendations_output])
__pycache__/app.cpython-311.pyc
app.py+108-27