ragaai-catalyst 2.1.5b25__py3-none-any.whl → 2.1.5b26__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,7 +13,7 @@ import traceback
13
13
  import importlib
14
14
  import sys
15
15
  from litellm import model_cost
16
- from llama_index.core.base.llms.types import ChatResponse
16
+ from llama_index.core.base.llms.types import ChatResponse,TextBlock, ChatMessage
17
17
 
18
18
  from .base import BaseTracer
19
19
  from ..utils.llm_utils import (
@@ -550,138 +550,132 @@ class LLMTracerMixin:
550
550
  error=None,
551
551
  parameters={},
552
552
  ):
553
- # Update total metrics
554
- self.total_tokens += usage.get("total_tokens", 0)
555
- self.total_cost += cost.get("total_cost", 0)
556
-
557
- network_calls = []
558
- if self.auto_instrument_network:
559
- network_calls = self.component_network_calls.get(component_id, [])
560
-
561
- interactions = []
562
- if self.auto_instrument_user_interaction:
563
- input_output_interactions = []
564
- for interaction in self.component_user_interaction.get(component_id, []):
565
- if interaction["interaction_type"] in ["input", "output"]:
566
- input_output_interactions.append(interaction)
567
- interactions.extend(input_output_interactions)
568
- if self.auto_instrument_file_io:
569
- file_io_interactions = []
570
- for interaction in self.component_user_interaction.get(component_id, []):
571
- if interaction["interaction_type"] in ["file_read", "file_write"]:
572
- file_io_interactions.append(interaction)
573
- interactions.extend(file_io_interactions)
574
-
575
- parameters_to_display = {}
576
- if "run_manager" in parameters:
577
- parameters_obj = parameters["run_manager"]
578
- if hasattr(parameters_obj, "metadata"):
579
- metadata = parameters_obj.metadata
580
- # parameters = {'metadata': metadata}
581
- parameters_to_display.update(metadata)
582
-
583
- # Add only those keys in parameters that are single values and not objects, dict or list
584
- for key, value in parameters.items():
585
- if isinstance(value, (str, int, float, bool)):
586
- parameters_to_display[key] = value
587
-
588
- # Limit the number of parameters to display
589
- parameters_to_display = dict(
590
- list(parameters_to_display.items())[: self.MAX_PARAMETERS_TO_DISPLAY]
591
- )
553
+ try:
554
+ # Update total metrics
555
+ self.total_tokens += usage.get("total_tokens", 0)
556
+ self.total_cost += cost.get("total_cost", 0)
557
+
558
+ network_calls = []
559
+ if self.auto_instrument_network:
560
+ network_calls = self.component_network_calls.get(component_id, [])
561
+
562
+ interactions = []
563
+ if self.auto_instrument_user_interaction:
564
+ input_output_interactions = []
565
+ for interaction in self.component_user_interaction.get(component_id, []):
566
+ if interaction["interaction_type"] in ["input", "output"]:
567
+ input_output_interactions.append(interaction)
568
+ interactions.extend(input_output_interactions)
569
+ if self.auto_instrument_file_io:
570
+ file_io_interactions = []
571
+ for interaction in self.component_user_interaction.get(component_id, []):
572
+ if interaction["interaction_type"] in ["file_read", "file_write"]:
573
+ file_io_interactions.append(interaction)
574
+ interactions.extend(file_io_interactions)
575
+
576
+ parameters_to_display = {}
577
+ if "run_manager" in parameters:
578
+ parameters_obj = parameters["run_manager"]
579
+ if hasattr(parameters_obj, "metadata"):
580
+ metadata = parameters_obj.metadata
581
+ # parameters = {'metadata': metadata}
582
+ parameters_to_display.update(metadata)
583
+
584
+ # Add only those keys in parameters that are single values and not objects, dict or list
585
+ for key, value in parameters.items():
586
+ if isinstance(value, (str, int, float, bool)):
587
+ parameters_to_display[key] = value
588
+
589
+ # Limit the number of parameters to display
590
+ parameters_to_display = dict(
591
+ list(parameters_to_display.items())[: self.MAX_PARAMETERS_TO_DISPLAY]
592
+ )
593
+
594
+ # Set the Context and GT
595
+ span_gt = None
596
+ span_context = None
597
+ if name in self.span_attributes_dict:
598
+ span_gt = self.span_attributes_dict[name].gt
599
+ span_context = self.span_attributes_dict[name].context
600
+
601
+ logger.debug(f"span context {span_context}, span_gt {span_gt}")
602
+
603
+ # Tags
604
+ tags = []
605
+ if name in self.span_attributes_dict:
606
+ tags = self.span_attributes_dict[name].tags or []
607
+
608
+ # Get End Time
609
+ end_time = datetime.now().astimezone().isoformat()
610
+
611
+ # Metrics
612
+ metrics = []
613
+ if name in self.span_attributes_dict:
614
+ raw_metrics = self.span_attributes_dict[name].metrics or []
615
+ for metric in raw_metrics:
616
+ base_metric_name = metric["name"]
617
+ counter = sum(1 for x in self.visited_metrics if x.startswith(base_metric_name))
618
+ metric_name = f'{base_metric_name}_{counter}' if counter > 0 else base_metric_name
619
+ self.visited_metrics.append(metric_name)
620
+ metric["name"] = metric_name
621
+ metrics.append(metric)
622
+
623
+ # TODO TO check i/p and o/p is according or not
624
+ input = input_data["args"] if hasattr(input_data, "args") else input_data
625
+ output = output_data.output_response if output_data else None
626
+ #print("Prompt input:",input)
627
+ prompt = self.convert_to_content(input)
628
+ #print("Prompt Output: ",prompt)
629
+ #print("Response input: ",output)
630
+ response = self.convert_to_content(output)
631
+ #print("Response output: ",response)
632
+
633
+ # TODO: Execute & Add the User requested metrics here
634
+ formatted_metrics = BaseTracer.get_formatted_metric(self.span_attributes_dict, self.project_id, name)
635
+ if formatted_metrics:
636
+ metrics.extend(formatted_metrics)
637
+
638
+ component = {
639
+ "id": component_id,
640
+ "hash_id": hash_id,
641
+ "source_hash_id": None,
642
+ "type": "llm",
643
+ "name": name,
644
+ "start_time": start_time,
645
+ "end_time": end_time,
646
+ "error": error,
647
+ "parent_id": self.current_agent_id.get(),
648
+ "info": {
649
+ "model": llm_type,
650
+ "version": version,
651
+ "memory_used": memory_used,
652
+ "cost": cost,
653
+ "tokens": usage,
654
+ "tags": tags,
655
+ **parameters_to_display,
656
+ },
657
+ "extra_info": parameters,
658
+ "data": {
659
+ "input": input,
660
+ "output": output,
661
+ "memory_used": memory_used,
662
+ },
663
+ "metrics": metrics,
664
+ "network_calls": network_calls,
665
+ "interactions": interactions,
666
+ }
667
+
668
+ # Assign context and gt if available
669
+ component["data"]["gt"] = span_gt
670
+ component["data"]["context"] = span_context
671
+
672
+ # Reset the SpanAttributes context variable
673
+ self.span_attributes_dict[name] = SpanAttributes(name)
674
+
675
+ return component
676
+ except Exception as e:
677
+ raise Exception("Failed to create LLM component")
592
678
 
