Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,116 +1,120 @@
|
|
1 |
import gradio as gr
|
2 |
import pandas as pd
|
3 |
-
import
|
4 |
-
from
|
|
|
5 |
from groq import Groq
|
6 |
|
7 |
# Initialize Groq API
|
8 |
client = Groq(api_key="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") # Replace with your Groq API key
|
9 |
|
10 |
-
#
|
11 |
-
def
|
12 |
-
resource_map = {
|
13 |
-
"Excavation": {"labor": 10, "equipment": "Excavator", "material": "Soil"},
|
14 |
-
"Foundation": {"labor": 15, "equipment": "Concrete Mixer", "material": "Concrete"},
|
15 |
-
"Framing": {"labor": 20, "equipment": "Cranes", "material": "Steel"},
|
16 |
-
"Finishing": {"labor": 5, "equipment": "Hand Tools", "material": "Paint"}
|
17 |
-
}
|
18 |
-
|
19 |
-
inferred_resources = []
|
20 |
-
for _, row in schedule.iterrows():
|
21 |
-
task = row["task"]
|
22 |
-
resources = resource_map.get(task, {"labor": 5, "equipment": "General", "material": "Standard"})
|
23 |
-
inferred_resources.append({
|
24 |
-
"task": task,
|
25 |
-
"labor": resources["labor"],
|
26 |
-
"equipment": resources["equipment"],
|
27 |
-
"material": resources["material"]
|
28 |
-
})
|
29 |
-
|
30 |
-
return pd.DataFrame(inferred_resources)
|
31 |
-
|
32 |
-
# Fill missing columns
|
33 |
-
def fill_missing_columns(schedule):
|
34 |
-
# Generate random dates if missing
|
35 |
-
if "start_date" not in schedule.columns:
|
36 |
-
schedule["start_date"] = [
|
37 |
-
(datetime.now() + timedelta(days=random.randint(1, 30))).strftime("%Y-%m-%d")
|
38 |
-
for _ in range(len(schedule))
|
39 |
-
]
|
40 |
-
if "end_date" not in schedule.columns:
|
41 |
-
schedule["end_date"] = [
|
42 |
-
(datetime.strptime(start, "%Y-%m-%d") + timedelta(days=random.randint(5, 15))).strftime("%Y-%m-%d")
|
43 |
-
for start in schedule["start_date"]
|
44 |
-
]
|
45 |
-
return schedule
|
46 |
-
|
47 |
-
# Mock optimization logic
|
48 |
-
def mock_optimize_schedule(schedule_with_resources):
|
49 |
-
optimized_schedule = []
|
50 |
-
conflicts = []
|
51 |
-
|
52 |
-
for _, row in schedule_with_resources.iterrows():
|
53 |
-
task = row["task"]
|
54 |
-
start_date = row["start_date"]
|
55 |
-
end_date = row["end_date"]
|
56 |
-
labor = row["labor"]
|
57 |
-
equipment = row["equipment"]
|
58 |
-
material = row["material"]
|
59 |
-
|
60 |
-
# Check for conflicts (mock logic)
|
61 |
-
if labor > 20: # Example conflict condition
|
62 |
-
conflicts.append(f"Task '{task}' exceeds labor capacity.")
|
63 |
-
|
64 |
-
optimized_schedule.append({
|
65 |
-
"task": task,
|
66 |
-
"start_date": start_date,
|
67 |
-
"end_date": end_date,
|
68 |
-
"labor": labor,
|
69 |
-
"equipment": equipment,
|
70 |
-
"material": material,
|
71 |
-
"conflict": "Yes" if f"Task '{task}' exceeds labor capacity." in conflicts else "No"
|
72 |
-
})
|
73 |
-
|
74 |
-
return pd.DataFrame(optimized_schedule), conflicts
|
75 |
-
|
76 |
-
# Main function for resource optimization
|
77 |
-
def optimize_resources(schedule_file):
|
78 |
try:
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
# Ensure the 'task' column exists
|
83 |
-
if "task" not in schedule.columns:
|
84 |
-
raise ValueError("The uploaded schedule must contain a 'task' column.")
|
85 |
-
|
86 |
-
# Fill missing columns
|
87 |
-
schedule = fill_missing_columns(schedule)
|
88 |
-
|
89 |
-
# Infer resources
|
90 |
-
inferred_resources = infer_resources(schedule)
|
91 |
-
schedule_with_resources = pd.concat([schedule, inferred_resources], axis=1)
|
92 |
-
|
93 |
-
# Perform optimization (mocked for now)
|
94 |
-
optimized_schedule_df, conflicts = mock_optimize_schedule(schedule_with_resources)
|
95 |
-
|
96 |
-
return optimized_schedule_df, "\n".join(conflicts) if conflicts else "No conflicts detected."
|
97 |
except Exception as e:
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
outputs=[
|
107 |
-
gr.
|
108 |
-
gr.
|
109 |
],
|
110 |
-
title="
|
111 |
-
description="Upload a
|
112 |
)
|
113 |
|
114 |
-
# Launch the app
|
115 |
if __name__ == "__main__":
|
116 |
-
|
|
|
1 |
import gradio as gr
|
2 |
import pandas as pd
|
3 |
+
from io import BytesIO
|
4 |
+
from fpdf import FPDF
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
from groq import Groq
|
7 |
|
8 |
# Initialize Groq API
|
9 |
client = Groq(api_key="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") # Replace with your Groq API key
|
10 |
|
11 |
+
# Function to interact with GROQ API for optimization
|
12 |
+
def optimize_schedule_with_groq(schedule):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
try:
|
14 |
+
optimized_schedule = client.optimize_schedule(schedule.to_dict(orient="records"))
|
15 |
+
return pd.DataFrame(optimized_schedule)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
except Exception as e:
|
17 |
+
print(f"Error using GROQ API: {e}")
|
18 |
+
raise e
|
19 |
+
|
20 |
+
# Function to generate PDF report
|
21 |
+
def generate_pdf_report(schedule, conflicts, cost_estimates):
|
22 |
+
pdf = FPDF()
|
23 |
+
pdf.set_auto_page_break(auto=True, margin=15)
|
24 |
+
pdf.add_page()
|
25 |
+
|
26 |
+
# Title
|
27 |
+
pdf.set_font("Arial", "B", 16)
|
28 |
+
pdf.cell(200, 10, txt="Project Schedule Optimization Report", ln=True, align="C")
|
29 |
+
|
30 |
+
# Schedule Table
|
31 |
+
pdf.set_font("Arial", "B", 12)
|
32 |
+
pdf.cell(200, 10, txt="Optimized Schedule", ln=True, align="L")
|
33 |
+
pdf.set_font("Arial", size=10)
|
34 |
+
for index, row in schedule.iterrows():
|
35 |
+
pdf.cell(0, 10, txt=f"{row['tasks']}: {row['start_date']} - {row['end_date']}", ln=True)
|
36 |
+
|
37 |
+
# Conflict Details
|
38 |
+
pdf.set_font("Arial", "B", 12)
|
39 |
+
pdf.cell(200, 10, txt="\nConflict Details", ln=True, align="L")
|
40 |
+
pdf.set_font("Arial", size=10)
|
41 |
+
for conflict in conflicts:
|
42 |
+
pdf.cell(0, 10, txt=f"{conflict}", ln=True)
|
43 |
+
|
44 |
+
# Cost Estimates
|
45 |
+
pdf.set_font("Arial", "B", 12)
|
46 |
+
pdf.cell(200, 10, txt="\nCost Estimates", ln=True, align="L")
|
47 |
+
pdf.set_font("Arial", size=10)
|
48 |
+
for resource, cost in cost_estimates.items():
|
49 |
+
pdf.cell(0, 10, txt=f"{resource}: ${cost:.2f}", ln=True)
|
50 |
+
|
51 |
+
# Save PDF to a buffer
|
52 |
+
buffer = BytesIO()
|
53 |
+
pdf.output(buffer)
|
54 |
+
buffer.seek(0)
|
55 |
+
return buffer
|
56 |
+
|
57 |
+
# Generate a sample visualization
|
58 |
+
def generate_visualization(schedule):
|
59 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
60 |
+
tasks = schedule['tasks']
|
61 |
+
start_dates = pd.to_datetime(schedule['start_date'])
|
62 |
+
end_dates = pd.to_datetime(schedule['end_date'])
|
63 |
+
durations = (end_dates - start_dates).dt.days
|
64 |
+
|
65 |
+
ax.barh(tasks, durations, left=start_dates.map(lambda x: x.toordinal()), color='skyblue')
|
66 |
+
ax.set_xlabel("Dates")
|
67 |
+
ax.set_ylabel("Tasks")
|
68 |
+
ax.set_title("Gantt Chart (Simplified)")
|
69 |
+
|
70 |
+
# Convert figure to BytesIO object
|
71 |
+
buf = BytesIO()
|
72 |
+
plt.savefig(buf, format='png')
|
73 |
+
buf.seek(0)
|
74 |
+
return buf
|
75 |
+
|
76 |
+
# Main function
|
77 |
+
def process_schedule(file):
|
78 |
+
schedule = pd.read_csv(file)
|
79 |
+
|
80 |
+
# Basic checks
|
81 |
+
if 'tasks' not in schedule.columns:
|
82 |
+
return "Error: 'tasks' column is mandatory.", None
|
83 |
+
|
84 |
+
# Infer missing columns (dummy inference for demonstration)
|
85 |
+
if 'start_date' not in schedule.columns:
|
86 |
+
schedule['start_date'] = pd.date_range("2025-01-01", periods=len(schedule))
|
87 |
+
if 'end_date' not in schedule.columns:
|
88 |
+
schedule['end_date'] = schedule['start_date'] + pd.to_timedelta(7, unit='d')
|
89 |
+
if 'required_resources' not in schedule.columns:
|
90 |
+
schedule['required_resources'] = ["Labor"] * len(schedule)
|
91 |
+
|
92 |
+
# Use GROQ API to optimize the schedule
|
93 |
+
optimized_schedule = optimize_schedule_with_groq(schedule)
|
94 |
+
|
95 |
+
# Placeholder conflict and cost calculations
|
96 |
+
conflicts = ["Task 1 and Task 2 overlap.", "Resource 'Crane' exceeds availability."]
|
97 |
+
cost_estimates = {"Labor": 5000, "Equipment": 2000}
|
98 |
+
|
99 |
+
# Generate PDF Report
|
100 |
+
pdf_report = generate_pdf_report(optimized_schedule, conflicts, cost_estimates)
|
101 |
+
|
102 |
+
# Generate Visualization
|
103 |
+
gantt_chart = generate_visualization(optimized_schedule)
|
104 |
+
|
105 |
+
return pdf_report, gantt_chart
|
106 |
+
|
107 |
+
# Gradio interface
|
108 |
+
iface = gr.Interface(
|
109 |
+
fn=process_schedule,
|
110 |
+
inputs=gr.File(label="Upload Schedule File (CSV)"),
|
111 |
outputs=[
|
112 |
+
gr.File(label="Download PDF Report"),
|
113 |
+
gr.Image(label="Visualization (Gantt Chart)")
|
114 |
],
|
115 |
+
title="Intelligent Resource Loading in Construction Schedule",
|
116 |
+
description="Upload a schedule file to generate a PDF report with optimized schedule, conflict details, cost estimates, and visualizations."
|
117 |
)
|
118 |
|
|
|
119 |
if __name__ == "__main__":
|
120 |
+
iface.launch()
|