ankush-003 commited on
Commit
6e8bd08
1 Parent(s): 44cb6c6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -0
app.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from langchain_community.vectorstores import MongoDBAtlasVectorSearch
4
+ from langchain_community.embeddings import HuggingFaceEmbeddings
5
+ import pymongo
6
+ import logging
7
+ import nest_asyncio
8
+ from langchain.docstore.document import Document
9
+ import redis
10
+ import asyncio
11
+ import threading
12
+ import time
13
+
14
+ # Config
15
+ nest_asyncio.apply()
16
+ logging.basicConfig(level=logging.INFO)
17
+ database = "AlertSimAndRemediation"
18
+ collection = "alert_embed"
19
+ stream_name = "alerts"
20
+
21
+ # Environment variables
22
+ MONGO_URI = os.getenv('MONGO_URI')
23
+ REDIS_HOST = os.getenv('REDIS_HOST')
24
+ REDIS_PWD = os.getenv('REDIS_PWD')
25
+
26
+ # Embedding model
27
+ embedding_args = {
28
+ "model_name": "BAAI/bge-large-en-v1.5",
29
+ "model_kwargs": {"device": "cpu"},
30
+ "encode_kwargs": {"normalize_embeddings": True}
31
+ }
32
+ embedding_model = HuggingFaceEmbeddings(**embedding_args)
33
+
34
+ # MongoDB connection
35
+ connection = pymongo.MongoClient(MONGO_URI)
36
+ alert_collection = connection[database][collection]
37
+
38
+ # Redis connection
39
+ r = redis.Redis(host=REDIS_HOST, password=REDIS_PWD, port=16652)
40
+
41
+ # Global variables to store alert information
42
+ latest_alert = "No alerts yet."
43
+ alert_count = 0
44
+
45
+ # Preprocessing
46
+ def create_textual_description(entry_data):
47
+ entry_dict = {k.decode(): v.decode() for k, v in entry_data.items()}
48
+
49
+ category = entry_dict["Category"]
50
+ created_at = entry_dict["CreatedAt"]
51
+ acknowledged = "Acknowledged" if entry_dict["Acknowledged"] == "1" else "Not Acknowledged"
52
+ remedy = entry_dict["Remedy"]
53
+ severity = entry_dict["Severity"]
54
+ source = entry_dict["Source"]
55
+ node = entry_dict["node"]
56
+
57
+ description = f"A {severity} alert of category {category} was raised from the {source} source for node {node} at {created_at}. The alert is {acknowledged}. The recommended remedy is: {remedy}."
58
+
59
+ return description, entry_dict
60
+
61
+ # Saving alert doc
62
+ def save(entry):
63
+ vector_search = MongoDBAtlasVectorSearch.from_documents(
64
+ documents=[Document(
65
+ page_content=entry["content"],
66
+ metadata=entry["metadata"]
67
+ )],
68
+ embedding=embedding_model,
69
+ collection=alert_collection,
70
+ index_name="alert_index",
71
+ )
72
+ logging.info("Alert stored successfully!")
73
+
74
+ # Listening to alert stream
75
+ def listen_to_alerts():
76
+ global latest_alert, alert_count
77
+ last_id = '$'
78
+
79
+ while True:
80
+ entries = r.xread({stream_name: last_id}, block=1000, count=None)
81
+
82
+ if entries:
83
+ stream, new_entries = entries[0]
84
+
85
+ for entry_id, entry_data in new_entries:
86
+ description, entry_dict = create_textual_description(entry_data)
87
+ save({
88
+ "content": description,
89
+ "metadata": entry_dict
90
+ })
91
+ latest_alert = description
92
+ alert_count += 1
93
+ last_id = entry_id
94
+
95
+ # Start listening to alerts in a separate thread
96
+ threading.Thread(target=listen_to_alerts, daemon=True).start()
97
+
98
+ # Function to get current stats
99
+ def get_current_stats():
100
+ return latest_alert, f"Total Alerts: {alert_count}"
101
+
102
+ # Gradio interface
103
+ def create_interface():
104
+ with gr.Blocks() as iface:
105
+ gr.Markdown("# Alert Monitoring Service")
106
+ with gr.Row():
107
+ latest_alert_md = gr.Markdown("Waiting for alerts...")
108
+ with gr.Row():
109
+ alert_count_md = gr.Markdown("Total Alerts: 0")
110
+
111
+ def update_stats():
112
+ while True:
113
+ time.sleep(1) # Update every second
114
+ yield get_current_stats()
115
+
116
+ iface.load(update_stats, None, [latest_alert_md, alert_count_md], every=1)
117
+
118
+ return iface
119
+
120
+ # Launch the app
121
+ if __name__ == "__main__":
122
+ iface = create_interface()
123
+ iface.queue().launch()