593
- # Set the Context and GT
594
- span_gt = None
595
- span_context = None
596
- if name in self.span_attributes_dict:
597
- span_gt = self.span_attributes_dict[name].gt
598
- span_context = self.span_attributes_dict[name].context
599
-
600
- logger.debug(f"span context {span_context}, span_gt {span_gt}")
601
-
602
- # Tags
603
- tags = []
604
- if name in self.span_attributes_dict:
605
- tags = self.span_attributes_dict[name].tags or []
606
-
607
- # Get End Time
608
- end_time = datetime.now().astimezone().isoformat()
609
-
610
- # Metrics
611
- metrics = []
612
- if name in self.span_attributes_dict:
613
- raw_metrics = self.span_attributes_dict[name].metrics or []
614
- for metric in raw_metrics:
615
- base_metric_name = metric["name"]
616
- counter = sum(1 for x in self.visited_metrics if x.startswith(base_metric_name))
617
- metric_name = f'{base_metric_name}_{counter}' if counter > 0 else base_metric_name
618
- self.visited_metrics.append(metric_name)
619
- metric["name"] = metric_name
620
- metrics.append(metric)
621
-
622
- # TODO TO check i/p and o/p is according or not
623
- input = input_data["args"] if hasattr(input_data, "args") else input_data
624
- output = output_data.output_response if output_data else None
625
- #print("Prompt input:",input)
626
- prompt = self.convert_to_content(input)
627
- #print("Prompt Output: ",prompt)
628
- #print("Response input: ",output)
629
- response = self.convert_to_content(output)
630
- #print("Response output: ",response)
631
-
632
- # TODO: Execute & Add the User requested metrics here
633
- formatted_metrics = BaseTracer.get_formatted_metric(self.span_attributes_dict, self.project_id, name)
634
- if formatted_metrics:
635
- metrics.extend(formatted_metrics)
636
-
637
- component = {
638
- "id": component_id,
639
- "hash_id": hash_id,
640
- "source_hash_id": None,
641
- "type": "llm",
642
- "name": name,
643
- "start_time": start_time,
644
- "end_time": end_time,
645
- "error": error,
646
- "parent_id": self.current_agent_id.get(),
647
- "info": {
648
- "model": llm_type,
649
- "version": version,
650
- "memory_used": memory_used,
651
- "cost": cost,
652
- "tokens": usage,
653
- "tags": tags,
654
- **parameters_to_display,
655
- },
656
- "extra_info": parameters,
657
- "data": {
658
- "input": input,
659
- "output": output,
660
- "memory_used": memory_used,
661
- },
662
- "metrics": metrics,
663
- "network_calls": network_calls,
664
- "interactions": interactions,
665
- }
666
-
667
- # Assign context and gt if available
668
- component["data"]["gt"] = span_gt
669
- component["data"]["context"] = span_context
670
-
671
- # Reset the SpanAttributes context variable
672
- self.span_attributes_dict[name] = SpanAttributes(name)
673
-
674
- return component
675
-
676
- # def convert_to_content(self, input_data):
677
- # if isinstance(input_data, dict):
678
- # messages = input_data.get("kwargs", {}).get("messages", [])
679
- # elif isinstance(input_data, list):
680
- # messages = input_data
681
- # else:
682
- # return ""
683
- # return "\n".join(process_content(msg.get("content", "")) for msg in messages if msg.get("content"))
684
-
685
679
  def convert_to_content(self, input_data):
