Darshanpurohit commited on
Commit
58c740a
·
verified ·
1 Parent(s): d9b52a6

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +25 -18
main.py CHANGED
@@ -26,10 +26,15 @@ except ImportError:
26
 
27
  app = FastAPI()
28
 
29
- # Enable CORS for frontend communication
 
 
 
 
 
30
  app.add_middleware(
31
  CORSMiddleware,
32
- allow_origins=["*"],
33
  allow_credentials=True,
34
  allow_methods=["*"],
35
  allow_headers=["*"],
@@ -56,25 +61,19 @@ class PipelineResponse(BaseModel):
56
 
57
 
58
  def is_dag(nodes: List[Node], edges: List[Edge]) -> bool:
59
- """
60
- Check if the graph is a Directed Acyclic Graph (DAG) using Kahn's algorithm.
61
- Returns True if the graph is a DAG (no cycles), False otherwise.
62
- """
63
- # Build adjacency list and calculate in-degrees
64
  graph = defaultdict(list)
65
  in_degree = defaultdict(int)
66
 
67
- # Initialize all nodes with in-degree 0
68
  node_ids = {node.id for node in nodes}
69
  for node_id in node_ids:
70
  in_degree[node_id] = 0
71
 
72
- # Build graph and calculate in-degrees
73
  for edge in edges:
 
 
74
  graph[edge.source].append(edge.target)
75
  in_degree[edge.target] += 1
76
 
77
- # Kahn's algorithm: Start with nodes that have in-degree 0
78
  queue = deque([node_id for node_id in node_ids if in_degree[node_id] == 0])
79
  visited_count = 0
80
 
@@ -82,16 +81,19 @@ def is_dag(nodes: List[Node], edges: List[Edge]) -> bool:
82
  current = queue.popleft()
83
  visited_count += 1
84
 
85
- # Reduce in-degree for all neighbors
86
  for neighbor in graph[current]:
87
  in_degree[neighbor] -= 1
88
  if in_degree[neighbor] == 0:
89
  queue.append(neighbor)
90
 
91
- # If we visited all nodes, there's no cycle (it's a DAG)
92
  return visited_count == len(node_ids)
93
 
94
 
 
 
 
 
 
95
  @app.get('/')
96
  def read_root():
97
  return {'Ping': 'Pong'}
@@ -107,9 +109,15 @@ def parse_pipeline(pipeline: PipelineRequest):
107
  """
108
  num_nodes = len(pipeline.nodes)
109
  num_edges = len(pipeline.edges)
110
- dag_status = is_dag(pipeline.nodes, pipeline.edges)
 
111
 
112
- message = "Valid DAG pipeline" if dag_status else "Invalid: Contains cycles"
 
 
 
 
 
113
 
114
  return PipelineResponse(
115
  num_nodes=num_nodes,
@@ -220,7 +228,7 @@ def get_available_models():
220
  class ExecutionNode(BaseModel):
221
  id: str
222
  type: str
223
- data: Dict[str, Any] = {}
224
 
225
 
226
  class ExecutionEdge(BaseModel):
@@ -234,7 +242,7 @@ class ExecutionEdge(BaseModel):
234
  class ExecutePipelineRequest(BaseModel):
235
  nodes: List[ExecutionNode]
236
  edges: List[ExecutionEdge]
237
- inputs: Dict[str, Any] = {}
238
 
239
 
240
  class ExecutePipelineResponse(BaseModel):
@@ -285,7 +293,6 @@ async def execute_node(node: ExecutionNode, inputs: Dict[str, Any], api_key: Opt
285
  # If there's a file upload, try to extract content
286
  if file_upload and isinstance(file_upload, dict):
287
  file_name = file_upload.get('name', '')
288
- file_type = file_upload.get('type', '')
289
  file_content = file_upload.get('content') # Actual text content from browser
290
 
291
  if file_content:
@@ -430,7 +437,7 @@ async def execute_node(node: ExecutionNode, inputs: Dict[str, Any], api_key: Opt
430
  elif node_type == 'delay':
431
  # Delay node
432
  import asyncio
433
- duration = int(data.get('duration', 1))
434
  unit = data.get('unit', 'seconds')
435
 
436
  delay_seconds = duration / 1000 if unit == 'milliseconds' else duration * 60 if unit == 'minutes' else duration
 
26
 
27
  app = FastAPI()
28
 
29
+ CORS_ORIGINS = [
30
+ origin.strip()
31
+ for origin in os.getenv("CORS_ORIGINS", "http://localhost:3000,http://127.0.0.1:3000").split(",")
32
+ if origin.strip()
33
+ ]
34
+
35
  app.add_middleware(
36
  CORSMiddleware,
37
+ allow_origins=CORS_ORIGINS,
38
  allow_credentials=True,
39
  allow_methods=["*"],
40
  allow_headers=["*"],
 
61
 
62
 
63
  def is_dag(nodes: List[Node], edges: List[Edge]) -> bool:
 
 
 
 
 
64
  graph = defaultdict(list)
65
  in_degree = defaultdict(int)
66
 
 
67
  node_ids = {node.id for node in nodes}
68
  for node_id in node_ids:
69
  in_degree[node_id] = 0
70
 
 
71
  for edge in edges:
72
+ if edge.source not in node_ids or edge.target not in node_ids:
73
+ return False
74
  graph[edge.source].append(edge.target)
75
  in_degree[edge.target] += 1
76
 
 
77
  queue = deque([node_id for node_id in node_ids if in_degree[node_id] == 0])
78
  visited_count = 0
79
 
 
81
  current = queue.popleft()
82
  visited_count += 1
83
 
 
84
  for neighbor in graph[current]:
85
  in_degree[neighbor] -= 1
86
  if in_degree[neighbor] == 0:
87
  queue.append(neighbor)
88
 
 
89
  return visited_count == len(node_ids)
90
 
91
 
92
+ def has_valid_edges(nodes: List[Node], edges: List[Edge]) -> bool:
93
+ node_ids = {node.id for node in nodes}
94
+ return all(edge.source in node_ids and edge.target in node_ids for edge in edges)
95
+
96
+
97
  @app.get('/')
98
  def read_root():
99
  return {'Ping': 'Pong'}
 
109
  """
110
  num_nodes = len(pipeline.nodes)
111
  num_edges = len(pipeline.edges)
112
+ valid_edges = has_valid_edges(pipeline.nodes, pipeline.edges)
113
+ dag_status = valid_edges and is_dag(pipeline.nodes, pipeline.edges)
114
 
115
+ if dag_status:
116
+ message = "Valid DAG pipeline"
117
+ elif not valid_edges:
118
+ message = "Invalid: Contains edges connected to missing nodes"
119
+ else:
120
+ message = "Invalid: Contains cycles"
121
 
122
  return PipelineResponse(
123
  num_nodes=num_nodes,
 
228
  class ExecutionNode(BaseModel):
229
  id: str
230
  type: str
231
+ data: Dict[str, Any] = Field(default_factory=dict)
232
 
233
 
234
  class ExecutionEdge(BaseModel):
 
242
  class ExecutePipelineRequest(BaseModel):
243
  nodes: List[ExecutionNode]
244
  edges: List[ExecutionEdge]
245
+ inputs: Dict[str, Any] = Field(default_factory=dict)
246
 
247
 
248
  class ExecutePipelineResponse(BaseModel):
 
293
  # If there's a file upload, try to extract content
294
  if file_upload and isinstance(file_upload, dict):
295
  file_name = file_upload.get('name', '')
 
296
  file_content = file_upload.get('content') # Actual text content from browser
297
 
298
  if file_content:
 
437
  elif node_type == 'delay':
438
  # Delay node
439
  import asyncio
440
+ duration = int(data.get('delay', data.get('duration', 1)))
441
  unit = data.get('unit', 'seconds')
442
 
443
  delay_seconds = duration / 1000 if unit == 'milliseconds' else duration * 60 if unit == 'minutes' else duration