ressay1973 commited on
Commit
f8a2d26
·
verified ·
1 Parent(s): 69dfb5c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -40
app.py CHANGED
@@ -1,69 +1,91 @@
1
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
- import requests
4
  import pytz
5
  import yaml
 
6
  from tools.final_answer import FinalAnswerTool
7
  from Gradio_UI import GradioUI
8
 
9
- # Herramienta para clasificar alertas P1, P2, P3 basado en criterios de la tabla
 
 
 
10
  @tool
11
- def classify_alert(service_criticity: str, disruption: str, affectation_time: str, magnitude: str, business_workaround: str) -> str:
12
- """Clasifica una alerta en P1, P2 o P3 según los criterios especificados.
13
  Args:
14
- service_criticity: 'High' o 'Low'
15
- disruption: 'Full', 'Degraded', 'None'
16
- affectation_time: 'Up 15 mins' o 'Less 15 mins'
17
- magnitude: 'High', 'Low', 'None'
18
- business_workaround: 'Yes' o 'No'
19
  """
20
- if service_criticity == "High" and disruption in ["Full", "Degraded"] and magnitude == "High" and business_workaround == "No":
21
- return "P1 - Crítico"
22
- elif service_criticity == "High" and (disruption in ["Full", "Degraded"] or affectation_time == "Up 15 mins"):
23
- return "P2 - Importante"
24
- else:
25
- return "P3 - Menor"
 
 
 
 
26
 
27
- # Herramienta para generar resúmenes de reportes de infraestructura
28
  @tool
29
- def summarize_report(report_text: str) -> str:
30
- """Genera un resumen de un reporte sobre la infraestructura de la plataforma.
31
  Args:
32
- report_text: Texto del reporte.
33
  """
34
- api_url = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
35
- headers = {"Authorization": "Bearer YOUR_HF_API_KEY"}
36
- payload = {"inputs": report_text}
37
-
38
- response = requests.post(api_url, headers=headers, json=payload)
39
- if response.status_code == 200:
40
- return response.json()[0]['summary_text']
41
- else:
42
- return "Error al generar el resumen."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- # Definir el modelo
45
- model = HfApiModel(
46
- model_name="meta-llama/Llama-2-13b-chat-hf",
47
- api_key="YOUR_HF_API_KEY"
48
- )
49
 
50
  final_answer = FinalAnswerTool()
51
 
52
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
 
 
 
 
53
 
54
- # Cargar plantillas de prompts
55
  with open("prompts.yaml", 'r') as stream:
56
  prompt_templates = yaml.safe_load(stream)
57
-
58
  agent = CodeAgent(
59
  model=model,
60
- tools=[final_answer, classify_alert, summarize_report, image_generation_tool],
61
  max_steps=6,
62
  verbosity_level=1,
63
  grammar=None,
64
  planning_interval=None,
65
- name=None,
66
- description=None,
67
  prompt_templates=prompt_templates
68
  )
69
 
 
1
+ from smolagents import CodeAgent, HfApiModel, load_tool, tool
2
  import datetime
 
3
  import pytz
4
  import yaml
5
+ from transformers import pipeline
6
  from tools.final_answer import FinalAnswerTool
7
  from Gradio_UI import GradioUI
8
 
9
+ # Initialize ASR model from Hugging Face
10
+ asr_pipeline = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-large-960h")
11
+
12
+ # Tool: Convert time between time zones
13
  @tool
14
+ def convert_time(time_str: str, from_tz: str, to_tz: str) -> str:
15
+ """Convert time from one timezone to another.
16
  Args:
17
+ time_str: Time in 'YYYY-MM-DD HH:MM:SS' format.
18
+ from_tz: Original timezone.
19
+ to_tz: Target timezone.
 
 
20
  """
21
+ try:
22
+ from_zone = pytz.timezone(from_tz)
23
+ to_zone = pytz.timezone(to_tz)
24
+ local_time = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
25
+ local_time = from_zone.localize(local_time)
26
+ converted_time = local_time.astimezone(to_zone).strftime("%Y-%m-%d %H:%M:%S")
27
+ return f"Time in {to_tz}: {converted_time}"
28
+ except Exception as e:
29
+ return f"Error converting time: {str(e)}"
30
+
31
 
32
+ # Tool: Assign alerts to departments based on keywords
33
  @tool
34
+ def assign_alert(alert_message: str) -> str:
35
+ """Assign an alert to a department based on keywords.
36
  Args:
37
+ alert_message: The alert description.
38
  """
39
+ alert_keywords = {
40
+ "network": "Network Operations",
41
+ "server": "Infrastructure",
42
+ "database": "Database Team",
43
+ "security": "Security Operations",
44
+ "application": "Development Team"
45
+ }
46
+ for keyword, department in alert_keywords.items():
47
+ if keyword.lower() in alert_message.lower():
48
+ return f"Alert assigned to: {department}"
49
+ return "Alert could not be assigned automatically. Please check manually."
50
+
51
+
52
+ # Tool: Transcribe audio and generate a timeline using Hugging Face ASR
53
+ @tool
54
+ def transcribe_audio(audio_path: str) -> str:
55
+ """Transcribe audio and log events with timestamps.
56
+ Args:
57
+ audio_path: Path to the audio file.
58
+ """
59
+ try:
60
+ result = asr_pipeline(audio_path)
61
+ transcript = result["text"]
62
+ timestamped_events = [f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {line}" for line in transcript.split('.')]
63
+ return "\n".join(timestamped_events)
64
+ except Exception as e:
65
+ return f"Error transcribing audio: {str(e)}"
66
 
 
 
 
 
 
67
 
68
  final_answer = FinalAnswerTool()
69
 
70
+ model = HfApiModel(
71
+ max_tokens=2096,
72
+ temperature=0.5,
73
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
74
+ custom_role_conversions=None,
75
+ )
76
 
 
77
  with open("prompts.yaml", 'r') as stream:
78
  prompt_templates = yaml.safe_load(stream)
79
+
80
  agent = CodeAgent(
81
  model=model,
82
+ tools=[final_answer, convert_time, assign_alert, transcribe_audio],
83
  max_steps=6,
84
  verbosity_level=1,
85
  grammar=None,
86
  planning_interval=None,
87
+ name="Monitoring Assistant",
88
+ description="An agent that helps with alert assignment, time conversion, monitoring tasks, and real-time transcription.",
89
  prompt_templates=prompt_templates
90
  )
91