686
680
  try:
687
681
  if isinstance(input_data, dict):
@@ -689,7 +683,6 @@ class LLMTracerMixin:
689
683
  elif isinstance(input_data, list):
690
684
  if len(input_data)>0 and isinstance(input_data[0]['content'],ChatResponse):
691
685
  extracted_messages = []
692
-
693
686
  for item in input_data:
694
687
  chat_response = item.get('content')
695
688
  if hasattr(chat_response, 'message') and hasattr(chat_response.message, 'blocks'):
@@ -699,9 +692,10 @@ class LLMTracerMixin:
699
692
  messages=extracted_messages
700
693
  if isinstance(messages,list):
701
694
  return "\n".join(messages)
702
-
703
- #messages=[msg["content"] for msg in input_data if isinstance(msg, dict) and "content" in msg]
704
- #messages = [msg["content"].message for msg in input_data if isinstance(msg, dict) and "content" in msg and isinstance(msg["content"], ChatResponse)]
695
+ elif len(input_data)>0 and isinstance(input_data[0]['content'],TextBlock):
696
+ return " ".join(block.text for item in input_data for block in item['content'] if isinstance(block, TextBlock))
697
+ elif len(input_data)>0 and isinstance(input_data[0]['content'],ChatMessage):
698
+ return " ".join(block.text for block in input_data[0]['content'].blocks if isinstance(block, TextBlock))
705
699
  else:
706
700
  messages = input_data
707
701
  elif isinstance(input_data,ChatResponse):
@@ -709,10 +703,9 @@ class LLMTracerMixin:
709
703
  else:
710
704
  return ""
711
705
  res=""
712
- # try:
713
706
  res="\n".join(msg.get("content", "").strip() for msg in messages if msg.get("content"))
714
707
  except Exception as e:
715
- res=str(messages)
708
+ res=str(input_data)
716
709
  return res
717
710
 
718
711
  def process_content(content):
@@ -965,6 +958,10 @@ class LLMTracerMixin:
965
958
  metrics: List[Dict[str, Any]] = [],
966
959
  feedback: Optional[Any] = None,
967
960
  ):
961
+
962
+ start_memory = psutil.Process().memory_info().rss
963
+ start_time = datetime.now().astimezone().isoformat()
964
+
968
965
  if name not in self.span_attributes_dict:
969
966
  self.span_attributes_dict[name] = SpanAttributes(name)
970
967
  if tags:
@@ -996,7 +993,6 @@ class LLMTracerMixin:
996
993
  self.current_llm_call_name.set(name)
997
994
 
998
995
  def decorator(func):
999
- @self.file_tracker.trace_decorator
1000
996
  @functools.wraps(func)
1001
997
  async def async_wrapper(*args, **kwargs):
1002
998
  gt = kwargs.get("gt") if kwargs else None
@@ -1018,14 +1014,34 @@ class LLMTracerMixin:
1018
1014
  result = await func(*args, **kwargs)
1019
1015
  return result
1020
1016
  except Exception as e:
1021
- error_info = {
1022
- "error": {
1023
- "type": type(e).__name__,
1024
- "message": str(e),
1025
- "traceback": traceback.format_exc(),
1026
- "timestamp": datetime.now().astimezone().isoformat(),
1027
- }
1017
+ error_component = {
1018
+ "type": type(e).__name__,
1019
+ "message": str(e),
1020
+ "traceback": traceback.format_exc(),
1021
+ "timestamp": datetime.now().astimezone().isoformat(),
1028
1022
  }
1023
+
1024
+ # End tracking network calls for this component
1025
+ self.end_component(component_id)
1026
+
1027
+ end_memory = psutil.Process().memory_info().rss
1028
+ memory_used = max(0, end_memory - start_memory)
1029
+
1030
+ llm_component = self.create_llm_component(
1031
+ component_id=component_id,
1032
+ hash_id=generate_unique_hash(func, args, kwargs),
1033
+ name=name,
1034
+ llm_type="unknown",
1035
+ version=None,
1036
+ memory_used=memory_used,
1037
+ start_time=start_time,
1038
+ input_data=extract_input_data(args, kwargs, None),
1039
+ output_data=None,
1040
+ error=error_component,
1041
+ )
1042
+ self.llm_data = llm_component
1043
+ self.add_component(llm_component, is_error=True)
1044
+
1029
1045
  raise
1030
1046
  finally:
1031
1047
 
@@ -1070,7 +1086,6 @@ class LLMTracerMixin:
1070
1086
  )
1071
1087
  self.add_component(llm_component)
1072
1088
 
1073
- @self.file_tracker.trace_decorator
1074
1089
  @functools.wraps(func)
1075
1090
  def sync_wrapper(*args, **kwargs):
1076
1091
  gt = kwargs.get("gt") if kwargs else None
@@ -1093,14 +1108,34 @@ class LLMTracerMixin:
1093
1108
  result = func(*args, **kwargs)
1094
1109
  return result
1095
1110
  except Exception as e:
1096
- error_info = {
1097
- "error": {
1098
- "type": type(e).__name__,
1099
- "message": str(e),
1100
- "traceback": traceback.format_exc(),
1101
- "timestamp": datetime.now().astimezone().isoformat(),
1102
- }
1111
+ error_component = {
1112
+ "type": type(e).__name__,
1113
+ "message": str(e),
1114
+ "traceback": traceback.format_exc(),
1115
+ "timestamp": datetime.now().astimezone().isoformat(),
1103
1116
  }
1117
+
1118
+ # End tracking network calls for this component
1119
+ self.end_component(component_id)
1120
+
1121
+ end_memory = psutil.Process().memory_info().rss
1122
+ memory_used = max(0, end_memory - start_memory)
1123
+
1124
+ llm_component = self.create_llm_component(
1125
+ component_id=component_id,
1126
+ hash_id=generate_unique_hash(func, args, kwargs),
1127
+ name=name,
1128
+ llm_type="unknown",
1129
+ version=None,
1130
+ memory_used=memory_used,
1131
+ start_time=start_time,
1132
+ input_data=extract_input_data(args, kwargs, None),
1133
+ output_data=None,
1134
+ error=error_component,
1135
+ )
1136
+ self.llm_data = llm_component
1137
+ self.add_component(llm_component, is_error=True)
1138
+
1104
1139
  raise
1105
1140
  finally:
1106
1141
  llm_component = self.llm_data
@@ -236,6 +236,8 @@ class AgenticTracing(
236
236
  total_cost = 0.0
237
237
  total_tokens = 0
238
238
 
239
+ processed_components = set()
240
+
239
241
  def process_component(component):
240
242
  nonlocal total_cost, total_tokens
241
243
  # Convert component to dict if it's an object
@@ -243,6 +245,11 @@ class AgenticTracing(
243
245
  component.__dict__ if hasattr(component, "__dict__") else component
244
246
  )
245
247
 
248
+ comp_id = comp_dict.get("id") or comp_dict.get("component_id")
249
+ if comp_id in processed_components:
250
+ return # Skip if already processed
251
+ processed_components.add(comp_id)
252
+
246
253
  if comp_dict.get("type") == "llm":
247
254
  info = comp_dict.get("info", {})
248
255
  if isinstance(info, dict):
@@ -372,66 +379,6 @@ class AgenticTracing(
372
379
 
373
380
  # Handle error case
374
381
  if is_error:
375
- # Get the parent component if it exists
376
- parent_id = component_data.get("parent_id")
377
- children = self.agent_children.get()
378
-
379
- # Set parent_id for all children
380
- for child in children:
381
- child["parent_id"] = parent_id
382
-
383
- agent_tracer_mixin = AgentTracerMixin()
384
- agent_tracer_mixin.component_network_calls = self.component_network_calls
385
- agent_tracer_mixin.component_user_interaction = (
386
- self.component_user_interaction
387
- )
388
-
389
- agent_tracer_mixin.span_attributes_dict[self.current_agent_name.get()] = (
390
- SpanAttributes(self.current_agent_name.get())
391
- )
392
-
393
- # Create parent component with error info
394
- parent_component = agent_tracer_mixin.create_agent_component(
395
- component_id=parent_id,
396
- hash_id=str(uuid.uuid4()),
397
- source_hash_id=None,
398
- type="agent",
399
- name=self.current_agent_name.get(),
400
- agent_type=self.agent_type.get(),
401
- version=self.version.get(),
402
- capabilities=self.capabilities.get(),
403
- start_time=self.start_time,
404
- end_time=datetime.now().astimezone().isoformat(),
405
- memory_used=0,
406
- input_data=self.input_data,
407
- output_data=None,
408
- children=children,
409
- parent_id=None, # Add parent ID if exists
410
- )
411
-
412
- filtered_data = {
413
- k: v
414
- for k, v in parent_component.items()
415
- if k
416
- in [
417
- "id",
418
- "hash_id",
419
- "source_hash_id",
420
- "type",
421
- "name",
422
- "start_time",
423
- "end_time",
424
- "parent_id",
425
- "info",
426
- "data",
427
- "network_calls",
428
- "interactions",
429
- "error",
430
- ]
431
- }
432
- parent_agent_component = AgentComponent(**filtered_data)
433
- # Add the parent component to trace and stop tracing
434
- super().add_component(parent_agent_component)
435
382
  self.stop()
436
383
 
437
384
  def __enter__(self):
@@ -255,7 +255,6 @@ class ToolTracerMixin:
255
255
  # Check if the function is async
256
256
  is_async = asyncio.iscoroutinefunction(func)
257
257
 
258
- @self.file_tracker.trace_decorator
259
258
  @functools.wraps(func)
260
259
  async def async_wrapper(*args, **kwargs):
261
260
  async_wrapper.metadata = metadata
@@ -267,7 +266,6 @@ class ToolTracerMixin:
267
266
  func, name, tool_type, version, *args, **kwargs
268
267
  )
269
268
 
270
- @self.file_tracker.trace_decorator
271
269
  @functools.wraps(func)
272
270
  def sync_wrapper(*args, **kwargs):
273
271
  sync_wrapper.metadata = metadata
@@ -309,7 +307,7 @@ class ToolTracerMixin:
309
307
 
310
308
  try:
311
309
  # Execute the tool
312
- result = self.file_tracker.trace_wrapper(func)(*args, **kwargs)
310
+ result = func(*args, **kwargs)
313
311
 
314
312
  # Calculate resource usage
315
313
  end_memory = psutil.Process().memory_info().rss
@@ -359,7 +357,7 @@ class ToolTracerMixin:
359
357
  error=error_component,
360
358
  )
361
359
 
362
- self.add_component(tool_component)
360
+ self.add_component(tool_component, is_error=True)
363
361
 
364
362
  raise
365
363
  finally:
@@ -391,7 +389,7 @@ class ToolTracerMixin:
391
389
  self.start_component(component_id)
392
390
  try:
393
391
  # Execute the tool
394
- result = await self.file_tracker.trace_wrapper(func)(*args, **kwargs)
392
+ result = await func(*args, **kwargs)
395
393
 
396
394
  # Calculate resource usage
397
395
  end_memory = psutil.Process().memory_info().rss
@@ -434,7 +432,7 @@ class ToolTracerMixin:
434
432
  output_data=None,
435
433
  error=error_component,
436
434
  )
437
- self.add_component(tool_component)
435
+ self.add_component(tool_component, is_error=True)
438
436
 
439
437
  raise
440
438
  finally:
@@ -62,4 +62,8 @@ class TrackName:
62
62
 
63
63
  def reset(self):
64
64
  """Reset the file tracker by clearing all tracked files."""
65
- self.files.clear()
65
+ self.files.clear()
66
+
67
+ def trace_main_file(self):
68
+ frame = inspect.stack()[-1]
69
+ self.files.add(frame.filename)
@@ -211,7 +211,6 @@ def comment_magic_commands(script_content: str) -> str:
211
211
  class TraceDependencyTracker:
212
212
  def __init__(self, output_dir=None):
213
213
  self.tracked_files = set()
214
- self.python_imports = set()
215
214
  self.notebook_path = None
216
215
  self.colab_content = None
217
216
 
@@ -302,7 +301,7 @@ class TraceDependencyTracker:
302
301
  except (UnicodeDecodeError, IOError):
303
302
  pass
304
303
 
305
- def analyze_python_imports(self, filepath):
304
+ def analyze_python_imports(self, filepath, ignored_locations):
306
305
  try:
307
306
  with open(filepath, 'r', encoding='utf-8') as file:
308
307
  tree = ast.parse(file.read(), filename=filepath)
@@ -315,8 +314,10 @@ class TraceDependencyTracker:
315
314
  module_name = name.name.split('.')[0]
316
315
  try:
317
316
  spec = importlib.util.find_spec(module_name)
318
- if spec and spec.origin and not spec.origin.startswith(os.path.dirname(importlib.__file__)):
319
- self.python_imports.add(spec.origin)
317
+ if spec and spec.origin:
318
+ if not (any(spec.origin.startswith(location) for location in ignored_locations) or (spec.origin in ['built-in', 'frozen'])):
319
+ self.tracked_files.add(spec.origin)
320
+ self.analyze_python_imports(spec.origin, ignored_locations)
320
321
  except (ImportError, AttributeError):
321
322
  pass
322
323
  except Exception as e:
@@ -332,6 +333,13 @@ class TraceDependencyTracker:
332
333
  except ImportError:
333
334
  logger.error("Error getting Catalyst location")
334
335
  return 'ragaai_catalyst'
336
+
337
+ def should_ignore_path(self, path, main_filepaths):
338
+ if any(os.path.abspath(path) in os.path.abspath(main_filepath) for main_filepath in main_filepaths):
339
+ return False
340
+ if path in ['', os.path.abspath('')]:
341
+ return False
342
+ return True
335
343
 
336
344
  def create_zip(self, filepaths):
337
345
  self.track_jupyter_notebook()
@@ -349,21 +357,31 @@ class TraceDependencyTracker:
349
357
  # Get current cell content
350
358
  self.check_environment_and_save()
351
359
 
360
+ env_location = self.get_env_location()
361
+ catalyst_location = self.get_catalyst_location()
362
+
352
363
  # Process all files (existing code)
364
+ ignored_locations = [env_location, catalyst_location] + [path for path in sys.path if self.should_ignore_path(path, filepaths)]
353
365
  for filepath in filepaths:
354
366
  abs_path = os.path.abspath(filepath)
355
367
  self.track_file_access(abs_path)
356
368
  try:
357
- with open(abs_path, 'r', encoding='utf-8') as file:
369
+ if filepath.endswith('.py'):
370
+ self.analyze_python_imports(abs_path, ignored_locations)
371
+ except Exception as e:
372
+ pass
373
+
374
+ for filepath in self.tracked_files:
375
+ try:
376
+ with open(filepath, 'r', encoding='utf-8') as file:
358
377
  content = file.read()
359
378
  # Comment out magic commands before processing
360
379
  content = comment_magic_commands(content)
361
- self.find_config_files(content, abs_path)
362
- if filepath.endswith('.py'):
363
- self.analyze_python_imports(abs_path)
380
+ self.find_config_files(content, filepath)
364
381
  except Exception as e:
365
382
  pass
366
383
 
384
+
367
385
  notebook_content_str = None
368
386
  if self.notebook_path and os.path.exists(self.notebook_path):
369
387
  try:
@@ -386,11 +404,7 @@ class TraceDependencyTracker:
386
404
  except Exception as e:
387
405
  pass
388
406
 
389
- env_location = self.get_env_location()
390
- catalyst_location = self.get_catalyst_location()
391
-
392
407
  # Calculate hash and create zip
393
- self.tracked_files.update(self.python_imports)
394
408
  hash_contents = []
395
409
 
396
410
  for filepath in sorted(self.tracked_files):