File size: 234,652 Bytes
b4d1e5f
 
 
 
 
cfecef0
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
9754fd0
 
 
 
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
 
 
 
 
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
 
 
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
9754fd0
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
 
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
 
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9754fd0
 
 
 
 
 
 
 
b4d1e5f
 
 
 
 
9754fd0
 
 
 
b4d1e5f
 
9754fd0
 
b4d1e5f
9754fd0
b4d1e5f
9754fd0
 
 
 
b4d1e5f
 
 
9754fd0
 
 
 
b4d1e5f
 
 
9754fd0
 
 
 
 
 
 
b4d1e5f
9754fd0
 
 
 
 
 
b4d1e5f
9754fd0
 
 
b4d1e5f
9754fd0
b4d1e5f
9754fd0
b4d1e5f
 
 
 
 
9754fd0
 
 
 
b4d1e5f
 
 
 
9754fd0
 
 
 
b4d1e5f
9754fd0
 
b4d1e5f
9754fd0
 
 
b4d1e5f
9754fd0
b4d1e5f
 
 
 
9754fd0
b4d1e5f
9754fd0
b4d1e5f
9754fd0
 
 
 
 
 
 
 
 
 
b4d1e5f
9754fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
 
9754fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
9754fd0
 
 
 
b4d1e5f
9754fd0
b4d1e5f
9754fd0
 
 
 
b4d1e5f
9754fd0
 
 
 
 
 
b4d1e5f
9754fd0
 
b4d1e5f
9754fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
 
9754fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
9754fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
 
 
 
9754fd0
 
 
b4d1e5f
9754fd0
b4d1e5f
9754fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d1e5f
 
 
 
 
 
 
 
 
 
9754fd0
b4d1e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
# Standard library imports
import collections
import os
import pickle

from PIL import Image
import io
import base64

# Third-party imports
import matplotlib.pyplot as plt
import openai
import pandas as pd
import numpy as np
import requests
import random
import streamlit as st
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from streamlit_option_menu import option_menu

# Local/application-specific imports
from langchain.chains import RetrievalQA
from langchain.chains.summarize import load_summarize_chain
from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import WebBaseLoader, YoutubeLoader
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts.chat import (
    ChatPromptTemplate,
    HumanMessagePromptTemplate,
    SystemMessagePromptTemplate
)
from langchain.text_splitter import TokenTextSplitter, CharacterTextSplitter
from langchain.vectorstores import Chroma, FAISS
from langchain.llms import OpenAI
from langchain.chains.question_answering import load_qa_chain
from langchain.callbacks import get_openai_callback

st.set_option('deprecation.showPyplotGlobalUse', False)

# Load and set our key
openai.api_key = open("key.txt", "r").read().strip("\n")

st.set_page_config(page_title="Sustainable Shipping and Logistics Advisor", page_icon="GH", initial_sidebar_state="expanded")

hide_streamlit_style = """
            <style>
            #MainMenu {visibility: hidden;}
            footer {visibility: hidden;}
            </style>
            """
st.markdown(hide_streamlit_style, unsafe_allow_html=True)

css_style = {
    "icon": {"color": "white"},
    "nav-link": {"--hover-color": "grey"},
    "nav-link-selected": {"background-color": "#FF4C1B"},
}

def home_page():

    st.write("<center><h1>Sustainable Shipping and Logistics Advisor</h1></center>", unsafe_allow_html=True)

    st.image("main.png", use_column_width=True)

    st.write(f"""<h2>The Challenge</h2>
    <p>The shipping, port, and logistics industry faces growing sustainability challenges in the face of increasing global trade and environmental awareness. Key factors and challenges include:</p>
    <ul>
        <li>Rising carbon emissions from global shipping operations.</li>
        <li>Waste management challenges in ports and logistics facilities.</li>
        <li>Operational inefficiencies leading to increased environmental footprint.</li>
        <li>Lack of integration of green technologies and renewable energy sources.</li>
        <li>Increasing regulatory and compliance pressures.</li>
        <li>Growing consumer demand for sustainable shipping options.</li>
        <li>Impact of shipping activities on marine biodiversity.</li>
        <li>Resource depletion and increasing waste generation.</li>
        <li>Addressing the socio-economic aspects of sustainability in shipping communities.</li>
    </ul>
    <p>To navigate these challenges, the industry requires comprehensive strategies and tools that can assess, manage, and mitigate its environmental and social impact, while also ensuring operational efficiency and profitability.</p>
    """, unsafe_allow_html=True)

    st.write(f"""<h2>Project Goals</h2>
    <p>The Sustainable Shipping and Logistics Advisor aims to champion sustainability in the shipping, port, and logistics domain by:</p>
    <ul>
        <li>Quantifying Carbon Emissions: Providing tools to measure and analyze carbon footprints of shipping operations.</li>
        <li>Offering Sustainability Insights: Generating personalized advice for businesses to optimize operations, reduce emissions, and implement green technologies.</li>
        <li>Promoting Green Practices: Educating stakeholders about best practices in sustainable shipping and logistics.</li>
        <li>Facilitating Sustainable Decisions: Empowering businesses with the information and tools they need to make sustainability-driven decisions in their operations.</li>
    </ul>
    <p>By achieving these goals, the Sustainable Shipping and Logistics Advisor aims to transform the industry towards a more sustainable future, fostering environmental responsibility and economic growth.</p>
    """, unsafe_allow_html=True)

def about_page():
    st.write("<center><h1>Sustainable Shipping and Logistics Advisor</h1></center>", unsafe_allow_html=True)

    st.image("about.png", use_column_width=True)
    st.write("""
    <p>The Sustainable Shipping and Logistics Advisor is an ambitious project stemming from the AI for Good 2023 Hackathon, organized by Quy Nhon AI Community. This hackathon, with its emphasis on leveraging the immense potential of Artificial Intelligence for social benefits, serves as an innovative platform where technology and sustainability meet. Our commitment to AI-driven solutions is underpinned by a belief that such technology can significantly propel the maritime sector towards a sustainable trajectory.</p>

    <p>The focal objectives of the AI for Good 2023 Hackathon are:</p>

    <ul>
        <li><strong>Empower with AI:</strong> The hackathon seeks to push the boundaries of AI, venturing beyond conventional realms, to address complex socio-economic challenges.</li>
        <li><strong>Cultivate Technological Advancement:</strong> By fostering an environment of collaboration and innovation, the hackathon aspires to spur developments in AI that are both revolutionary and beneficial for society.</li>
        <li><strong>Champion Sustainable Solutions:</strong> With an eye on the broader horizon, the hackathon emphasizes AI solutions that are sustainable, ethical, and poised to make a long-lasting positive impact.</li>
    </ul>

    <p>In this backdrop, the Sustainable Shipping and Logistics Advisor emerges as a pioneering solution navigating the intricate landscape of maritime sustainability. Conceived and crafted by the dedicated duo - Alidu Abubakari from Ghana and Adejumobi Joshua from Nigeria, this advisor offers invaluable insights into sustainable practices in the realm of shipping and logistics. It's more than just an application; it's a beacon calling the maritime industry towards eco-friendly practices, carbon footprint reduction, and a sustainable future.</p>
""", unsafe_allow_html=True)

    st.header("Chat with Sustainability Code πŸ’¬")

    query = st.text_input("Ask questions about the sustainability code:")

    def process_query(query):
        store_name = 'sustainablecodebase'

        if os.path.exists(f"{store_name}.pkl"):
            with open(f"{store_name}.pkl", "rb") as f:
                VectorStore = pickle.load(f)
        else:
            st.write("Pickle file not found. Please upload the PDF to generate the pickle file.")
            return

        docs = VectorStore.similarity_search(query=query, k=3)
        llm = OpenAI(openai_api_key=openai.api_key)
        chain = load_qa_chain(llm=llm, chain_type="stuff")
        with get_openai_callback() as cb:
            response = chain.run(input_documents=docs, question=query)

        return response

    if st.button("Submit"):
        response = process_query(query)
        if response:
            st.write(response)
            if st.button("Download Question and Answer"):
                qa_text = f"Question: {query}\nAnswer: {response}"
                st.download_button("Download Q&A", qa_text, "qa.txt")

def page1():
    # Load and set our key
    #openai.api_key = open("key.txt", "r").read().strip("\n")

    st.write("<center><h1>Energizing Sustainability: Powering a Greener Future</h1></center>", unsafe_allow_html=True)
    st.image("page2.1.png", use_column_width=True)
    st.write("Assess and improve the sustainability of your logistics operations.")

    st.header("Company Information")


    input_option = st.radio("Choose an input option:", ["Enter logistics company's website URL", "Provide company description manually"])

    # Function to extract logistics information from a website URL
    def extract_logistics_info_from_website(url):
      try:
          response = requests.get(url)
          response.raise_for_status()  # Raise an exception for HTTP errors (e.g., 404)

          # Parse the HTML content of the page
          soup = BeautifulSoup(response.text, 'html.parser')

          # Example: Extract company description from the website
          company_description = soup.find('meta', attrs={'name': 'description'})
          if company_description:
              return company_description['content']

      except requests.exceptions.RequestException as e:
          return f"Error: Unable to connect to the website ({e})"
      except Exception as e:
          return f"Error: {e}"

      return None

    # Function to summarize logistics information using OpenAI's GPT-3 model
    def summarize_logistics_info(logistics_info):
      prompt = f"""
      Please extract the following information from the logistics company's description:
      - Core logistics services offered
      - Sustainability practices or initiatives related to logistics

      Description:
      {logistics_info}

      Please provide responses while avoiding speculative or unfounded information.
      """
      try:
          response = openai.ChatCompletion.create(
              model="gpt-3.5-turbo",
              messages=[
                  {"role": "system", "content": "You are an excellent sustainability assessment tool for logistics."},
                  {"role": "user", "content": prompt}
              ],
              max_tokens=100,
              temperature=0
          )
          company_summary = response.choices[0].message['content']

          return company_summary
      except Exception as e:
          return f"Error: {e}"

    # Streamlit UI
    st.title("Logistics Information Extractor")
    st.write("Extract logistics information from a logistics company's website URL.")

    if input_option == "Enter logistics company's website URL":
      example_url = "https://quangninhport.com.vn/en/home"
      website_url = st.text_input("Please enter the logistics company's website URL:", example_url)
      if website_url:
          # Ensure the URL starts with http/https
          website_url = website_url if website_url.startswith(("http://", "https://")) else "https://" + website_url

          logistics_info = extract_logistics_info_from_website(website_url)
          if logistics_info:
              company_summary = summarize_logistics_info(logistics_info)
              #st.write("Company Summary:")
              #st.write(company_summary)

    elif input_option == "Provide company description manually":
      st.markdown("""
          Please provide a description of the logistics company, focusing on the following:
          - Core logistics services offered
          - Sustainability practices or initiatives related to logistics
      """)
      company_description = st.text_area("Please provide the company description:", "")

      if company_description:
          company_summary = summarize_logistics_info(company_description)
          #st.write("Company Summary:")
          #st.write(company_summary)

    st.header("Logistics Sustainability Information")

    # Definitions for logistics sustainability levels
    sustainability_info = {
      "None": "No sustainability info available",
      "Green Logistics": "Green logistics refers to environmentally friendly practices in logistics operations, such as using electric vehicles, optimizing routes to reduce emissions, and minimizing packaging waste.",
      "Sustainable Supply Chain": "A sustainable supply chain involves responsible sourcing, ethical labor practices, and reducing the carbon footprint throughout the supply chain.",
      "Circular Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing waste in packaging and materials, leading to a more sustainable and resource-efficient approach.",
    }

    sustainability_level = st.selectbox("Logistics Sustainability Level", list(sustainability_info.keys()))

    # Display the definition when the user selects a sustainability level
    if sustainability_level in sustainability_info:
      st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}")

    # Additional sustainability-related information
    carbon_emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)", min_value=0)
    renewable_energy = st.checkbox("Does the company utilize Renewable Energy Sources in its operations?")

    # Certification and Sustainability Initiatives
    st.subheader("Certifications and Sustainability Initiatives")

    # Explanations for logistics-related certifications
    logistics_certification_info = {
      "None": "No certifications or initiatives related to logistics.",
      "ISO 14001 for Logistics": "ISO 14001 for Logistics is an international standard that sets requirements for an environmental management system in logistics operations.",
      "SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that reduce fuel use and emissions through efficient transportation practices.",
      "C-TPAT Certification": "C-TPAT (Customs-Trade Partnership Against Terrorism) certification ensures secure and sustainable supply chain practices in logistics.",
      "Green Freight Programs": "Green Freight Programs focus on reducing the environmental impact of freight transportation through efficiency improvements.",
      "Zero Emission Zones Participation": "Participating in Zero Emission Zones demonstrates a commitment to using zero-emission vehicles and reducing emissions in specific areas.",
    }

    selected_certifications = st.multiselect("Select Logistics Certifications and Initiatives", list(logistics_certification_info.keys()))

    # Display explanations for selected certifications
    for certification in selected_certifications:
      if certification in logistics_certification_info:
          st.write(f"**Explanation of {certification}:** {logistics_certification_info[certification]}")

    # Define the company_data dictionary
    company_data = {
      "Logistics Sustainability Level": sustainability_level,
      "Annual Carbon Emissions (in metric tons)": carbon_emissions,
      "Utilize Renewable Energy Sources": renewable_energy,
      "Selected Logistics Certifications and Initiatives": selected_certifications
    }

    # If company_summary is generated, add it to company_data dictionary
    if 'company_summary' in locals() or 'company_summary' in globals():
      company_data["Company Summary"] = company_summary

    #st.write(company_data)
    # Define your questions and their types
    sections = {
        "Energy Usage": [
        ("23. What is the primary source of energy used in your logistics operations?", 'selectbox', ["Electricity", "Diesel", "Natural Gas", "Other"]),
        ("24. Percentage of electricity consumption from renewable sources in logistics (0-100%)", 'number_input', {"min_value": 0, "max_value": 100}),
        ("25. Average annual energy consumption in logistics operations (kWh)", 'number_input', {"min_value": 0}),
        ("26. Do you use energy-efficient technologies (e.g., LED lighting, energy-efficient HVAC) in your facilities?", 'radio', ["Yes", "No"]),
        ("27. Do you implement measures to reduce energy waste during non-operational hours?", 'radio', ["Yes", "No"]),
        ("28. Are there initiatives to optimize energy usage in transportation (e.g., route planning, load optimization)?", 'radio', ["Yes", "No"]),
        ("29. Do you have energy management systems to monitor and control energy usage?", 'radio', ["Yes", "No"]),
        ("30. Have you implemented specific energy efficiency measures or technologies in logistics operations?", 'radio', ["Yes", "No"]),
        ("31. Are you adopting renewable energy sources (e.g., solar panels, wind turbines)?", 'radio', ["Yes", "No"]),
        ("32. Have you conducted energy audits to identify energy savings opportunities?", 'radio', ["Yes", "No"]),
        ("33. Do you have a system for reporting energy consumption and sustainability efforts?", 'radio', ["Yes", "No"]),
        ("34. Do you have specific energy efficiency or renewable energy goals for logistics?", 'radio', ["Yes", "No"]),
        ("35. How frequently do you monitor and analyze energy usage data?", 'selectbox', ["Regularly", "Occasionally", "Rarely", "Never"]),
        ("36. Are you involved in partnerships to enhance energy efficiency and sustainability?", 'radio', ["Yes", "No"]),
        ("37. Are you actively managing and reducing energy consumption in your operations?", 'radio', ["Yes", "No"]),
        ("38. Do you have future plans or initiatives for energy sustainability in logistics?", 'radio', ["Yes", "No"])
        ],
    }

    # Initialize a dictionary to store the answers
    all_answers = {}

    # Display the section header
    st.subheader("Energy Usage")
    st.write("<hr>", unsafe_allow_html=True)

    # Create the columns outside the loop
    num_columns = 3
    columns = [st.columns(num_columns) for _ in range((len(sections["Energy Usage"]) + num_columns - 1) // num_columns)]

    # Display each question in columns and collect responses
    for i, (question_text, input_type, *options) in enumerate(sections["Energy Usage"]):
        col = columns[i // num_columns][i % num_columns]
        with col:
            if input_type == 'selectbox':
                all_answers[question_text] = col.selectbox(question_text, options[0])
            elif input_type == 'number_input':
                params = options[0]
                all_answers[question_text] = col.number_input(question_text, **params)
            elif input_type == 'radio':
                all_answers[question_text] = col.radio(question_text, options[0])

    #st.write(all_answers)

    # Convert answers to a DataFrame
    answers_df = pd.DataFrame([all_answers])

    def calculate_energy_score(df):
        score = 0

        # Scoring for primary energy source
        primary_energy = df.at[0, "23. What is the primary source of energy used in your logistics operations?"].lower()
        energy_source_scores = {"electricity": 10, "diesel": 5, "natural gas": 7, "other": 3}
        score += energy_source_scores.get(primary_energy, 0)

        # Renewable energy percentage (linear scoring)
        renewable_percentage = df.at[0, "24. Percentage of electricity consumption from renewable sources in logistics (0-100%)"]
        score += int(renewable_percentage / 10)  # Every 10% adds 1 point

        # Scoring for average annual energy consumption
        annual_consumption = df.at[0, "25. Average annual energy consumption in logistics operations (kWh)"]
        if annual_consumption > 0:  # Lower consumption gets higher score
            score += 5 - min(4, int(annual_consumption / 10000))  # Example scoring, adjust as needed

        # Scoring for Yes/No questions (5 points for each 'Yes')
        # Generate the list of Yes/No questions
        yes_no_questions = [question[0] for question in sections["Energy Usage"] if question[1] == 'radio']


        for question in yes_no_questions:
            response = df.at[0, question].strip().lower()
            if response == 'yes':
                score += 5

        # Additional scoring based on energy monitoring frequency
        monitoring_frequency = df.at[0, "35. How frequently do you monitor and analyze energy usage data?"].lower()
        frequency_scores = {"regularly": 5, "occasionally": 3, "rarely": 1, "never": 0}
        score += frequency_scores.get(monitoring_frequency, 0)

        # Ensure score is within 0-100 range
        score = max(0, min(100, score))

        return score
    def visualize_score_explanation(df):
        # Define scoring parameters
        energy_source_scores = {"electricity": 10, "diesel": 5, "natural gas": 7, "other": 3}
        frequency_scores = {"regularly": 5, "occasionally": 3, "rarely": 1, "never": 0}
        yes_no_questions = [question[0] for question in sections["Energy Usage"] if question[1] == 'radio']

        # Calculate the components of the score
        primary_energy_score = energy_source_scores.get(df.at[0, "23. What is the primary source of energy used in your logistics operations?"].lower(), 0)
        renewable_energy_score = int(df.at[0, "24. Percentage of electricity consumption from renewable sources in logistics (0-100%)"] / 10)
        annual_consumption = df.at[0, "25. Average annual energy consumption in logistics operations (kWh)"]
        annual_consumption_score = 5 - min(4, int(annual_consumption / 10000))
        yes_no_score = sum(df.at[0, question].strip().lower() == 'yes' for question in yes_no_questions) * 5
        monitoring_score = frequency_scores.get(df.at[0, "35. How frequently do you monitor and analyze energy usage data?"].lower(), 0)

        # Components for visualization
        components = {
            'Primary Energy Source': primary_energy_score,
            'Renewable Energy %': renewable_energy_score,
            'Annual Energy Consumption': annual_consumption_score,
            'Yes/No Questions': yes_no_score,
            'Monitoring Frequency': monitoring_score
        }

        # Create a pie chart
        fig, ax = plt.subplots()
        ax.pie(components.values(), labels=components.keys(), autopct='%1.1f%%', startangle=90)
        ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
        plt.title('Contribution to Total Energy Sustainability Score')

        # Display the plot in Streamlit
        st.pyplot(fig)

    # Explanation for the energy sustainability score calculation
    explanation_E_eval = """

    The Energy Sustainability Score is calculated based on several factors related to sustainable energy practices in logistics operations. Here's how the score is composed:

    - **Primary Energy Source:** Points are allocated based on the type of primary energy used, with renewable sources scoring higher.
    - **Renewable Energy Percentage:** The percentage of electricity consumption from renewable sources contributes linearly to the score.
    - **Average Annual Energy Consumption:** Lower consumption rates are rewarded with higher points, promoting energy efficiency.
    - **Yes/No Questions:** Each 'Yes' answer to questions about sustainable practices adds to the score, reflecting proactive measures taken.
    - **Energy Monitoring Frequency:** Regular monitoring of energy usage indicates a commitment to sustainability and adds additional points.

    A higher score indicates a stronger commitment to sustainable energy practices in logistics operations.
    """


    def evaluate_sustainability_practice(score, df):
        # Calculate the energy sustainability score
        #score = calculate_energy_score(df)

        # Counting 'Yes' responses for Yes/No questions
        yes_no_questions = [question[0] for question in sections["Energy Usage"] if question[1] == 'radio']
        yes_count = sum(df[question].eq('Yes').sum() for question in yes_no_questions if question in df.columns)
        yes_percentage = (yes_count / len(yes_no_questions)) * 100

        # Calculate a combined sustainability index (example: 60% weight to score, 40% to yes_percentage)
        combined_index = (0.6 * score) + (0.4 * yes_percentage)

        # Grading system with detailed advice

        if combined_index >= 80:
            grade = "A (Eco-Champion 🌍)"
            st.image("Eco-Champion.png", use_column_width=True)
            Explanation = "You are at the forefront of sustainability in shipping and logistics, showcasing exemplary practices and commitment."
            advice = " Continue leading by example and exploring new frontiers in sustainability. Consider being a mentor or partner for smaller companies striving to become more sustainable. Invest in research and development for sustainable technologies. Advocate for sustainable policies in your industry. Strive for continuous improvement and set visionary goals like a completely zero-emission operation"
        elif combined_index >= 60:
            grade = "B (Sustainability Steward πŸƒ)"
            st.image("Sustainability_Steward.png", use_column_width=True)
            Explanation = "Your operations demonstrate a high level of sustainability, setting you apart as a leader in green practices."
            advice = "Innovate by investing in cutting-edge technologies like AI and IoT for predictive maintenance and better energy management. Consider setting ambitious targets like achieving carbon-neutral operations. Share your knowledge and experiences in sustainability forums and workshops. Look for opportunities to collaborate on sustainability projects and pilot new eco-friendly technologies."
        elif combined_index >= 40:
            grade = "C (Eco-Advancer 🌿)"
            st.image("Eco-Advancer.png", use_column_width=True)
            Explanation = "You are actively engaging in sustainable practices, showing a clear commitment to improving your operations."
            advice = " Leverage technology to further optimize your logistics routes for fuel efficiency and reduced emissions. Consider investing in advanced energy management systems for real-time monitoring and control. Explore certifications for sustainability to benchmark your performance against industry standards. Engage with suppliers and clients who also prioritize sustainability, creating a green supply chain."
        elif combined_index >= 20:
            grade = "D (Green Learner 🌼)"
            st.image("Green_Learner.png", use_column_width=True)
            Explanation = "You've made some initial steps towards sustainability but haven't fully integrated these practices into your operations yet."
            advice = "Start tracking your carbon footprint to set a baseline for improvement. Explore opportunities to incorporate more renewable energy sources, like solar or wind power, in your facilities. Engage in partnerships with other companies to learn from best practices in the industry. Look into eco-friendly packaging options and explore the possibility of using electric or hybrid vehicles for transportation."
        else:
            grade = "E (Eco-Novice 🌱)"
            st.image("Eco-Novice.png", use_column_width=True)
            Explanation = "You are at the early stages of implementing sustainable practices in your logistics operations. This is a great starting point, and there's much room for growth."
            advice = "Begin by conducting a thorough energy audit to understand your current energy usage and identify areas for improvement. Focus on low-hanging fruits like switching to LED lighting, optimizing route planning to reduce fuel consumption, and training staff on energy conservation techniques. Consider simple measures like ensuring vehicles and equipment are well-maintained to improve fuel efficiency."
        return f"**Sustainability Grade: {grade}** \n\n**Explanation:** \n{Explanation} \n\n**Basic Advice:** \n{advice}"


    def visualize_data(df):
        renewable_energy = df["24. Percentage of electricity consumption from renewable sources in logistics (0-100%)"]
        labels = ['Renewable', 'Non-Renewable']
        sizes = [renewable_energy.mean(), 100 - renewable_energy.mean()]
        fig, ax = plt.subplots()
        ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140, colors=['lightgreen', 'lightcoral'])
        ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
        st.pyplot(fig)

    def format_answer(answer):
        """Format the answer based on its type for better readability."""
        if isinstance(answer, bool):
            return "Yes" if answer else "No"
        elif isinstance(answer, (int, float)):
            return str(answer)
        return answer  # Assume the answer is already in a string format

    def extract_data(data):
        """Extract and format data from a dictionary."""
        formatted_data = {}
        for key, value in data.items():
            formatted_data[key] = format_answer(value)
        return formatted_data

    def generate_swot_analysis(company_data):
        # Extracting relevant data from company_data
        logistics_sustainability_level = company_data.get("Logistics Sustainability Level", "None")
        annual_carbon_emissions = company_data.get("Annual Carbon Emissions (in metric tons)", 0)
        utilize_renewable_energy = company_data.get("Utilize Renewable Energy Sources", False)
        selected_certifications = company_data.get("Selected Logistics Certifications and Initiatives", [])
        company_summary = company_data.get("Company Summary", "No specific information provided.")

        # Constructing a dynamic SWOT analysis based on extracted data
        strengths = [
            "Utilization of Renewable Energy Sources" if utilize_renewable_energy else "None"
        ]

        weaknesses = [
            "Lack of Logistics Sustainability Level: " + logistics_sustainability_level,
            "Zero Annual Carbon Emissions" if annual_carbon_emissions == 0 else "Annual Carbon Emissions Present",
            "Company Summary: " + company_summary
        ]

        opportunities = [
            "Exploration of Logistics Certifications" if not selected_certifications else "None"
        ]

        threats = [
            "Competitive Disadvantage Due to Lack of Certifications" if not selected_certifications else "None"
        ]

        # Constructing a SWOT analysis prompt dynamically
        swot_analysis_prompt = f"""
        Strengths, Weaknesses, Opportunities, Threats (SWOT) Analysis:

        Strengths:
        Strengths Analysis:
        {", ".join(strengths)}

        Weaknesses:
        Weaknesses Analysis:
        {", ".join(weaknesses)}

        Opportunities:
        Opportunities Analysis:
        {", ".join(opportunities)}

        Threats:
        Threats Analysis:
        {", ".join(threats)}
        """

        # OpenAI API call for SWOT analysis
        response_swot = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "assistant", "content": "You are analyzing the company's sustainability practices."},
                {"role": "system", "content": "Conduct a SWOT analysis based on the provided company data."},
                {"role": "user", "content": swot_analysis_prompt}
            ],
            max_tokens=1000,
            temperature=0.5,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0
        )

        # Extracting the SWOT analysis content from the response
        swot_analysis_content = response_swot.choices[0].message['content']

        return swot_analysis_content


    def get_energy_report(all_answers, score):
        """Generates an Energy Sustainability report based on responses to a questionnaire."""
        extracted_data = extract_data(all_answers)

        # Consolidate data using extracted data
        energy_source_info = f"Primary Energy Source: {extracted_data.get('23. What is the primary source of energy used in your logistics operations?', 'N/A')}, Renewable Source Percentage: {extracted_data.get('24. Percentage of electricity consumption from renewable sources in logistics (0-100%)', 'N/A')}%, Average Annual Consumption: {extracted_data.get('25. Average annual energy consumption in logistics operations (kWh)', 'N/A')}"
        efficiency_measures = f"Efficiency Technologies: {extracted_data.get('26. Do you use energy-efficient technologies (e.g., LED lighting, energy-efficient HVAC) in your facilities?', 'N/A')}, Energy Management Practices: {extracted_data.get('29. Do you have energy management systems to monitor and control energy usage?', 'N/A')}, Renewable Energy Adoption: {extracted_data.get('31. Are you adopting renewable energy sources (e.g., solar panels, wind turbines)?', 'N/A')}"

        consolidated_report = f"""
        Energy Sustainability Report
        Score: {score}/100
        Report Details:
        {energy_source_info}
        {efficiency_measures}
        """

        # Prompt for the OpenAI API
        prompt = f"""
        As an energy sustainability advisor, analyze the Energy Sustainability Report with a score of {score}/100. Review the data points provided and offer a detailed analysis. Identify strengths, weaknesses, and areas for improvement. Provide specific recommendations to improve the energy sustainability score, considering the current energy mix and efficiency measures.

        Data Points:
        {energy_source_info}
        {efficiency_measures}
        """

        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "Analyze the data and provide comprehensive insights and recommendations."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=3000,
                temperature=0.7,
                top_p=1.0,
                frequency_penalty=0,
                presence_penalty=0
            )

            evaluation_content = response.choices[0].message['content']

            refined_report = f"{consolidated_report}\n\n{evaluation_content}"
            return refined_report

        except Exception as e:
            return f"Error: {e}"

    def get_energy_sustainability_advice(all_answers, company_data):
        # Extracting and formatting data from all_answers and company_data
        extracted_all_answers = extract_data(all_answers)
        extracted_company_data = extract_data(company_data)

        # Forming the prompt with extracted data
        prompt = f"""
        Based on the provided company and energy sustainability assessment data, provide energy sustainability Strategy:

        **Company Info**:
        - Logistics Sustainability Level: {extracted_company_data.get('Logistics Sustainability Level', 'N/A')}
        - Annual Carbon Emissions: {extracted_company_data.get('Annual Carbon Emissions (in metric tons)', 'N/A')} metric tons
        - Utilize Renewable Energy Sources: {extracted_company_data.get('Utilize Renewable Energy Sources', 'No')}
        - Certifications: {extracted_company_data.get('Selected Logistics Certifications and Initiatives', 'N/A')}
        - Company Summary: {extracted_company_data.get('Company Summary', 'N/A')}

        **Energy Sustainability Assessment Data**:
        - Primary Energy Source: {extracted_all_answers.get("23. What is the primary source of energy used in your logistics operations?", "N/A")}
        - Renewable Source Percentage: {extracted_all_answers.get("24. Percentage of electricity consumption from renewable sources in logistics (0-100%)", "N/A")}%
        - Average Annual Consumption: {extracted_all_answers.get("25. Average annual energy consumption in logistics operations (kWh)", "N/A")} kWh
        - Efficiency Technologies: {extracted_all_answers.get("26. Do you use energy-efficient technologies (e.g., LED lighting, energy-efficient HVAC) in your facilities?", "N/A")}
        - Energy Management Practices: {extracted_all_answers.get("29. Do you have energy management systems to monitor and control energy usage?", "N/A")}
        - Renewable Energy Adoption: {extracted_all_answers.get("31. Are you adopting renewable energy sources (e.g., solar panels, wind turbines)?", "N/A")}

        Offer actionable strategy considering the company's specific context.
        """

        additional_context = f"Provide detailed sustainability stratey using context data from the above company info and in responses to the energy sustainability assessment."

        # Assuming you have an API call here to generate a response based on the prompt
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "assistant", "content": "You are an energy sustainability strategy advisor."},
                {"role": "user", "content": prompt},
                {"role": "user", "content": additional_context}
            ],
            max_tokens=3000,
            temperature=0.7,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0
        )

        return response.choices[0].message['content']

    def get_certification_details(certification_name):
      # Prepare the prompt for the API call
      messages = [
          {"role": "system", "content": "You are a knowledgeable assistant about global certifications."},
          {"role": "user", "content": f"Provide detailed information on how to obtain the {certification_name} certification."}
      ]

      # Query the OpenAI API for information on the certification process
      response = openai.ChatCompletion.create(
          model="gpt-3.5-turbo",
          messages=messages,
          max_tokens=1500,
          temperature=0.3,
          top_p=1.0,
          frequency_penalty=0.5,
          presence_penalty=0.0
      )
      # Return the content of the response
      return response.choices[0].message['content']

    def advise_on_energy_sustainability_certification(company_data):
        # Extract company data
        annual_carbon_emissions = company_data.get('Annual Carbon Emissions', 0)
        use_renewable_energy = company_data.get('Use Renewable Energy', False)
        selected_certifications_and_initiatives = company_data.get('Selected Certifications and Initiatives', [])
        #country_of_operation = company_data.get('Country of Operation', 'N/A')

        # Initialize a string to store recommendations
        recommendations_text = ""

        # If the company uses renewable energy, suggest certifications that validate this practice
        if use_renewable_energy:
            recommendations_text += "To certify that your energy is sourced from renewable resources, consider obtaining the Renewable Energy Certificate (REC). "

        # Recommend energy management certifications based on carbon emissions
        if annual_carbon_emissions > 0:
            recommendations_text += "To measure, manage, and reduce your carbon emissions, pursuing the Carbon Trust Standard would be beneficial. "

        # If the company does not have an energy management system, recommend establishing one
        if "ISO 50001" not in selected_certifications_and_initiatives:
            recommendations_text += "Implementing an ISO 50001 Energy Management System can help you continuously improve energy efficiency. "

        # Suggest building certifications if the company operates physical locations
        recommendations_text += "For sustainable building operations, consider LEED or BREEAM certifications. "

        # Recommend product-specific energy certifications
        recommendations_text += "Achieving Energy Star certification can enhance the marketability of your energy-efficient products. "

        # For each recommendation, get more details on how to obtain the certification
        for certification in ["Renewable Energy Certificate", "Carbon Trust Standard", "ISO 50001", "LEED", "BREEAM", "Energy Star"]:
            certification_details = get_certification_details(certification)
            recommendations_text += f"\n\nFor {certification}, here's what you need to know: {certification_details}"

        # Return the combined recommendations as a single formatted string
        return recommendations_text


    st.markdown("<br>"*1, unsafe_allow_html=True)

    if st.button('Submit'):

        try:
           # Use a spinner for generating advice
           with st.spinner("Generating report and advice..."):
               st.subheader("Visualize Energy Data")
               visualize_data(answers_df)

               st.subheader("Visualize Energy Scores")
               score = calculate_energy_score(answers_df)

               st.write(f"**Energy Sustainability Score:**")
               st.markdown(f"**{score:.1f}%**")
               # Call the function with the DataFrame
               visualize_score_explanation(answers_df)
               # Display the explanation in Streamlit
               st.markdown(explanation_E_eval)

               st.subheader("Visualize Sustainability Grade")
               # Call the function with the DataFrame
               result = evaluate_sustainability_practice(score, answers_df)
               # Display the result in Streamlit
               st.write(result)

               strategy = get_energy_sustainability_advice(all_answers, company_data)
               #strategy = get_energy_sustainability_advice(strategy, company_data)
               report = get_energy_report(all_answers, score)

               # Extracting the SWOT analysis content from the response
               swot_analysis_content = generate_swot_analysis(company_data)
               #st.subheader("Energy Sustainability Strategy")
               st.subheader("Company SWOT Report")
               st.write(swot_analysis_content)

               #st.subheader("Energy Sustainability Strategy")
               st.subheader("Energy Sustainability Report")
               st.write(report)
               st.download_button(
                   label="Download Energy Sustainability Report",
                   data=report,
                   file_name='Energy_sustainability_report.txt',
                   mime='text/txt',
                   key="download_report_button",  # Unique key for this button
                   )
               st.subheader("Energy Sustainability Strategy")
               st.write(strategy)
               st.download_button(
                   label="Download Energy Sustainability Strategy",
                       data=strategy,
                       file_name='Energy_sustainability_strategy.txt',
                       mime='text/txt',
                       key="download_strategy_button",  # Unique key for this button
                       )
               st.subheader("Energy Sustainability Certification")
               energy_cert=advise_on_energy_sustainability_certification(company_data)
               st.write(energy_cert)

       # Embed a YouTube video after processing
           st.subheader("Watch More on Sustainability")
           # Define a list of video URLs
           video_urls = [
           "https://www.youtube.com/watch?v=olOjPWpYo4U",
           #"https://www.youtube.com/watch?v=your_video_url_2",
           #"https://www.youtube.com/watch?v=your_video_url_3",
           # Add more video URLs as needed
           ]

           # Select a random video URL from the list
           random_video_url = random.choice(video_urls)

           # Display the random video
           st.video(random_video_url)
        except Exception as e:
            st.error(f"An error occurred: {e}")

def page2():
    st.write("<center><h1>Sustainable Logistics Strategy and Transportation</h1></center>", unsafe_allow_html=True)

    st.image("page1.1.png", use_column_width=True)

    st.write("Assess and improve the sustainability of your logistics operations.")

    st.header("Company Information")


    input_option = st.radio("Choose an input option:", ["Enter logistics company's website URL", "Provide company description manually"])

    # Function to extract logistics information from a website URL
    def extract_logistics_info_from_website(url):
      try:
          response = requests.get(url)
          response.raise_for_status()  # Raise an exception for HTTP errors (e.g., 404)

          # Parse the HTML content of the page
          soup = BeautifulSoup(response.text, 'html.parser')

          # Example: Extract company description from the website
          company_description = soup.find('meta', attrs={'name': 'description'})
          if company_description:
              return company_description['content']

      except requests.exceptions.RequestException as e:
          return f"Error: Unable to connect to the website ({e})"
      except Exception as e:
          return f"Error: {e}"

      return None

    # Function to summarize logistics information using OpenAI's GPT-3 model
    def summarize_logistics_info(logistics_info):
      prompt = f"""
      Please extract the following information from the logistics company's description:
      - Core logistics services offered
      - Sustainability practices or initiatives related to logistics

      Description:
      {logistics_info}

      Please provide responses while avoiding speculative or unfounded information.
      """
      try:
          response = openai.ChatCompletion.create(
              model="gpt-3.5-turbo",
              messages=[
                  {"role": "system", "content": "You are an excellent sustainability assessment tool for logistics."},
                  {"role": "user", "content": prompt}
              ],
              max_tokens=100,
              temperature=0
          )
          company_summary = response.choices[0].message['content']

          return company_summary
      except Exception as e:
          return f"Error: {e}"

    # Streamlit UI
    st.title("Logistics Information Extractor")
    st.write("Extract logistics information from a logistics company's website URL.")

    if input_option == "Enter logistics company's website URL":
      example_url = "https://quangninhport.com.vn/en/home"
      website_url = st.text_input("Please enter the logistics company's website URL:", example_url)
      if website_url:
          # Ensure the URL starts with http/https
          website_url = website_url if website_url.startswith(("http://", "https://")) else "https://" + website_url

          logistics_info = extract_logistics_info_from_website(website_url)
          if logistics_info:
              company_summary = summarize_logistics_info(logistics_info)
              #st.write("Company Summary:")
              #st.write(company_summary)

    elif input_option == "Provide company description manually":
      st.markdown("""
          Please provide a description of the logistics company, focusing on the following:
          - Core logistics services offered
          - Sustainability practices or initiatives related to logistics
      """)
      company_description = st.text_area("Please provide the company description:", "")

      if company_description:
          company_summary = summarize_logistics_info(company_description)
          #st.write("Company Summary:")
          #st.write(company_summary)

    st.header("Logistics Sustainability Information")

    # Definitions for logistics sustainability levels
    sustainability_info = {
      "None": "No sustainability info available",
      "Green Logistics": "Green logistics refers to environmentally friendly practices in logistics operations, such as using electric vehicles, optimizing routes to reduce emissions, and minimizing packaging waste.",
      "Sustainable Supply Chain": "A sustainable supply chain involves responsible sourcing, ethical labor practices, and reducing the carbon footprint throughout the supply chain.",
      "Circular Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing waste in packaging and materials, leading to a more sustainable and resource-efficient approach.",
    }

    sustainability_level = st.selectbox("Logistics Sustainability Level", list(sustainability_info.keys()))

    # Display the definition when the user selects a sustainability level
    if sustainability_level in sustainability_info:
      st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}")

    # Additional sustainability-related information
    carbon_emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)", min_value=0)
    renewable_energy = st.checkbox("Does the company utilize Renewable Energy Sources in its operations?")

    # Certification and Sustainability Initiatives
    st.subheader("Certifications and Sustainability Initiatives")

    # Explanations for logistics-related certifications
    logistics_certification_info = {
      "None": "No certifications or initiatives related to logistics.",
      "ISO 14001 for Logistics": "ISO 14001 for Logistics is an international standard that sets requirements for an environmental management system in logistics operations.",
      "SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that reduce fuel use and emissions through efficient transportation practices.",
      "C-TPAT Certification": "C-TPAT (Customs-Trade Partnership Against Terrorism) certification ensures secure and sustainable supply chain practices in logistics.",
      "Green Freight Programs": "Green Freight Programs focus on reducing the environmental impact of freight transportation through efficiency improvements.",
      "Zero Emission Zones Participation": "Participating in Zero Emission Zones demonstrates a commitment to using zero-emission vehicles and reducing emissions in specific areas.",
    }

    selected_certifications = st.multiselect("Select Logistics Certifications and Initiatives", list(logistics_certification_info.keys()))

    # Display explanations for selected certifications
    for certification in selected_certifications:
      if certification in logistics_certification_info:
          st.write(f"**Explanation of {certification}:** {logistics_certification_info[certification]}")

    # Define the company_data dictionary
    company_data = {
      "Logistics Sustainability Level": sustainability_level,
      "Annual Carbon Emissions (in metric tons)": carbon_emissions,
      "Utilize Renewable Energy Sources": renewable_energy,
      "Selected Logistics Certifications and Initiatives": selected_certifications
    }

    # If company_summary is generated, add it to company_data dictionary
    if 'company_summary' in locals() or 'company_summary' in globals():
      company_data["Company Summary"] = company_summary

    #st.write(company_data)

    st.write("<hr>", unsafe_allow_html=True)
    st.write("In this section, we'll assess your company's commitment to environmental management, progress in reducing its environmental impact, transparency in reporting environmental performance to stakeholders, preparedness in managing climate change risks, and commitment to protecting biodiversity.")
    st.write("<hr>", unsafe_allow_html=True)

    sections = {
        "Transport and Environmental Commitment": [
            # Environmental Commitment related to Transport
            ("1. Environmental Management Commitment (0-10):", 'slider'),
            ("2. Progress in Reducing Environmental Impact of Transport (0-10):", 'slider'),
            ("3. Transparency in Transport-Related Environmental Reporting (0-10):", 'slider'),
            ("4. Commitment to Digital Transformation for Sustainable Transport (0-10):", 'slider'),
            ("5. Integration of Transport Sustainability Goals in Business Strategy (0-10):", 'slider'),
            ("6. Commitment to Increasing Energy Efficiency in Transport (0-10):", 'slider'),
            ("7. Commitment to Sustainable Packaging in Transport (0-10):", 'slider'),
            ("8. Commitment to Emission Reduction in Transport Operations (0-10):", 'slider'),
            ("9. Commitment to Sustainable Waste Management in Transport (0-10):", 'slider'),

            # Transport Method
            ("10. Type of Vehicle (Select primary type):", ['Truck', 'Ship', 'Train', 'Airplane'], 'selectbox'),
            ("11. Fuel Type (Select primary type):", ['Diesel', 'Gasoline', 'Natural Gas', 'Electric'], 'selectbox'),
            ("12. Average Vehicle Fuel Efficiency (MPG or L/Km):", 'number_input', {"min_value": 0}),
            ("13. Frequency of Vehicle Trips (per month):", 'number_input', {"min_value": 0}),
            ("14. Use of Alternative Transportation Methods:", 'radio', ["Yes", "No"]),
            ("15. Initiatives to Reduce Empty or Partially Filled Vehicle Trips:", 'radio', ["Yes", "No"]),
            ("16. Monitoring and Reduction of Vehicle Idling Time:", 'radio', ["Yes", "No"]),
            ("17. Equipped with Fuel-Efficient Technologies:", 'radio', ["Yes", "No"]),
            ("18. Strategies or Technologies for Vehicle Emission Management:", 'radio', ["Yes", "No"]),
            ("19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):", 'number_input', {"min_value": 0, "max_value": 100}),
            ("20. Vehicle Maintenance for Optimal Fuel Efficiency and Emissions Control:", 'radio', ["Yes", "No"]),
            ("21. Average Age of Vehicle Fleet (in years):", 'number_input', {"min_value": 0}),
            ("22. Environmentally Friendly Disposal/Recycling of End-of-Life Vehicles:", 'radio', ["Yes", "No"])
        ]
    }

    # Initialize a dictionary to store the answers
    all_answers = {}

    # Display the section header
    st.subheader("Transport and Environmental Commitment")
    st.write("<hr>", unsafe_allow_html=True)

    # Create columns outside the loop
    col1, col2, col3 = st.columns(3)

    # Iterate through each question and display them in columns
    for i, (question_text, input_type, *options) in enumerate(sections["Transport and Environmental Commitment"]):
        # Determine which column to use based on the question index
        if i % 3 == 0:
            col = col1
        elif i % 3 == 1:
            col = col2
        else:
            col = col3

        with col:
            if input_type == 'selectbox':
                all_answers[question_text] = st.selectbox(question_text, options[0])
            elif input_type == 'number_input':
                params = options[0]
                all_answers[question_text] = st.number_input(question_text, **params)
            elif input_type == 'radio':
                all_answers[question_text] = st.radio(question_text, options[0])
            elif input_type == 'slider':
                all_answers[question_text] = st.slider(question_text, 0, 10)

    # Convert answers to a DataFrame for analysis
    answers_df = pd.DataFrame([all_answers])

    #st.write(all_answers)

    # Display the collected answers
    #st.write("Collected Answers:", answers_df)

    def calculate_transport_score(all_answers):
        score = 0

        # Scoring for transport-related commitment (sliders)
        for i in range(1, 10):
            commitment_score = all_answers.get(f"{i}. Environmental Management Commitment (0-10):", 0)
            score += commitment_score

        # Scoring for vehicle type
        vehicle_type_score = {"Truck": 5, "Ship": 7, "Train": 10, "Airplane": 3}
        primary_vehicle = all_answers.get("10. Type of Vehicle (Select primary type):", "").lower()
        score += vehicle_type_score.get(primary_vehicle, 0)

        # Scoring for fuel type
        fuel_type_score = {"Diesel": 3, "Gasoline": 2, "Natural Gas": 5, "Electric": 10}
        primary_fuel = all_answers.get("11. Fuel Type (Select primary type):", "").lower()
        score += fuel_type_score.get(primary_fuel, 0)

        # Scoring for fuel efficiency
        fuel_efficiency = all_answers.get("12. Average Vehicle Fuel Efficiency (MPG or L/Km)", 0)
        if fuel_efficiency > 0:
            score += min(10, int(fuel_efficiency / 10))  # Scale as needed

        # Scoring for frequency of trips
        trip_frequency = all_answers.get("13. Frequency of Vehicle Trips (per month):", 0)
        if trip_frequency > 0:
            score -= min(5, int(trip_frequency / 10))  # Lower frequency, higher score

        # Scoring for Yes/No questions (5 points for each 'Yes')
        yes_no_questions = [
            "14. Use of Alternative Transportation Methods:",
            "15. Initiatives to Reduce Empty or Partially Filled Vehicle Trips:",
            "16. Monitoring and Reduction of Vehicle Idling Time:",
            "17. Equipped with Fuel-Efficient Technologies:",
            "18. Strategies or Technologies for Vehicle Emission Management:",
            "20. Vehicle Maintenance for Optimal Fuel Efficiency and Emissions Control:",
            "22. Environmentally Friendly Disposal/Recycling of End-of-Life Vehicles:"
        ]
        for question in yes_no_questions:
            response = all_answers.get(question, "No").lower()
            if response == 'yes':
                score += 5

        # Scoring based on fleet meeting emission standards
        emission_standards_percentage = all_answers.get("19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):", 0)
        score += int(emission_standards_percentage / 10)

        # Scoring based on fleet age
        fleet_age = all_answers.get("21. Average Age of Vehicle Fleet (in years):", 0)
        if fleet_age > 0:
            score -= min(5, int(fleet_age / 5))  # Newer fleet gets higher score

        # Ensure score is within 0-100 range
        score = max(0, min(100, score))

        return score

    def visualize_data(all_answers):
        # For commitment-related questions (questions 1 to 9)
        commitment_scores = [all_answers.get(f"{i}. Environmental Management Commitment (0-10):", 0) for i in range(1, 10)]
        total_commitment_score = sum(commitment_scores)
        max_commitment_score = 10 * len(commitment_scores)  # Maximum possible score
        average_commitment_score = total_commitment_score / max_commitment_score  # Fraction of maximum

        # Determine commitment level based on fraction
        commitment_level = "Eco-Enthusiast" if average_commitment_score > 0.5 else "Eco-Beginner"

        explanation = ""
        if average_commitment_score > 0.5:
            explanation = "With an above-average commitment score, your company has shown a strong commitment to sustainable practices."
        else:
            explanation = "Your commitment to sustainability is just beginning. There's much potential for growth in this area."

        # Creating two columns in Streamlit
        col1, col2 = st.columns(2)

        with col1:
            st.subheader("Transport Environmental Commitment")
            st.write(f"**Commitment Level:** {commitment_level}")
            st.write(explanation)

            # Plotting commitment level
            plt.figure(figsize=(6, 4))
            plt.bar(["Commitment Level"], [average_commitment_score], color='green' if average_commitment_score > 0.5 else 'red')
            plt.xlabel('Category')
            plt.ylabel('Average Score')
            plt.title('Transport Environmental Commitment')
            plt.ylim(0, 1)  # Assuming you want to scale the bar to 1 for visual consistency
            plt.xticks([0], ['Commitment Score'])  # Setting x-ticks to show "Commitment Score"
            plt.yticks([0, 0.5, 1], ['0%', '50%', '100%'])  # Setting y-ticks to show percentages
            st.pyplot(plt.gcf())

        with col2:
            st.subheader("Digital Transformation for Sustainable Transport")

            # For Digital Transformation score visualization (replace with actual score variable)
            digital_transformation = all_answers.get("4. Commitment to Digital Transformation for Sustainable Transport (0-10):", 0)

            st.write(f"**Digital Transformation Score:** {digital_transformation}/10")
            st.write("This score represents the commitment to digital transformation for sustainable transport.")

            # Plotting Digital Transformation score
            plt.figure(figsize=(6, 4))
            plt.bar(["Digital Transformation"], [digital_transformation], color='lightblue')
            plt.xlabel('Category')
            plt.ylabel('Score')
            plt.title('Commitment to Digital Transformation for Sustainable Transport')
            plt.ylim(0, 10)  # Assuming scores range from 0 to 10
            plt.xticks([0], ['Digital Transformation Score'])  # Setting x-ticks to show "Digital Transformation Score"
            st.pyplot(plt.gcf())

    def visualize_data1(all_answers):
        # Extracting data for visualization
        emission_reduction_commitment = all_answers.get("8. Commitment to Emission Reduction in Transport Operations (0-10):", 0)
        fleet_meeting_emission_standards = all_answers.get("19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):", 0)

        # Creating two columns in Streamlit
        col1, col2 = st.columns(2)

        # Visualizing "8. Commitment to Emission Reduction in Transport Operations (0-10):"
        with col1:
            st.subheader("Commitment to Emission Reduction")
            st.write(f"**Commitment Score:** {emission_reduction_commitment}/10")
            st.write("This score represents the commitment to reducing emissions in transport operations.")
            fig_emission = plt.figure(figsize=(6, 4))
            bar1 = plt.bar("Emission Reduction Commitment", emission_reduction_commitment, color='skyblue')
            plt.xlabel('Commitment')
            plt.ylabel('Score')
            plt.title('Commitment to Emission Reduction in Transport Operations')
            plt.legend([bar1], ['Emission Reduction Commitment'])
            # Add data label
            plt.text(bar1[0].get_x() + bar1[0].get_width() / 2., bar1[0].get_height(),
                     f'{emission_reduction_commitment}/10', ha='center', va='bottom')
            st.pyplot(fig_emission)

        # Visualizing "19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):"
        with col2:
            st.subheader("Fleet Meeting Emission Standards")
            st.write(f"**Emission Standards Percentage:** {fleet_meeting_emission_standards}%")
            st.write("This represents the percentage of the fleet meeting the latest emission standards.")
            fig_fleet_emission = plt.figure(figsize=(6, 4))
            bar2 = plt.bar("Fleet Meeting Emission Standards", fleet_meeting_emission_standards, color='lightgreen')
            plt.xlabel('Fleet Emission Standards')
            plt.ylabel('Percentage')
            plt.title('Percentage of Fleet Meeting Latest Emission Standards')
            plt.legend([bar2], ['Fleet Meeting Emission Standards'])
            # Add data label
            plt.text(bar2[0].get_x() + bar2[0].get_width() / 2., bar2[0].get_height(),
                     f'{fleet_meeting_emission_standards}%', ha='center', va='bottom')
            st.pyplot(fig_fleet_emission)


    #visualize_data(all_answers)

    #st.subheader("Visualize Transport Scores")

    #score = calculate_transport_score(all_answers)
    #st.write("Transport Sustainability Score:", score)

    def visualize_transport_score(all_answers):
        # Scoring parameters
        vehicle_type_score = {"Truck": 5, "Ship": 7, "Train": 10, "Airplane": 3}
        fuel_type_score = {"Diesel": 3, "Gasoline": 2, "Natural Gas": 5, "Electric": 10}
        yes_no_score_value = 5  # Points for each 'Yes' in yes/no questions

        # Extracting data from all_answers
        vehicle_type = all_answers.get("10. Type of Vehicle (Select primary type):", "").lower()
        fuel_type = all_answers.get("11. Fuel Type (Select primary type):", "").lower()
        fuel_efficiency = all_answers.get("12. Average Vehicle Fuel Efficiency (MPG or L/Km)", 0)
        emission_standards_percentage = all_answers.get("19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):", 0)
        fleet_age = all_answers.get("21. Average Age of Vehicle Fleet (in years):", 0)

        # Scoring components
        vehicle_type_score = vehicle_type_score.get(vehicle_type, 0)
        fuel_type_score = fuel_type_score.get(fuel_type, 0)
        fuel_efficiency_score = min(10, int(fuel_efficiency / 10))
        emission_standards_score = int(emission_standards_percentage / 10)
        fleet_age_score = max(0, 5 - int(fleet_age / 5))

        # Yes/No questions scoring
        yes_no_questions = [
            "14. Use of Alternative Transportation Methods:",
            "15. Initiatives to Reduce Empty or Partially Filled Vehicle Trips:",
            "16. Monitoring and Reduction of Vehicle Idling Time:",
            "17. Equipped with Fuel-Efficient Technologies:",
            "18. Strategies or Technologies for Vehicle Emission Management:",
            "20. Vehicle Maintenance for Optimal Fuel Efficiency and Emissions Control:",
            "22. Environmentally Friendly Disposal/Recycling of End-of-Life Vehicles:"
        ]
        yes_no_score = sum(all_answers.get(question, "No").lower() == 'yes' for question in yes_no_questions) * yes_no_score_value

        # Components for visualization
        components = {
            'Vehicle Type': vehicle_type_score,
            'Fuel Type': fuel_type_score,
            'Fuel Efficiency': fuel_efficiency_score,
            'Emission Standards Compliance': emission_standards_score,
            'Fleet Age': fleet_age_score,
            'Yes/No Sustainability Practices': yes_no_score
        }

        # Define colors for the bar chart
        colors = ['skyblue', 'orange', 'lightgreen', 'red', 'purple', 'pink']  # Define colors as needed

        # Create a horizontal bar chart
        plt.figure(figsize=(10, 6))
        plt.barh(list(components.keys()), list(components.values()), color=colors)

        # Add data labels to the bars
        for index, value in enumerate(components.values()):
            plt.text(value, index, str(value), va='center', color='black', fontweight='bold')

        # Set labels and title
        plt.xlabel('Score')
        plt.title('Contribution to Total Transport Sustainability Score')

        # Show grid and invert y-axis for better readability
        plt.grid(axis='x')
        plt.gca().invert_yaxis()

        plt.tight_layout()
        plt.show()

    explanation_T_metric = """
    The Transport Sustainability Score is calculated based on various factors that reflect sustainable practices in transport operations. Here's a breakdown of how the score is composed:

    - **Vehicle Type:** Different types of vehicles are scored based on their environmental impact. More sustainable vehicle types, like trains, score higher points.
    - **Fuel Type:** The primary fuel type used in vehicles influences the score. Renewable and cleaner fuels like electric power receive higher points.
    - **Fuel Efficiency:** Points are awarded based on the average fuel efficiency of the vehicle fleet. Higher fuel efficiency, indicating less fuel consumption per mile, contributes more points.
    - **Emission Standards Compliance:** The percentage of the vehicle fleet meeting the latest emission standards is a key factor. A higher percentage indicates better compliance with environmental standards and contributes positively to the score.
    - **Yes/No Sustainability Practices:** Responses to yes/no questions about sustainable transport practices such as the use of alternative transportation methods, strategies to reduce emissions, and maintenance for optimal fuel efficiency contribute to the score. Each 'Yes' response reflects a proactive measure in sustainable transport and adds points.
    - **Vehicle Maintenance and Disposal Practices:** Good maintenance practices that ensure optimal fuel efficiency and responsible disposal or recycling of end-of-life vehicles are crucial. These practices are scored to encourage sustainability throughout the vehicle's lifecycle.

    A higher score indicates a stronger commitment to sustainable transport practices and efficient environmental management in transport operations.
    """

    def evaluate_transport_sustainability_practice(score, df):
        # Calculate the transport sustainability score
        # Assuming score is calculated using calculate_transport_score(df)

        # Counting 'Yes' responses for transport-related Yes/No questions
        transport_yes_no_questions = [question[0] for question in sections["Transport and Environmental Commitment"] if question[1] == 'radio']
        yes_count = sum(df[question].eq('Yes').sum() for question in transport_yes_no_questions if question in df.columns)
        yes_percentage = (yes_count / len(transport_yes_no_questions)) * 100 if transport_yes_no_questions else 0

        # Calculate a combined transport sustainability index
        combined_index = (0.6 * score) + (0.4 * yes_percentage)

        # Grading system with detailed advice for transport sustainability
        if combined_index >= 80:
            grade = "A (Transport Eco-Champion 🌍)"
            st.image("Eco-Champion.png")
            Explanation = "Your transport operations are at the forefront of sustainability, setting a high standard for the industry."
            advice = "Continue to innovate and lead in sustainable transport practices. Explore new technologies and collaborate on industry-wide sustainability initiatives."
        elif combined_index >= 60:
            grade = "B (Transport Sustainability Steward πŸƒ)"
            st.image("Sustainability_Steward.png", use_column_width=True)
            Explanation = "Your transport operations are highly sustainable, demonstrating a strong commitment to environmental stewardship."
            advice = "Seek opportunities for further improvement in areas like fuel efficiency, emissions reduction, and green logistics."
        elif combined_index >= 40:
            grade = "C (Transport Eco-Advancer 🌿)"
            st.image("Eco-Advancer.png", use_column_width=True)
            Explanation = "You are making significant strides in sustainable transport, but there's room for further progress."
            advice = "Focus on areas such as increasing the use of renewable fuels, optimizing routes for efficiency, and reducing idle times."
        elif combined_index >= 20:
            grade = "D (Transport Green Learner 🌼)"
            st.image("Green_Learner.png", use_column_width=True)
            Explanation = "You've started to integrate sustainable practices in your transport operations, but there's much to learn and implement."
            advice = "Begin with achievable goals like improving vehicle maintenance for better fuel efficiency and exploring eco-friendly transport options."
        else:
            grade = "E (Transport Eco-Novice 🌱)"
            st.image("Eco-Novice.png", use_column_width=True)
            Explanation = "You are at the beginning of your journey towards sustainable transport."
            advice = "Start with basic measures such as monitoring fuel consumption, training drivers in eco-driving techniques, and planning efficient routes."

        return f"**Sustainability Grade: {grade}** \n\n**Explanation:** \n{Explanation} \n\n**Detailed Advice:** \n{advice}"

    #st.markdown(evaluate_transport_sustainability_practice(score, answers_df), unsafe_allow_html=True)
    def generate_swot_analysis(company_data):
        # Extracting relevant data from company_data
        logistics_sustainability_level = company_data.get("Logistics Sustainability Level", "None")
        annual_carbon_emissions = company_data.get("Annual Carbon Emissions (in metric tons)", 0)
        utilize_renewable_energy = company_data.get("Utilize Renewable Energy Sources", False)
        selected_certifications = company_data.get("Selected Logistics Certifications and Initiatives", [])
        company_summary = company_data.get("Company Summary", "No specific information provided.")

        # Constructing a dynamic SWOT analysis based on extracted data
        strengths = [
            "Utilization of Renewable Energy Sources" if utilize_renewable_energy else "None"
        ]

        weaknesses = [
            "Lack of Logistics Sustainability Level: " + logistics_sustainability_level,
            "Zero Annual Carbon Emissions" if annual_carbon_emissions == 0 else "Annual Carbon Emissions Present",
            "Company Summary: " + company_summary
        ]

        opportunities = [
            "Exploration of Logistics Certifications" if not selected_certifications else "None"
        ]

        threats = [
            "Competitive Disadvantage Due to Lack of Certifications" if not selected_certifications else "None"
        ]

        # Constructing a SWOT analysis prompt dynamically
        swot_analysis_prompt = f"""
        Strengths, Weaknesses, Opportunities, Threats (SWOT) Analysis:

        Strengths:
        Strengths Analysis:
        {", ".join(strengths)}

        Weaknesses:
        Weaknesses Analysis:
        {", ".join(weaknesses)}

        Opportunities:
        Opportunities Analysis:
        {", ".join(opportunities)}

        Threats:
        Threats Analysis:
        {", ".join(threats)}
        """

        # OpenAI API call for SWOT analysis
        response_swot = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "assistant", "content": "You are analyzing the company's sustainability practices."},
                {"role": "system", "content": "Conduct a SWOT analysis based on the provided company data."},
                {"role": "user", "content": swot_analysis_prompt}
            ],
            max_tokens=1000,
            temperature=0.5,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0
        )

        # Extracting the SWOT analysis content from the response
        swot_analysis_content = response_swot.choices[0].message['content']

        return swot_analysis_content

    def get_transport_sustainability_report(all_answers, score):
        """Generates a Transport Sustainability report based on responses to a questionnaire."""
        extracted_data = extract_data(all_answers)

        # Consolidate data for transport method using extracted data
        vehicle_info = f"Vehicle Type: {extracted_data.get('10. Type of Vehicle (Select primary type):', 'N/A')}, Fuel Type: {extracted_data.get('11. Fuel Type (Select primary type):', 'N/A')}"
        transport_efficiency_measures = f"Average Fuel Efficiency: {extracted_data.get('12. Average Vehicle Fuel Efficiency (MPG or L/Km):', 'N/A')}, Frequency of Trips: {extracted_data.get('13. Frequency of Vehicle Trips (per month):', 'N/A')}"
        environmental_commitment = f"Alternative Transportation Methods: {extracted_data.get('14. Use of Alternative Transportation Methods:', 'N/A')}, Empty Trip Reduction: {extracted_data.get('15. Initiatives to Reduce Empty or Partially Filled Vehicle Trips:', 'N/A')}"

        consolidated_report = f"""
        Transport Sustainability Report
        Score: {score}/100
        Report Details:
        {vehicle_info}
        {transport_efficiency_measures}
        {environmental_commitment}
        """

        # Prompt for the OpenAI API
        prompt = f"""
        As a transport sustainability advisor, analyze the Transport Sustainability Report with a score of {score}/100. Review the data points provided and offer a detailed analysis. Identify strengths, weaknesses, and areas for improvement. Provide specific recommendations to improve the transport sustainability score, considering the current vehicle mix, fuel efficiency, and environmental initiatives.

        Data Points:
        {vehicle_info}
        {transport_efficiency_measures}
        {environmental_commitment}
        """

        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "Analyze the data and provide comprehensive insights and recommendations."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=3000,
                temperature=0.7,
                top_p=1.0,
                frequency_penalty=0,
                presence_penalty=0
            )

            evaluation_content = response.choices[0].message['content']

            refined_report = f"{consolidated_report}\n\n{evaluation_content}"
            return refined_report

        except Exception as e:
            return f"Error: {e}"

    def format_answer(answer):
        """Format the answer based on its type for better readability."""
        if isinstance(answer, bool):
            return "Yes" if answer else "No"
        elif isinstance(answer, (int, float)):
            return str(answer)
        return answer  # Assume the answer is already in a string format

    def extract_data(data):
        """Extract and format data from a dictionary."""
        formatted_data = {}
        for key, value in data.items():
            formatted_data[key] = format_answer(value)
        return formatted_data

    def get_transport_sustainability_strategy(all_answers, company_data):
        # Extracting and formatting data from all_answers and company_data
        extracted_all_answers = extract_data(all_answers)
        extracted_company_data = extract_data(company_data)

        # Forming the prompt with extracted data
        prompt = f"""
        Based on the provided company and transport sustainability assessment data, provide a transport sustainability strategy:

        **Company Info**:
        - Logistics Sustainability Level: {extracted_company_data.get('Logistics Sustainability Level', 'N/A')}
        - Annual Carbon Emissions: {extracted_company_data.get('Annual Carbon Emissions (in metric tons)', 'N/A')} metric tons
        - Utilize Renewable Energy Sources: {extracted_company_data.get('Utilize Renewable Energy Sources', 'No')}
        - Certifications: {extracted_company_data.get('Selected Logistics Certifications and Initiatives', 'N/A')}
        - Company Summary: {extracted_company_data.get('Company Summary', 'N/A')}

        **Transport Sustainability Assessment Data**:
        - Vehicle Type: {extracted_all_answers.get("10. Type of Vehicle (Select primary type):", "N/A")}
        - Fuel Type: {extracted_all_answers.get("11. Fuel Type (Select primary type):", "N/A")}
        - Average Fuel Efficiency: {extracted_all_answers.get("12. Average Vehicle Fuel Efficiency (MPG or L/Km):", "N/A")}
        - Use of Alternative Transportation Methods: {extracted_all_answers.get("14. Use of Alternative Transportation Methods:", "N/A")}
        - Initiatives for Efficiency: {extracted_all_answers.get("15. Initiatives to Reduce Empty or Partially Filled Vehicle Trips:", "N/A")}
        - Emission Standards Compliance: {extracted_all_answers.get("19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):", "N/A")}%

        Offer actionable strategy considering the company's specific context and transport sustainability data.
        """

        additional_context = f"Provide detailed transport sustainability strategy using context data from the above company info and in responses to the transport sustainability assessment."
        # Assuming you have an API call here to generate a response based on the prompt
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "assistant", "content": "You are an energy sustainability strategy advisor."},
                {"role": "user", "content": prompt},
                {"role": "user", "content": additional_context}
            ],
            max_tokens=3000,
            temperature=0.7,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0
        )

        return response.choices[0].message['content']

    def get_certification_details(certification_name):
        # Prepare the prompt for the API call
        messages = [
            {"role": "system", "content": "You are a knowledgeable assistant about global certifications."},
            {"role": "user", "content": f"Provide detailed information on how to obtain the {certification_name} certification."}
        ]

        # Query the OpenAI API for information on the certification process
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=messages,
            max_tokens=1500,
            temperature=0.3,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0
        )

        # Return the content of the response
        return response.choices[0].message['content']

    def advise_on_transport_sustainability_certification(company_data):
        # Check if company_data is a dictionary
        if not isinstance(company_data, dict):
            raise ValueError("company_data must be a dictionary")

        # Extract company data
        annual_carbon_emissions = company_data.get('Annual Carbon Emissions', 0)
        use_alternative_transport_methods = company_data.get('Use Alternative Transport Methods', False)
        selected_transport_certifications = company_data.get('Selected Transport Certifications and Initiatives', [])

        # Initialize a string to store recommendations
        recommendations_text = ""

        # Determine which certifications to suggest
        certifications_to_consider = {
            "SmartWay": use_alternative_transport_methods,
            "Clean Cargo": use_alternative_transport_methods,
            "Carbon Trust Standard": annual_carbon_emissions > 0,
            "GLEC Framework": annual_carbon_emissions > 0,
            "ISO 39001": "ISO 39001" not in selected_transport_certifications,
            "EcoVadis": True,
            "Green Logistics": True
        }

        for certification, consider in certifications_to_consider.items():
            if consider:
                try:
                    certification_details = get_certification_details(certification)
                    recommendations_text += f"\n\nFor {certification}, here's what you need to know: {certification_details}"
                except Exception as e:
                    recommendations_text += f"\n\nError retrieving details for {certification}: {e}"

        # If no certifications are suggested, add a message
        if not recommendations_text.strip():
            recommendations_text = "Based on the provided data, there are no specific certifications recommended at this time."

        # Return the combined recommendations as a single formatted string
        return recommendations_text

    st.markdown("<br>"*1, unsafe_allow_html=True)

    if st.button('Submit'):

        try:
           # Use a spinner for generating advice
           with st.spinner("Generating report and advice..."):
               st.subheader("Visualize Transport Data")

               visualize_data(all_answers)
               visualize_data1(all_answers)

               st.subheader("Transport Scores")

               score = calculate_transport_score(all_answers)

               #st.write("Transport Sustainability Score:", score)
               # Display formatted score

               st.write(f"**Transport Sustainability Score:**")
               st.markdown(f"**{score:.1f}%**")

               st.subheader("Visualize Transport Scores")
               # Call the function to get the figure
               fig = visualize_transport_score(all_answers)

               # Display the figure in Streamlit, using a column layout
               st.pyplot(fig)

               st.markdown(explanation_T_metric)

               st.subheader("Visualize Sustainability Grade")
               # Call the function with the DataFrame

               st.markdown(evaluate_transport_sustainability_practice(score, answers_df), unsafe_allow_html=True)

               strategy = get_transport_sustainability_strategy(all_answers, company_data)
               #strategy = get_energy_sustainability_advice(strategy, company_data)
               report = get_transport_sustainability_report(all_answers, score)
               #st.subheader("Energy Sustainability Strategy")

               # Extracting the SWOT analysis content from the response
               swot_analysis_content = generate_swot_analysis(company_data)
               #st.subheader("Energy Sustainability Strategy")
               st.subheader("Company SWOT Report")
               st.write(swot_analysis_content)

               st.subheader("Transport Sustainability Report")
               st.write(report)
               st.download_button(
                   label="Download Transport Sustainability Report",
                       data=report,
                       file_name='sustainability_report.txt',
                       mime='text/txt',
                       key="download_report_button",  # Unique key for this button
                       )

               st.subheader("Sustainability Strategy")
               st.write(strategy)
               st.download_button(
                   label="Download Sustainability Strategy",
                   data=strategy,
                   file_name='sustainability_strategy.txt',
                   mime='text/txt',
                   key="download_strategy_button",  # Unique key for this button
               )

               st.subheader("Advice on Sustainability Certification")
               #certification_advice = advise_on_transport_sustainability_certification(company_data)
               try:
                   advice = advise_on_transport_sustainability_certification(company_data)
                   st.write(advice)
               except ValueError as e:
                   print(e)

        # Embed a YouTube video after processing
           st.subheader("Watch More on Sustainability")
           video_urls = [
           "https://www.youtube.com/watch?v=BawgdP1jmPo",
           #"https://www.youtube.com/watch?v=your_video_url_2",
           #"https://www.youtube.com/watch?v=your_video_url_3",
           # Add more video URLs as needed
           ]

           # Select a random video URL from the list
           random_video_url = random.choice(video_urls)

           # Display the random video
           st.video(random_video_url)

        except Exception as e:
           st.error(f"An error occurred: {e}")

        st.write("""
        ---
        *Powered by Streamlit, CarbonInterface API, and OpenAI.*
        """)

def page3():
    st.write("<center><h1>Waste Warriors: Navigating Sustainable Logistics</h1></center>", unsafe_allow_html=True)
    st.image("page6.1.png", use_column_width=True)
    st.write("Assess and improve the sustainability of your logistics operations.")
    st.header("Company Information")

    input_option = st.radio("Choose an input option:", ["Enter logistics company's website URL", "Provide company description manually"])

    # Function to extract logistics information from a website URL
    def extract_logistics_info_from_website(url):
        try:
            response = requests.get(url)
            response.raise_for_status()  # Raise an exception for HTTP errors (e.g., 404)

            # Parse the HTML content of the page
            soup = BeautifulSoup(response.text, 'html.parser')

            # Example: Extract company description from the website
            company_description = soup.find('meta', attrs={'name': 'description'})
            if company_description:
                return company_description['content']

        except requests.exceptions.RequestException as e:
            return f"Error: Unable to connect to the website ({e})"
        except Exception as e:
            return f"Error: {e}"

        return None

    # Function to summarize logistics information using OpenAI's GPT-3 model
    def summarize_logistics_info(logistics_info):
        prompt = f"""
        Please extract the following information from the logistics company's description:
        - Core logistics services offered
        - Sustainability practices or initiatives related to logistics

        Description:
        {logistics_info}

        Please provide responses while avoiding speculative or unfounded information.
        """
        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "You are an excellent sustainability assessment tool for logistics."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=100,
                temperature=0
            )
            company_summary = response.choices[0].message['content']

            return company_summary
        except Exception as e:
            return f"Error: {e}"

    # Streamlit UI
    st.title("Logistics Information Extractor")
    st.write("Extract logistics information from a logistics company's website URL.")

    # User input field for the website URL
    #website_url = st.text_input("Enter the logistics company's website URL:")

    if input_option == "Enter logistics company's website URL":
        example_url = "https://quangninhport.com.vn/en/home"
        website_url = st.text_input("Please enter the logistics company's website URL:", example_url)
        if website_url:
            # Ensure the URL starts with http/https
            website_url = website_url if website_url.startswith(("http://", "https://")) else "https://" + website_url

            logistics_info = extract_logistics_info_from_website(website_url)
            if logistics_info:
                company_summary = summarize_logistics_info(logistics_info)
                #st.write("Company Summary:")
                #st.write(company_summary)

    elif input_option == "Provide company description manually":
        st.markdown("""
            Please provide a description of the logistics company, focusing on the following:
            - Core logistics services offered
            - Sustainability practices or initiatives related to logistics
        """)
        company_description = st.text_area("Please provide the company description:", "")

        if company_description:
            company_summary = summarize_logistics_info(company_description)
            #st.write("Company Summary:")
            #st.write(company_summary)

    st.header("Logistics Sustainability Information")

    # Definitions for logistics sustainability levels
    sustainability_info = {
        "None": "No sustainability info available",
        "Green Logistics": "Green logistics refers to environmentally friendly practices in logistics operations, such as using electric vehicles, optimizing routes to reduce emissions, and minimizing packaging waste.",
        "Sustainable Supply Chain": "A sustainable supply chain involves responsible sourcing, ethical labor practices, and reducing the carbon footprint throughout the supply chain.",
        "Circular Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing waste in packaging and materials, leading to a more sustainable and resource-efficient approach.",
    }

    sustainability_level = st.selectbox("Logistics Sustainability Level", list(sustainability_info.keys()))

    # Display the definition when the user selects a sustainability level
    if sustainability_level in sustainability_info:
        st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}")

    # Additional sustainability-related information
    carbon_emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)", min_value=0)
    renewable_energy = st.checkbox("Does the company utilize Renewable Energy Sources in its operations?")

    # Certification and Sustainability Initiatives
    st.subheader("Certifications and Sustainability Initiatives")

    # Explanations for logistics-related certifications
    logistics_certification_info = {
        "None": "No certifications or initiatives related to logistics.",
        "ISO 14001 for Logistics": "ISO 14001 for Logistics is an international standard that sets requirements for an environmental management system in logistics operations.",
        "SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that reduce fuel use and emissions through efficient transportation practices.",
        "C-TPAT Certification": "C-TPAT (Customs-Trade Partnership Against Terrorism) certification ensures secure and sustainable supply chain practices in logistics.",
        "Green Freight Programs": "Green Freight Programs focus on reducing the environmental impact of freight transportation through efficiency improvements.",
        "Zero Emission Zones Participation": "Participating in Zero Emission Zones demonstrates a commitment to using zero-emission vehicles and reducing emissions in specific areas.",
    }

    selected_certifications = st.multiselect("Select Logistics Certifications and Initiatives", list(logistics_certification_info.keys()))

    # Display explanations for selected certifications
    for certification in selected_certifications:
        if certification in logistics_certification_info:
            st.write(f"**Explanation of {certification}:** {logistics_certification_info[certification]}")

    # Define the company_data dictionary
    company_data = {
        "Logistics Sustainability Level": sustainability_level,
        "Annual Carbon Emissions (in metric tons)": carbon_emissions,
        "Utilize Renewable Energy Sources": renewable_energy,
        "Selected Logistics Certifications and Initiatives": selected_certifications
    }

    # If company_summary is generated, add it to company_data dictionary
    if 'company_summary' in locals() or 'company_summary' in globals():
        company_data["Company Summary"] = company_summary

    #st.write(company_data)

    # Display the section header
    st.subheader("Waste Management")
    st.write("<hr>", unsafe_allow_html=True)
    st.write("In this section, we'll delve into your company's waste management practices and sustainability efforts. We'll examine how you handle waste, reduce single-use items, and manage waste in an environmentally friendly manner.")
    st.write("<hr>", unsafe_allow_html=True)

    sections = {
        "Waste Management": [
            ("80. Do you have a waste management plan in place for your logistics operations?", 'radio', ["Yes", "No"]),
            ("81. Do you actively implement waste reduction and recycling initiatives?", 'radio', ["Yes", "No"]),
            ("82. Is waste segregated according to type (hazardous, non-hazardous, recyclable) at your facilities?", 'radio', ["Yes", "No"]),
            ("83. Are there measures to minimize waste generation in cargo handling or packaging processes?", 'radio', ["Yes", "No"]),
            ("84. Do you have initiatives for reusing or repurposing materials and equipment to reduce waste?", 'radio', ["Yes", "No"]),
            ("85. Do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?", 'radio', ["Yes", "No"]),
            ("86. Are waste reduction and recycling efforts communicated to logistics employees?", 'radio', ["Yes", "No"]),
            ("87. What percentage of waste is recycled or diverted from landfills in your logistics operations?", 'number_input', {"min_value": 0, "max_value": 100}),
            ("88. Have you conducted waste audits or assessments to evaluate waste management practices?", 'radio', ["Yes", "No"]),
            ("89. Are there plans to improve waste management and recycling efforts in the future?", 'radio', ["Yes", "No"]),
            ("90. Do you use software or systems for waste tracking and reporting?", 'radio', ["Yes", "No"]),
            ("91. Have you set quantifiable goals for waste reduction in the next year?", 'radio', ["Yes", "No"]),
            ("92. What is your target percentage for waste reduction in the next year?", 'number_input', {"min_value": 0, "max_value": 100}),
            ("93. Do you have partnerships with recycling or waste management companies?", 'radio', ["Yes", "No"]),
            ("94. Do you provide training on waste management for new employees?", 'radio', ["Yes", "No"]),
            ("95. Have you implemented a policy to reduce single-use items within logistics operations?", 'radio', ["Yes", "No"]),
            ("96. Do you conduct regular waste management compliance checks?", 'radio', ["Yes", "No"]),
            ("97. Do you participate in or support community waste management programs?", 'radio', ["Yes", "No"]),
            ("98. What percentage of your logistics operations are zero-waste to landfill?", 'number_input', {"min_value": 0, "max_value": 100}),
            ("99. Have you received any certifications or awards for your waste management practices?", 'radio', ["Yes", "No"]),
            ("100. Is there a designated team or department responsible for waste management?", 'radio', ["Yes", "No"])

        ],
    }

    # Initialize a dictionary to store the answers
    all_answers = {}


    st.write("<hr>", unsafe_allow_html=True)

    # Create columns outside the loop
    col1, col2, col3 = st.columns(3)

    # Iterate through each question and display them in columns
    for i, (question_text, input_type, *options) in enumerate(sections["Waste Management"]):
        # Determine which column to use based on the question index
        if i % 3 == 0:
            col = col1
        elif i % 3 == 1:
            col = col2
        else:
            col = col3

        with col:
            if input_type == 'selectbox':
                all_answers[question_text] = st.selectbox(question_text, options[0])
            elif input_type == 'number_input':
                params = options[0]
                all_answers[question_text] = st.number_input(question_text, **params)
            elif input_type == 'radio':
                all_answers[question_text] = st.radio(question_text, options[0])
            elif input_type == 'slider':
                all_answers[question_text] = st.slider(question_text, 0, 10)

    # Convert answers to a DataFrame for analysis
    answers_df = pd.DataFrame([all_answers])

    #st.write(all_answers)

    # Display the collected answers
    #st.write("Collected Answers:", answers_df)


    def visualize_data1(all_answers):
        # Extracting data for visualization
        target_waste_reduction = all_answers.get("92. What is your target percentage for waste reduction in the next year?", 0)
        zero_waste_to_landfill = all_answers.get("98. What percentage of your logistics operations are zero-waste to landfill?", 0)

        # Creating two columns in Streamlit
        col1, col2 = st.columns(2)

        # Visualizing "92. What is your target percentage for waste reduction in the next year?"
        with col1:
            st.header("Target Percentage for Waste Reduction")
            st.write(f"**Target Percentage:** {target_waste_reduction}%")
            st.write("This target represents the company's goal for reducing waste over the next year.")
            fig_target = plt.figure(figsize=(6, 4))
            bar1 = plt.bar("Target Reduction", target_waste_reduction, color='skyblue')
            plt.xlabel('Target')
            plt.ylabel('Percentage')
            plt.title('Target Percentage for Waste Reduction')
            plt.legend([bar1], ['Waste Reduction Target'])
            # Add data label
            plt.text(bar1[0].get_x() + bar1[0].get_width()/2., bar1[0].get_height(), f'{target_waste_reduction}%', ha='center', va='bottom')
            st.pyplot(fig_target)

        # Visualizing "98. What percentage of your logistics operations are zero-waste to landfill?"
        with col2:
            st.header("Percentage of Zero-Waste to Landfill")
            st.write(f"**Zero-Waste Percentage:** {zero_waste_to_landfill}%")
            st.write("This indicates the proportion of the company's logistics operations that successfully avoid sending waste to landfills.")
            fig_zero_waste = plt.figure(figsize=(6, 4))
            bar2 = plt.bar("Zero-Waste to Landfill", zero_waste_to_landfill, color='lightgreen')
            plt.xlabel('Zero-Waste')
            plt.ylabel('Percentage')
            plt.title('Percentage of Zero-Waste to Landfill')
            plt.legend([bar2], ['Zero-Waste to Landfill'])
            # Add data label
            plt.text(bar2[0].get_x() + bar2[0].get_width()/2., bar2[0].get_height(), f'{zero_waste_to_landfill}%', ha='center', va='bottom')
            st.pyplot(fig_zero_waste)

    def Waste_Management_Practices(all_answers):
        # Visualize Count of 'Yes' and 'No' Responses
        st.subheader("Waste Management Practices")
        st.write("**Yes/No Responses Overview:**")
        st.write("This chart shows the count of 'Yes' and 'No' responses to questions about waste management practices. A higher count of 'Yes' responses indicates proactive engagement in sustainable waste management.")

        # Counting 'Yes' and 'No' responses
        yes_count = sum(1 for response in all_answers.values() if response == 'Yes')
        no_count = len(all_answers) - yes_count

        # Creating a horizontal bar chart
        fig = plt.figure(figsize=(8, 6))
        plt.barh(['Yes', 'No'], [yes_count, no_count], color=['green', 'red'])
        plt.xlabel('Count')
        plt.title('Count of "Yes" and "No" Responses for Waste Management Practices')
        # Adding data labels to the bars
        for index, value in enumerate([yes_count, no_count]):
            plt.text(value, index, f'{value}', ha='right', va='center')
        st.pyplot(fig)

    def calculate_waste_score(all_answers):
        score = 0
        max_possible_score = 0

        # Scoring for Yes/No questions (5 points for each 'Yes')
        yes_no_questions = [
            "80. Do you have a waste management plan in place for your logistics operations?",
            "81. Do you actively implement waste reduction and recycling initiatives?",
            "82. Is waste segregated according to type (hazardous, non-hazardous, recyclable) at your facilities?",
            "83. Are there measures to minimize waste generation in cargo handling or packaging processes?",
            "84. Do you have initiatives for reusing or repurposing materials and equipment to reduce waste?",
            "85. Do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?",
            "86. Are waste reduction and recycling efforts communicated to logistics employees?",
            "88. Have you conducted waste audits or assessments to evaluate waste management practices?",
            "89. Are there plans to improve waste management and recycling efforts in the future?",
            "90. Do you use software or systems for waste tracking and reporting?",
            "91. Have you set quantifiable goals for waste reduction in the next year?",
            "93. Do you have partnerships with recycling or waste management companies?",
            "94. Do you provide training on waste management for new employees?",
            "95. Have you implemented a policy to reduce single-use items within logistics operations?",
            "96. Do you conduct regular waste management compliance checks?",
            "97. Do you participate in or support community waste management programs?",
            "99. Have you received any certifications or awards for your waste management practices?",
            "100. Is there a designated team or department responsible for waste management?"
        ]
        for question in yes_no_questions:
            response = all_answers.get(question, "No").lower()
            if response == 'yes':
                score += 5
            max_possible_score += 5

        # Scoring for quantitative questions
        recycling_percentage = all_answers.get("87. What percentage of waste is recycled or diverted from landfills in your logistics operations?", 0)
        waste_reduction_target = all_answers.get("92. What is your target percentage for waste reduction in the next year?", 0)
        zero_waste_to_landfill = all_answers.get("98. What percentage of your logistics operations are zero-waste to landfill?", 0)

        # Adding up to 10 points for each of the percentage-based questions based on their value
        score += min(10, int(recycling_percentage / 10))
        score += min(10, int(waste_reduction_target / 10))
        score += min(10, int(zero_waste_to_landfill / 10))
        max_possible_score += 30

        # Ensure score is within 0-100 range and calculate the percentage score
        score = max(0, min(score, max_possible_score))
        percentage_score = (score / max_possible_score) * 100

        return percentage_score

    # Calculate sustainability score
    score = calculate_waste_score(all_answers)

    # Display formatted score
    #st.write(f"**Waste Sustainability Score:**")
    #st.write(f"**{score:.1f}%**")

    def visualize_waste_score(all_answers):
        # Calculate the waste score
        waste_score = calculate_waste_score(all_answers)

        # Scoring components for visualization
        # Scoring components for visualization
        components = {
            'Waste Management Plan': 5 if all_answers.get("80. Do you have a waste management plan in place for your logistics operations?", "No") == "Yes" else 0,
            'Recycling Initiatives': 5 if all_answers.get("81. Do you actively implement waste reduction and recycling initiatives?", "No") == "Yes" else 0,
            'Waste Segregation': 5 if all_answers.get("82. Is waste segregated according to type (hazardous, non-hazardous, recyclable) at your facilities?", "No") == "Yes" else 0,
            'Minimize Waste Generation': 5 if all_answers.get("83. Are there measures to minimize waste generation in cargo handling or packaging processes?", "No") == "Yes" else 0,
            'Reuse/Repurpose Initiatives': 5 if all_answers.get("84. Do you have initiatives for reusing or repurposing materials and equipment to reduce waste?", "No") == "Yes" else 0,
            'Proper Disposal of Hazardous Materials': 5 if all_answers.get("85. Do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?", "No") == "Yes" else 0,
            'Employee Communication on Waste': 5 if all_answers.get("86. Are waste reduction and recycling efforts communicated to logistics employees?", "No") == "Yes" else 0,
            'Waste Audits': 5 if all_answers.get("88. Have you conducted waste audits or assessments to evaluate waste management practices?", "No") == "Yes" else 0,
            'Future Improvement Plans': 5 if all_answers.get("89. Are there plans to improve waste management and recycling efforts in the future?", "No") == "Yes" else 0,
            'Waste Tracking Software': 5 if all_answers.get("90. Do you use software or systems for waste tracking and reporting?", "No") == "Yes" else 0,
            'Waste Reduction Goals': 5 if all_answers.get("91. Have you set quantifiable goals for waste reduction in the next year?", "No") == "Yes" else 0,
            'Recycling Partnerships': 5 if all_answers.get("93. Do you have partnerships with recycling or waste management companies?", "No") == "Yes" else 0,
            'Employee Training on Waste': 5 if all_answers.get("94. Do you provide training on waste management for new employees?", "No") == "Yes" else 0,
            'Single-Use Item Reduction': 5 if all_answers.get("95. Have you implemented a policy to reduce single-use items within logistics operations?", "No") == "Yes" else 0,
            'Compliance Checks': 5 if all_answers.get("96. Do you conduct regular waste management compliance checks?", "No") == "Yes" else 0,
            'Community Program Participation': 5 if all_answers.get("97. Do you participate in or support community waste management programs?", "No") == "Yes" else 0,
            'Waste Management Awards': 5 if all_answers.get("99. Have you received any certifications or awards for your waste management practices?", "No") == "Yes" else 0,
            'Dedicated Waste Team': 5 if all_answers.get("100. Is there a designated team or department responsible for waste management?", "No") == "Yes" else 0,
            'Recycling Percentage': min(10, int(all_answers.get("87. What percentage of waste is recycled or diverted from landfills in your logistics operations?", 0) / 10)),
            'Zero Waste to Landfill': min(10, int(all_answers.get("98. What percentage of your logistics operations are zero-waste to landfill?", 0) / 10)),
            'Waste Reduction Target': min(10, int(all_answers.get("92. What is your target percentage for waste reduction in the next year?", 0) / 10))
        }

        component_names = list(components.keys())
        component_scores = list(components.values())

        # Split the scores into positive and negative scores for the stacked bar chart
        positive_scores = [score if score > 0 else 0 for score in component_scores]
        negative_scores = [score if score < 0 else 0 for score in component_scores]

        # Create a stacked bar chart
        fig, ax = plt.subplots(figsize=(10, 8))
        ax.barh(component_names, positive_scores, color='skyblue', label='Positive Scores')
        ax.barh(component_names, negative_scores, color='salmon', label='Negative Scores')

        # Add waste score as text to the right of the bar
        for i, (pos_score, neg_score) in enumerate(zip(positive_scores, negative_scores)):
            total_score = pos_score + neg_score
            ax.text(max(total_score, 0) + 0.2, i,
                    f'{total_score:.1f}',
                    va='center', fontsize=10, fontweight='bold', color='grey')

        # Set labels and title
        ax.set_xlabel('Scores')
        ax.set_title(f'Waste Management Score: {waste_score:.1f}%')
        ax.legend()

        # Adjust layout
        plt.tight_layout()

        return fig

    # Assuming all_answers is a dictionary with the answers
    # Call the function with the answers dictionary
    #fig = visualize_waste_score(all_answers)
    #st.pyplot(fig)


    explanation_W_metric = """
    The Waste Management Score is calculated based on various factors that reflect sustainable waste management practices in logistics operations. Here's a breakdown of how the score is composed:

    - **Waste Management Plan:** Whether there is a waste management plan in place for logistics operations. Having a plan contributes positively to the score.
    - **Recycling Initiatives:** Actively implementing waste reduction and recycling initiatives adds points to the score.
    - **Waste Segregation:** Segregation of waste according to type (hazardous, non-hazardous, recyclable) at facilities contributes positively to the score.
    - **Minimize Waste Generation:** Measures to minimize waste generation in cargo handling or packaging processes are scored positively.
    - **Reuse/Repurpose Initiatives:** Initiatives for reusing or repurposing materials and equipment to reduce waste contribute to a higher score.
    - **Proper Disposal of Hazardous Materials:** Ensuring proper disposal of hazardous materials and chemicals used in logistics operations adds points to the score.
    - **Employee Communication on Waste:** Communicating waste reduction and recycling efforts to logistics employees positively affects the score.
    - **Waste Audits:** Conducting waste audits or assessments to evaluate waste management practices contributes positively to the score.
    - **Future Improvement Plans:** Having plans to improve waste management and recycling efforts in the future adds to the score.
    - **Waste Tracking Software:** Using software or systems for waste tracking and reporting contributes positively to the score.
    - **Waste Reduction Goals:** Setting quantifiable goals for waste reduction in the next year adds points to the score.
    - **Recycling Partnerships:** Having partnerships with recycling or waste management companies contributes positively to the score.
    - **Employee Training on Waste:** Providing training on waste management for new employees adds points to the score.
    - **Single-Use Item Reduction:** Implementing a policy to reduce single-use items within logistics operations contributes to a higher score.
    - **Compliance Checks:** Conducting regular waste management compliance checks adds points to the score.
    - **Community Program Participation:** Participating in or supporting community waste management programs contributes positively to the score.
    - **Waste Management Awards:** Receiving certifications or awards for waste management practices adds points to the score.
    - **Dedicated Waste Team:** Having a designated team or department responsible for waste management contributes positively to the score.
    - **Recycling Percentage:** The percentage of waste recycled or diverted from landfills impacts the score positively.
    - **Zero Waste to Landfill:** The percentage of logistics operations being zero-waste to landfill contributes positively to the score.
    - **Waste Reduction Target:** Setting a target percentage for waste reduction in the next year adds points to the score.

    A higher Waste Management Score indicates a stronger commitment to sustainable waste management practices and efficient waste reduction strategies in logistics operations.
    """

    #st.markdown(explanation_W_metric)

    def evaluate_waste_sustainability_practice(score, df):
        # Counting 'Yes' responses for waste-related Yes/No questions
        waste_yes_no_questions = [
            question[0] for question in sections["Waste Management"] if question[1] == 'radio'
        ]
        yes_count = sum(
            df[question].eq('Yes').sum() for question in waste_yes_no_questions if question in df.columns
        )
        yes_percentage = (yes_count / len(waste_yes_no_questions)) * 100 if waste_yes_no_questions else 0

        # Calculate a combined waste sustainability index
        combined_index = (0.6 * score) + (0.4 * yes_percentage)

        # Grading system with detailed advice for waste sustainability
        if combined_index >= 80:
            grade = "A (Eco-Champion 🌍)"
            st.image("Eco-Champion.png")
            explanation = "You demonstrate exemplary waste management practices, setting a high benchmark in sustainability."
            advice = "Continue leading and innovating in waste management, and share your successful practices with others."
        elif combined_index >= 60:
            grade = "B (Sustainability Steward πŸƒ)"
            st.image("Sustainability_Steward.png", use_column_width=True)
            explanation = "Your efforts in waste management reflect a strong commitment to sustainability."
            advice = "Keep improving your waste reduction strategies and explore new technologies for recycling and waste-to-energy conversion."
        elif combined_index >= 40:
            grade = "C (Eco-Advancer 🌿)"
            st.image("Eco-Advancer.png")
            explanation = "You're actively working towards better waste management but have room to grow."
            advice = "Enhance your waste reduction and recycling programs, and consider community engagement for broader impact."
        elif combined_index >= 20:
            grade = "D (Green Learner 🌼)"
            st.image("Green_Learner.png")
            explanation = "You've started to engage in sustainable waste management practices, but there's much to develop."
            advice = "Focus on establishing a solid waste management plan and educate your team about its importance and implementation."
        else:
            grade = "E (Eco-Novice 🌱)"
            st.image("Eco-Novice.png", use_column_width=True)
            explanation = "You are at the early stages of adopting sustainable waste management practices."
            advice = "Begin with basic steps like segregation of waste, regular audits, and simple recycling initiatives to build a foundation for sustainable practices."

        return f"**Sustainability Grade: {grade}** \n\n**Explanation:** \n{explanation} \n\n**Detailed Advice:** \n{advice}"

    #st.markdown(evaluate_waste_sustainability_practice(score, answers_df), unsafe_allow_html=True)

    def generate_swot_analysis(company_data):
       # Extracting relevant data from company_data
       logistics_sustainability_level = company_data.get("Logistics Sustainability Level", "None")
       annual_carbon_emissions = company_data.get("Annual Carbon Emissions (in metric tons)", 0)
       utilize_renewable_energy = company_data.get("Utilize Renewable Energy Sources", False)
       selected_certifications = company_data.get("Selected Logistics Certifications and Initiatives", [])
       company_summary = company_data.get("Company Summary", "No specific information provided.")

       # Constructing a dynamic SWOT analysis based on extracted data
       strengths = [
           "Utilization of Renewable Energy Sources" if utilize_renewable_energy else "None"
       ]

       weaknesses = [
           "Lack of Logistics Sustainability Level: " + logistics_sustainability_level,
           "Zero Annual Carbon Emissions" if annual_carbon_emissions == 0 else "Annual Carbon Emissions Present",
           "Company Summary: " + company_summary
       ]

       opportunities = [
           "Exploration of Logistics Certifications" if not selected_certifications else "None"
       ]

       threats = [
           "Competitive Disadvantage Due to Lack of Certifications" if not selected_certifications else "None"
       ]

       # Constructing a SWOT analysis prompt dynamically
       swot_analysis_prompt = f"""
       Strengths, Weaknesses, Opportunities, Threats (SWOT) Analysis:

       Strengths:
       Strengths Analysis:
       {", ".join(strengths)}

       Weaknesses:
       Weaknesses Analysis:
       {", ".join(weaknesses)}

       Opportunities:
       Opportunities Analysis:
       {", ".join(opportunities)}

       Threats:
       Threats Analysis:
       {", ".join(threats)}
       """

       # OpenAI API call for SWOT analysis
       response_swot = openai.ChatCompletion.create(
           model="gpt-3.5-turbo-16k",
           messages=[
               {"role": "assistant", "content": "You are analyzing the company's sustainability practices."},
               {"role": "system", "content": "Conduct a SWOT analysis based on the provided company data."},
               {"role": "user", "content": swot_analysis_prompt}
           ],
           max_tokens=1000,
           temperature=0.5,
           top_p=1.0,
           frequency_penalty=0.5,
           presence_penalty=0.0
       )

       # Extracting the SWOT analysis content from the response
       swot_analysis_content = response_swot.choices[0].message['content']

       return swot_analysis_content

    def evaluate_waste_sustainability_report(all_answers, score):
        """Generates a Waste Sustainability report based on responses to a questionnaire."""
        extracted_data = extract_data(all_answers)

        # Consolidate data for waste sustainability
        waste_management_plan = extracted_data.get("80. Do you have a waste management plan in place for your logistics operations?", "N/A")
        waste_reduction_initiatives = extracted_data.get("81. Do you actively implement waste reduction and recycling initiatives?", "N/A")
        waste_segregation = extracted_data.get("82. Is waste segregated according to type at your facilities?", "N/A")
        waste_minimization_measures = extracted_data.get("83. Are there measures to minimize waste generation in cargo handling or packaging processes?", "N/A")
        waste_reuse_repurpose = extracted_data.get("84. Do you have initiatives for reusing or repurposing materials and equipment to reduce waste?", "N/A")
        proper_disposal_hazardous = extracted_data.get("85. Do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?", "N/A")
        waste_communication_employees = extracted_data.get("86. Are waste reduction and recycling efforts communicated to logistics employees?", "N/A")
        waste_recycling_percentage = extracted_data.get("87. What percentage of waste is recycled or diverted from landfills in your logistics operations?", 0)
        waste_audits_assessments = extracted_data.get("88. Have you conducted waste audits or assessments to evaluate waste management practices?", "N/A")
        future_improvement_plans = extracted_data.get("89. Are there plans to improve waste management and recycling efforts in the future?", "N/A")
        waste_tracking_software = extracted_data.get("90. Do you use software or systems for waste tracking and reporting?", "N/A")
        quantifiable_goals_waste_reduction = extracted_data.get("91. Have you set quantifiable goals for waste reduction in the next year?", "N/A")
        target_percentage_waste_reduction = extracted_data.get("92. What is your target percentage for waste reduction in the next year?", 0)
        recycling_partnerships = extracted_data.get("93. Do you have partnerships with recycling or waste management companies?", "N/A")
        waste_management_training_employees = extracted_data.get("94. Do you provide training on waste management for new employees?", "N/A")
        policy_reduce_single_use_items = extracted_data.get("95. Have you implemented a policy to reduce single-use items within logistics operations?", "N/A")
        compliance_checks = extracted_data.get("96. Do you conduct regular waste management compliance checks?", "N/A")
        community_programs_participation = extracted_data.get("97. Do you participate in or support community waste management programs?", "N/A")
        zero_waste_to_landfill = extracted_data.get("98. What percentage of your logistics operations are zero-waste to landfill?", 0)
        waste_management_certifications_awards = extracted_data.get("99. Have you received any certifications or awards for your waste management practices?", "N/A")
        designated_waste_team = extracted_data.get("100. Is there a designated team or department responsible for waste management?", "N/A")

        consolidated_report = f"""
        Waste Sustainability Report
        Score: {score}/100
        Report Details:
        Waste Management Plan: {waste_management_plan}
        Recycling Initiatives: {waste_reduction_initiatives}
        Waste Segregation: {waste_segregation}
        Minimize Waste Generation: {waste_minimization_measures}
        Reuse/Repurpose Initiatives: {waste_reuse_repurpose}
        Proper Disposal of Hazardous Materials: {proper_disposal_hazardous}
        Employee Communication on Waste: {waste_communication_employees}
        Recycling Percentage: {waste_recycling_percentage}%
        Waste Audits/Assessments: {waste_audits_assessments}
        Future Improvement Plans: {future_improvement_plans}
        Waste Tracking Software: {waste_tracking_software}
        Quantifiable Goals for Waste Reduction: {quantifiable_goals_waste_reduction}
        Target Percentage for Waste Reduction: {target_percentage_waste_reduction}%
        Recycling Partnerships: {recycling_partnerships}
        Waste Management Training for Employees: {waste_management_training_employees}
        Policy to Reduce Single-Use Items: {policy_reduce_single_use_items}
        Compliance Checks: {compliance_checks}
        Community Programs Participation: {community_programs_participation}
        Zero Waste to Landfill: {zero_waste_to_landfill}%
        Waste Management Certifications/Awards: {waste_management_certifications_awards}
        Designated Waste Team: {designated_waste_team}
        """

        # Include further analysis via OpenAI API
        prompt = f"""
        As a waste sustainability advisor, analyze the Waste Sustainability Report with a score of {score}/100. Review the provided data points and offer a detailed analysis. Identify strengths, weaknesses, and areas for improvement in waste management practices. Provide specific recommendations to enhance waste sustainability considering the current waste management initiatives and recycling strategies.

        Data Points:
        {consolidated_report}
        """

        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo-16k",
                messages=[
                    {"role": "system", "content": "Analyze the data and provide comprehensive insights and recommendations."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=4000,
                temperature=0.7,
                top_p=1.0,
                frequency_penalty=0,
                presence_penalty=0
            )

            evaluation_content = response.choices[0].message['content']

            refined_report = f"{consolidated_report}\n\n{evaluation_content}"
            return refined_report

        except Exception as e:
            return f"Error: {e}"

    # Function to format answer for better readability
    def format_answer(answer):
        if isinstance(answer, bool):
            return "Yes" if answer else "No"
        elif isinstance(answer, (int, float)):
            return str(answer)
        return answer  # Assume the answer is already in a string format

    # Function to extract and format data from a dictionary
    def extract_data(data):
        formatted_data = {}
        for key, value in data.items():
            formatted_data[key] = format_answer(value)
        return formatted_data

    #report = evaluate_waste_sustainability_report(all_answers, score)

    #st.write(report)

    def get_waste_sustainability_strategy(all_answers, company_data):
        # Extracting and formatting data from all_answers and company_data
        extracted_all_answers = extract_data(all_answers)
        extracted_company_data = extract_data(company_data)

        # Forming the prompt with extracted data
        prompt = f"""
        Based on the provided company and waste sustainability assessment data, provide a waste sustainability strategy:

        **Company Info**:
        - Logistics Sustainability Level: {extracted_company_data.get('Logistics Sustainability Level', 'N/A')}
        - Annual Carbon Emissions: {extracted_company_data.get('Annual Carbon Emissions (in metric tons)', 'N/A')} metric tons
        - Utilize Renewable Energy Sources: {extracted_company_data.get('Utilize Renewable Energy Sources', 'No')}
        - Certifications: {extracted_company_data.get('Selected Logistics Certifications and Initiatives', 'N/A')}
        - Company Summary: {extracted_company_data.get('Company Summary', 'N/A')}

        **Waste Sustainability Assessment Data**:
        - Waste Management Plan: {extracted_all_answers.get("80. Do you have a waste management plan in place for your logistics operations?", "N/A")}
        - Recycling Initiatives: {extracted_all_answers.get("81. Do you actively implement waste reduction and recycling initiatives?", "N/A")}
        - Waste Segregation: {extracted_all_answers.get("82. Is waste segregated according to type at your facilities?", "N/A")}
        - Minimize Waste Generation: {extracted_all_answers.get("83. Are there measures to minimize waste generation in cargo handling or packaging processes?", "N/A")}
        - Reuse/Repurpose Initiatives: {extracted_all_answers.get("84. Do you have initiatives for reusing or repurposing materials and equipment to reduce waste?", "N/A")}
        - Proper Disposal of Hazardous Materials: {extracted_all_answers.get("85. Do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?", "N/A")}
        - Employee Communication on Waste: {extracted_all_answers.get("86. Are waste reduction and recycling efforts communicated to logistics employees?", "N/A")}
        - Recycling Percentage: {extracted_all_answers.get("87. What percentage of waste is recycled or diverted from landfills in your logistics operations?", 0)}%
        - Waste Audits/Assessments: {extracted_all_answers.get("88. Have you conducted waste audits or assessments to evaluate waste management practices?", "N/A")}
        - Future Improvement Plans: {extracted_all_answers.get("89. Are there plans to improve waste management and recycling efforts in the future?", "N/A")}
        - Waste Tracking Software: {extracted_all_answers.get("90. Do you use software or systems for waste tracking and reporting?", "N/A")}
        - Quantifiable Goals for Waste Reduction: {extracted_all_answers.get("91. Have you set quantifiable goals for waste reduction in the next year?", "N/A")}
        - Target Percentage for Waste Reduction: {extracted_all_answers.get("92. What is your target percentage for waste reduction in the next year?", 0)}%
        - Recycling Partnerships: {extracted_all_answers.get("93. Do you have partnerships with recycling or waste management companies?", "N/A")}
        - Waste Management Training for Employees: {extracted_all_answers.get("94. Do you provide training on waste management for new employees?", "N/A")}
        - Policy to Reduce Single-Use Items: {extracted_all_answers.get("95. Have you implemented a policy to reduce single-use items within logistics operations?", "N/A")}
        - Compliance Checks: {extracted_all_answers.get("96. Do you conduct regular waste management compliance checks?", "N/A")}
        - Community Programs Participation: {extracted_all_answers.get("97. Do you participate in or support community waste management programs?", "N/A")}
        - Zero Waste to Landfill: {extracted_all_answers.get("98. What percentage of your logistics operations are zero-waste to landfill?", 0)}%
        - Waste Management Certifications/Awards: {extracted_all_answers.get("99. Have you received any certifications or awards for your waste management practices?", "N/A")}
        - Designated Waste Team: {extracted_all_answers.get("100. Is there a designated team or department responsible for waste management?", "N/A")}

        Offer an actionable strategy considering the company's specific context and waste sustainability data.
        """

        additional_context = f"Provide a detailed waste sustainability strategy using context data from the above company info and in responses to the waste sustainability assessment."
        # Assuming you have an API call here to generate a response based on the prompt
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-16k",
            messages=[
                {"role": "assistant", "content": "You are a waste sustainability strategy advisor."},
                {"role": "user", "content": prompt},
                {"role": "user", "content": additional_context}
            ],
            max_tokens=4000,
            temperature=0.7,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0
        )

        return response.choices[0].message['content']

    #strategy = get_waste_sustainability_strategy(all_answers, company_data)

    #st.write(strategy)
    def get_certification_details(certification_name):
        # Prepare the prompt for the API call
        messages = [
            {"role": "system", "content": "You are a knowledgeable assistant about global certifications."},
            {"role": "user", "content": f"Provide detailed information on how to obtain the {certification_name} certification."}
        ]

        # Query the OpenAI API for information on the certification process
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-16k",
            messages=messages,
            max_tokens=2000,
            temperature=0.3,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0
        )

        # Return the content of the response
        return response.choices[0].message['content']

    def advise_on_waste_sustainability_certification(company_data):
        # Check if company_data is a dictionary
        if not isinstance(company_data, dict):
            raise ValueError("company_data must be a dictionary")

        # Extract company data relevant to waste sustainability certifications
        has_waste_management_plan = company_data.get('Do you have a waste management plan?', False)
        waste_reduction_initiatives = company_data.get('Implement waste reduction initiatives?', False)
        segregate_waste = company_data.get('Segregate waste at facilities?', False)
        recycling_percentage = company_data.get('Recycling percentage', 0)
        partnerships_recycling_companies = company_data.get('Partnerships with recycling companies?', False)
        waste_management_certifications = company_data.get('Waste management certifications', [])

        # Initialize a string to store recommendations
        recommendations_text = ""

        # Determine which waste sustainability certifications to suggest based on the provided data
        waste_certifications_to_consider = {
            "Zero Waste Certification": not has_waste_management_plan,
            "Recycling Initiative Certification": not waste_reduction_initiatives,
            "Waste Segregation Certification": not segregate_waste,
            "Recycling Percentage Improvement Certification": recycling_percentage < 30,
            "Partnership with Recycling Companies Certification": not partnerships_recycling_companies,
            "Advanced Waste Management Certification": "Advanced Waste Management" not in waste_management_certifications
        }

        for certification, consider in waste_certifications_to_consider.items():
            if consider:
                try:
                    certification_details = get_certification_details(certification)
                    recommendations_text += f"\n\nFor {certification}, here's what you need to know: {certification_details}"
                except Exception as e:
                    recommendations_text += f"\n\nError retrieving details for {certification}: {e}"

        # If no waste sustainability certifications are suggested, add a message
        if not recommendations_text.strip():
            recommendations_text = "Based on the provided data, there are no specific waste sustainability certifications recommended at this time."

        # Return the combined recommendations as a single formatted string
        return recommendations_text

    #reply = advise_on_waste_sustainability_certification(company_data)

    #st.write(reply)
    st.markdown("<br>"*1, unsafe_allow_html=True)

    if st.button('Submit'):

        try:
           # Use a spinner for generating advice
           with st.spinner("Generating report and advice..."):
               st.subheader("Visualize Waste Data")
               Waste_Management_Practices(all_answers)

               visualize_data1(all_answers) # Call the function with the dictionary containing the answers


               st.subheader("Visualize Waste Scores")

               # Calculate sustainability score
               score = calculate_waste_score(all_answers)

               # Display formatted score
               st.write(f"**Waste Sustainability Score:**")
               st.markdown(f"**{score:.1f}%**")

               fig = visualize_waste_score(all_answers)
               st.pyplot(fig)

               st.markdown(explanation_W_metric)

               st.subheader("Visualize Sustainability Grade")
               # Call the function with the DataFrame

               st.markdown(evaluate_waste_sustainability_practice(score, answers_df), unsafe_allow_html=True)

               strategy = get_waste_sustainability_strategy(all_answers, company_data)
               #strategy = get_energy_sustainability_advice(strategy, company_data)
               report = evaluate_waste_sustainability_report(all_answers, score)
               #st.subheader("Energy Sustainability Strategy")
               # Extracting the SWOT analysis content from the response
               swot_analysis_content = generate_swot_analysis(company_data)
               #st.subheader("Energy Sustainability Strategy")
               st.subheader("Company SWOT Report")
               st.write(swot_analysis_content)

               st.subheader("Waste Sustainability Report")
               st.write(report)
               st.download_button(
                   label="Download Waste Sustainability Report",
                       data=report,
                       file_name='sustainability_report.txt',
                       mime='text/txt',
                       key="download_report_button",  # Unique key for this button
                       )

               st.subheader("Sustainability Strategy")
               st.write(strategy)
               st.download_button(
                   label="Download Waste Sustainability Strategy",
                   data=strategy,
                   file_name='sustainability_strategy.txt',
                   mime='text/txt',
                   key="download_strategy_button",  # Unique key for this button
               )

               st.subheader("Advice on Sustainability Certification")
               #certification_advice = advise_on_transport_sustainability_certification(company_data)
               try:
                   advice = advise_on_waste_sustainability_certification(company_data)
                   st.write(advice)
               except ValueError as e:
                   print(e)

        # Embed a YouTube video after processing
           st.subheader("Watch More on Sustainability")
           video_urls = [
           "https://www.youtube.com/watch?v=BawgdP1jmPo",
           #"https://www.youtube.com/watch?v=your_video_url_2",
           #"https://www.youtube.com/watch?v=your_video_url_3",
           # Add more video URLs as needed
           ]

           # Select a random video URL from the list
           random_video_url = random.choice(video_urls)

           # Display the random video
           st.video(random_video_url)

        except Exception as e:
           st.error(f"An error occurred: {e}")

        st.write("""
        ---
        *Powered by Streamlit, CarbonInterface API, and OpenAI.*
        """)

def page4():

    # Function to encode the image to base64
    def encode_image(image):
        buffered = io.BytesIO()
        image.save(buffered, format="JPEG")
        return base64.b64encode(buffered.getvalue()).decode('utf-8')

    # Function to provide sustainability advice based on trash information
    def sustainability_advice_with_elements(key_elements):
        try:
            messages = [
                {"role": "system", "content": "You are a knowledgeable assistant on waste management and sustainability."},
                {"role": "user", "content": f"Please generate sustainable methods to dispose of the identified waste elements.\n\nKey Waste Elements:\n{key_elements}"}
            ]
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=messages,
                max_tokens=1000,
                temperature=0
            )
            advice = response.choices[0].message['content']
            return advice
        except Exception as e:
            return f"Error: {e}"


    def extract_key_elements_with_openai(trash_info):
        messages=[
            {"role": "system", "content": "Identify waste elements from the given information."},
            {"role": "user", "content": trash_info}
        ],
        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "Identify waste elements from the given information."},
                    {"role": "user", "content": trash_info}
                ],
                max_tokens=300,
                temperature=0.3,
                top_p=1.0,
                frequency_penalty=0.0,
                presence_penalty=0.0,
                stop=["."]
            )

            elements = response.choices[0].message['content']
            return elements

        except Exception as e:
            return f"Error: {e}"

    def sustainability_advice(trash_info):
        # Prepare the prompt for the API call
        messages = [
            {"role": "system", "content": "You are an environmental sustainability advisor."},
            {"role": "user", "content": f"Provide sustainable methods to dispose of this trash. Description: {trash_info}"}
        ]

        # Query the OpenAI API for advice on sustainable trash disposal methods
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=messages,
            max_tokens=1500,
            temperature=0.5,
            top_p=1.0,
            frequency_penalty=0.0,
            presence_penalty=0.0
        )

        # Get the advice on sustainable trash disposal methods
        advice = response.choices[0].message['content']


    # Streamlit app

    st.write("<center><h1>Trash Ninja: Waste Classification Assistant</h1></center>", unsafe_allow_html=True)
    #st.title('Trash Ninja: Waste Classification Assistant')
    st.image("banner1.png", use_column_width=True)
    # Provide instructions for image upload

     # Providing instructions for image upload
    st.markdown("""
        **Step 1: Capture a Clear Image**
        - Center the trash item in your photo.
        - Use a plain, contrasting background.
        - Ensure good lighting to make the item clearly visible.

        **Step 2: Upload Your Image**
        - Click 'Browse' to select your image file (JPG, JPEG, or PNG format).

        **Step 3: Analyze and Get Insights**
        - Once the image is uploaded, click 'Analyze Image' to receive your classification and sustainable disposal advice.

        **Note:** For best results, avoid including multiple items or excessive background clutter in your image.
    """)
    # Instructions and other static content can go here

    # User uploads an image of trash
    uploaded_file = st.file_uploader("Upload an image of the trash item you want to classify", type=["jpg", "jpeg", "png"])

    # Button to analyze the image and provide sustainability advice
    if st.button(label='Analyze Image'):
        if uploaded_file is not None:
            # Display the uploaded image
            image = Image.open(uploaded_file)
            st.image(image, caption='Uploaded Trash Image', use_column_width=True)

            # Placeholder for analysis function call
            st.success("Image analysis successful! (Placeholder for actual analysis results)")


            # Encode the image for GPT-4 Vision API
            encoded_image = encode_image(image)

            # Call to GPT-4 Vision API (replace with your actual API call)

            with st.spinner('Analyzing the image...'):
                result = openai.ChatCompletion.create(
                    model="gpt-4-vision-preview",
                    messages=[
                        {
                            "role": "user",
                            "content": [
                                {"type": "text", "text": "Analyze this picture of trash and identify the type."},
                                {"type": "image_url", "image_url": f"data:image/jpeg;base64,{encoded_image}"},
                            ]
                        },
                    ],
                    max_tokens=900
                )

            # Check if a response was received
            if result.choices:
                trash_info = result.choices[0].message.content
                st.write("Analysis Result:")
                st.info(trash_info)

                # Provide sustainability advice based on the analysis
                with st.spinner('Generating sustainability advice...'):
                    # Extract key elements using OpenAI GPT-3 model
                    extracted_elements = extract_key_elements_with_openai(trash_info)

                    # Generate sustainability advice based on extracted key elements
                    advice_based_on_elements = sustainability_advice_with_elements(extracted_elements)

                    st.write("Sustainability Advice:")
                    st.info(advice_based_on_elements)
            else:
                st.error("No response was received. Please try again with a different image.")
        else:
            st.error("Please upload an image to proceed.")

        # Provide educational content after the analysis
        st.markdown("""
            **Why Recycle?**
            - **Environmental Protection:** Recycling reduces the need for extracting, refining, and processing raw materials, which create substantial air and water pollution. Recycling saves energy and reduces greenhouse gas emissions, helping to tackle climate change.
            - **Conservation:** Recycling conserves natural resources such as timber, water, and minerals, ensuring they last longer for future generations.
            - **Energy Efficiency:** Manufacturing with recycled materials uses less energy than creating products from virgin materials.
            - **Economic Benefits:** Recycling creates jobs in the collection, processing, and selling of recyclable materials.
        """)

def page5():
    st.write("<center><h1>Emission Excellence: Paving the Way to Sustainability</h1></center>", unsafe_allow_html=True)
    st.image("page5.1.png", use_column_width=True)

    st.write("Assess and improve the sustainability of your logistics operations.")
    st.header("Company Information")

    input_option = st.radio("Choose an input option:", ["Enter logistics company's website URL", "Provide company description manually"])

    # Function to extract logistics information from a website URL
    def extract_logistics_info_from_website(url):
      try:
          response = requests.get(url)
          response.raise_for_status()  # Raise an exception for HTTP errors (e.g., 404)

          # Parse the HTML content of the page
          soup = BeautifulSoup(response.text, 'html.parser')

          # Example: Extract company description from the website
          company_description = soup.find('meta', attrs={'name': 'description'})
          if company_description:
              return company_description['content']

      except requests.exceptions.RequestException as e:
          return f"Error: Unable to connect to the website ({e})"
      except Exception as e:
          return f"Error: {e}"

      return None

    # Function to summarize logistics information using OpenAI's GPT-3 model
    def summarize_logistics_info(logistics_info):
      prompt = f"""
      Please extract the following information from the logistics company's description:
      - Core logistics services offered
      - Sustainability practices or initiatives related to logistics

      Description:
      {logistics_info}

      Please provide responses while avoiding speculative or unfounded information.
      """
      try:
          response = openai.ChatCompletion.create(
              model="gpt-3.5-turbo",
              messages=[
                  {"role": "system", "content": "You are an excellent sustainability assessment tool for logistics."},
                  {"role": "user", "content": prompt}
              ],
              max_tokens=100,
              temperature=0
          )
          company_summary = response.choices[0].message['content']

          return company_summary
      except Exception as e:
          return f"Error: {e}"

    # Streamlit UI
    st.title("Logistics Information Extractor")
    st.write("Extract logistics information from a logistics company's website URL.")

    # User input field for the website URL
    #website_url = st.text_input("Enter the logistics company's website URL:")

    if input_option == "Enter logistics company's website URL":
      example_url = "https://quangninhport.com.vn/en/home"
      website_url = st.text_input("Please enter the logistics company's website URL:", example_url)
      if website_url:
          # Ensure the URL starts with http/https
          website_url = website_url if website_url.startswith(("http://", "https://")) else "https://" + website_url

          logistics_info = extract_logistics_info_from_website(website_url)
          if logistics_info:
              company_summary = summarize_logistics_info(logistics_info)
              #st.write("Company Summary:")
              #st.write(company_summary)

    elif input_option == "Provide company description manually":
      st.markdown("""
          Please provide a description of the logistics company, focusing on the following:
          - Core logistics services offered
          - Sustainability practices or initiatives related to logistics
      """)
      company_description = st.text_area("Please provide the company description:", "")

      if company_description:
          company_summary = summarize_logistics_info(company_description)


    st.header("Logistics Sustainability Information")

    # Definitions for logistics sustainability levels
    sustainability_info = {
      "None": "No sustainability info available",
      "Green Logistics": "Green logistics refers to environmentally friendly practices in logistics operations, such as using electric vehicles, optimizing routes to reduce emissions, and minimizing packaging waste.",
      "Sustainable Supply Chain": "A sustainable supply chain involves responsible sourcing, ethical labor practices, and reducing the carbon footprint throughout the supply chain.",
      "Circular Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing waste in packaging and materials, leading to a more sustainable and resource-efficient approach.",
    }

    sustainability_level = st.selectbox("Logistics Sustainability Level", list(sustainability_info.keys()))

    # Display the definition when the user selects a sustainability level
    if sustainability_level in sustainability_info:
      st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}")

    # Additional sustainability-related information
    carbon_emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)", min_value=0)
    renewable_energy = st.checkbox("Does the company utilize Renewable Energy Sources in its operations?")

    # Certification and Sustainability Initiatives
    st.subheader("Certifications and Sustainability Initiatives")

    # Explanations for logistics-related certifications
    logistics_certification_info = {
      "None": "No certifications or initiatives related to logistics.",
      "ISO 14001 for Logistics": "ISO 14001 for Logistics is an international standard that sets requirements for an environmental management system in logistics operations.",
      "SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that reduce fuel use and emissions through efficient transportation practices.",
      "C-TPAT Certification": "C-TPAT (Customs-Trade Partnership Against Terrorism) certification ensures secure and sustainable supply chain practices in logistics.",
      "Green Freight Programs": "Green Freight Programs focus on reducing the environmental impact of freight transportation through efficiency improvements.",
      "Zero Emission Zones Participation": "Participating in Zero Emission Zones demonstrates a commitment to using zero-emission vehicles and reducing emissions in specific areas.",
    }

    selected_certifications = st.multiselect("Select Logistics Certifications and Initiatives", list(logistics_certification_info.keys()))

    # Display explanations for selected certifications
    for certification in selected_certifications:
      if certification in logistics_certification_info:
          st.write(f"**Explanation of {certification}:** {logistics_certification_info[certification]}")

    # Define the company_data dictionary
    company_data = {
      "Logistics Sustainability Level": sustainability_level,
      "Annual Carbon Emissions (in metric tons)": carbon_emissions,
      "Utilize Renewable Energy Sources": renewable_energy,
      "Selected Logistics Certifications and Initiatives": selected_certifications
    }

    # If company_summary is generated, add it to company_data dictionary
    if 'company_summary' in locals() or 'company_summary' in globals():
      company_data["Company Summary"] = company_summary

    #st.write("Company Summary:")
    #st.write(company_summary)


    st.write("<hr>", unsafe_allow_html=True)
    st.write("In this section, we'll explore your company's commitment to emission reduction initiatives. We'll assess your efforts and investments in reducing emissions, as well as any strategies and technologies you employ to achieve this sustainability goal.")
    st.write("<hr>", unsafe_allow_html=True)

    sections = {
          "Emission Reduction Initiatives": [
            ("65. Do you monitor CO2 emissions in your logistics operations?", 'radio', ["Yes", "No"]),
            ("66. Do you have emissions reduction targets in place for your logistics operations?", 'radio', ["Yes", "No"]),
            ("67. Percentage reduction target for CO2 emissions in the next year:", 'number_input', {"min_value": 0, "max_value": 100}),
            ("68. Are measures in place to reduce NOx and SOx emissions in your transportation equipment or facilities?", 'radio', ["Yes", "No"]),
            ("69. Do you have initiatives to minimize particulate matter emissions?", 'radio', ["Yes", "No"]),
            ("70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?", 'radio', ["Yes", "No"]),
            ("71. Do you manage emissions from refrigerated cargo containers?", 'radio', ["Yes", "No"]),
            ("72. Do you have strategies to reduce emissions from idling vehicles and equipment?", 'radio', ["Yes", "No"]),
            ("73. Do you employ emission-reducing practices in your facility’s lighting, heating, and cooling systems?", 'radio', ["Yes", "No"]),
            ("74. Are renewable energy sources used to power your logistics facilities?", 'radio', ["Yes", "No"]),
            ("75. How do you manage emissions from equipment maintenance and repair activities?", 'radio', ["Yes", "No"]),
            ("76. Do you have specific percentage goals for emission reduction in logistics operations?", 'radio', ["Yes", "No"]),
            ("77. Percentage of emission reduction goal achieved last year:", 'number_input', {"min_value": 0, "max_value": 100}),
            ("78. Are emission reduction efforts audited or assessed regularly?", 'radio', ["Yes", "No"]),
            ("79. Are there plans for future emission reduction initiatives in logistics?", 'radio', ["Yes", "No"]),
            ("80. Do you participate in any carbon offset programs?", 'radio', ["Yes", "No"]),
            ("81. Is there a system for tracking and reporting emissions data?", 'radio', ["Yes", "No"]),
            ("82. Do you engage in partnerships or collaborations for emission reduction initiatives?", 'radio', ["Yes", "No"]),
            ("83. Do you provide training or awareness programs on emission reduction for employees?", 'radio', ["Yes", "No"]),
            ("84. Are emission reduction initiatives integrated into your overall business strategy?", 'radio', ["Yes", "No"])
        ]


      }

    # Initialize a dictionary to store the answers
    all_answers = {}

    # Create columns outside the loop
    col1, col2, col3 = st.columns(3)

    # Iterate through each question and display them in columns
    for i, (question_text, input_type, *options) in enumerate(sections["Emission Reduction Initiatives"]):
        # Determine which column to use based on the question index
        if i % 3 == 0:
            col = col1
        elif i % 3 == 1:
            col = col2
        else:
            col = col3

        with col:
            if input_type == 'selectbox':
                all_answers[question_text] = st.selectbox(question_text, options[0])
            elif input_type == 'number_input':
                params = options[0]
                all_answers[question_text] = st.number_input(question_text, **params)
            elif input_type == 'radio':
                all_answers[question_text] = st.radio(question_text, options[0])
            elif input_type == 'slider':
                all_answers[question_text] = st.slider(question_text, 0, 10)

    # Convert answers to a DataFrame for analysis
    answers_df = pd.DataFrame([all_answers])

    #st.write(all_answers)

    # Display the collected answers
    #st.write("Collected Answers:", answers_df)


    def visualize_emission_reduction_data(all_answers):
        # Extracting data for visualization
        next_year_co2_reduction_target = all_answers.get("67. Percentage reduction target for CO2 emissions in the next year:", 0)
        last_year_emission_reduction_achieved = all_answers.get("77. Percentage of emission reduction goal achieved last year:", 0)

        # Creating two columns in Streamlit
        col1, col2 = st.columns(2)

        # Visualizing "67. Percentage reduction target for CO2 emissions in the next year:"
        with col1:
            st.header("CO2 Emission Reduction Target for Next Year")
            st.write(f"**Target Percentage:** {next_year_co2_reduction_target}%")
            st.write("This target represents the company's goal for reducing CO2 emissions over the next year.")
            fig_target_co2 = plt.figure(figsize=(6, 4))
            bar1 = plt.bar("CO2 Reduction Target", next_year_co2_reduction_target, color='skyblue')
            plt.xlabel('Target')
            plt.ylabel('Percentage')
            plt.title('CO2 Emission Reduction Target for Next Year')
            plt.legend([bar1], ['CO2 Reduction Target'])
            # Add data label
            plt.text(bar1[0].get_x() + bar1[0].get_width() / 2., bar1[0].get_height(),
                     f'{next_year_co2_reduction_target}%', ha='center', va='bottom')
            st.pyplot(fig_target_co2)

        # Visualizing "77. Percentage of emission reduction goal achieved last year:"
        with col2:
            st.header("Achieved Emission Reduction Last Year")
            st.write(f"**Achieved Percentage:** {last_year_emission_reduction_achieved}%")
            st.write("This indicates the proportion of the company's achieved emission reduction goal from last year.")
            fig_achieved_last_year = plt.figure(figsize=(6, 4))
            bar2 = plt.bar("Achieved Last Year", last_year_emission_reduction_achieved, color='lightgreen')
            plt.xlabel('Achieved')
            plt.ylabel('Percentage')
            plt.title('Achieved Emission Reduction Last Year')
            plt.legend([bar2], ['Achieved Last Year'])
            # Add data label
            plt.text(bar2[0].get_x() + bar2[0].get_width() / 2., bar2[0].get_height(),
                     f'{last_year_emission_reduction_achieved}%', ha='center', va='bottom')
            st.pyplot(fig_achieved_last_year)

    def visualize_emission_reduction_responses(all_answers):
        # Visualize Count of 'Yes' and 'No' Responses for Emission Reduction Initiatives
        st.header("Emission Reduction Initiatives")
        st.write("**Yes/No Responses Overview:**")
        st.write("This chart shows the count of 'Yes' and 'No' responses to questions about emission reduction initiatives. A higher count of 'Yes' responses indicates proactive engagement in emission reduction strategies.")

        # Emission reduction-related questions
        emission_reduction_questions = [
            "65. Do you monitor CO2 emissions in your logistics operations?",
            "66. Do you have emissions reduction targets in place for your logistics operations?",
            "67. Percentage reduction target for CO2 emissions in the next year:",
            "68. Are measures in place to reduce NOx and SOx emissions in your transportation equipment or facilities?",
            "69. Do you have initiatives to minimize particulate matter emissions?",
            "70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?",
            "71. Do you manage emissions from refrigerated cargo containers?",
            "72. Do you have strategies to reduce emissions from idling vehicles and equipment?",
            "73. Do you employ emission-reducing practices in your facility’s lighting, heating, and cooling systems?",
            "74. Are renewable energy sources used to power your logistics facilities?",
            "75. How do you manage emissions from equipment maintenance and repair activities?",
            "76. Do you have specific percentage goals for emission reduction in logistics operations?",
            "77. Percentage of emission reduction goal achieved last year:",
            "78. Are emission reduction efforts audited or assessed regularly?",
            "79. Are there plans for future emission reduction initiatives in logistics?",
            "80. Do you participate in any carbon offset programs?",
            "81. Is there a system for tracking and reporting emissions data?",
            "82. Do you engage in partnerships or collaborations for emission reduction initiatives?",
            "83. Do you provide training or awareness programs on emission reduction for employees?",
            "84. Are emission reduction initiatives integrated into your overall business strategy?"
        ]

        # Counting 'Yes' and 'No' responses
        yes_count_emission = sum(1 for question in emission_reduction_questions if all_answers.get(question, "No") == 'Yes')
        no_count_emission = len(emission_reduction_questions) - yes_count_emission

        # Creating a horizontal bar chart
        fig_emission = plt.figure(figsize=(8, 6))
        plt.barh(['Yes', 'No'], [yes_count_emission, no_count_emission], color=['green', 'red'])
        plt.xlabel('Count')
        plt.title('Count of "Yes" and "No" Responses for Emission Reduction Initiatives')
        # Adding data labels to the bars
        for index, value in enumerate([yes_count_emission, no_count_emission]):
            plt.text(value, index, f'{value}', ha='right', va='center')
        st.pyplot(fig_emission)


    def calculate_emission_score(all_answers):
        score = 0
        max_possible_score = 0

        # Scoring for Yes/No questions (5 points for each 'Yes')
        yes_no_questions = [
            "65. Do you monitor CO2 emissions in your logistics operations?",
            "66. Do you have emissions reduction targets in place for your logistics operations?",
            "68. Are measures in place to reduce NOx and SOx emissions in your transportation equipment or facilities?",
            "69. Do you have initiatives to minimize particulate matter emissions?",
            "70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?",
            "71. Do you manage emissions from refrigerated cargo containers?",
            "72. Do you have strategies to reduce emissions from idling vehicles and equipment?",
            "73. Do you employ emission-reducing practices in your facility’s lighting, heating, and cooling systems?",
            "74. Are renewable energy sources used to power your logistics facilities?",
            "75. How do you manage emissions from equipment maintenance and repair activities?",
            "76. Do you have specific percentage goals for emission reduction in logistics operations?",
            "78. Are emission reduction efforts audited or assessed regularly?",
            "79. Are there plans for future emission reduction initiatives in logistics?",
            "80. Do you participate in any carbon offset programs?",
            "81. Is there a system for tracking and reporting emissions data?",
            "82. Do you engage in partnerships or collaborations for emission reduction initiatives?",
            "83. Do you provide training or awareness programs on emission reduction for employees?",
            "84. Are emission reduction initiatives integrated into your overall business strategy?"
        ]

        for question in yes_no_questions:
            response = all_answers.get(question, "No").lower()
            if response == 'yes':
                score += 5
            max_possible_score += 5

        # Scoring for quantitative questions
        emission_reduction_goal = all_answers.get("67. Percentage reduction target for CO2 emissions in the next year:", 0)
        emission_reduction_achieved = all_answers.get("77. Percentage of emission reduction goal achieved last year:", 0)

        # Adding up to 10 points for each of the percentage-based questions based on their value
        score += min(10, int(emission_reduction_goal / 10))
        score += min(10, int(emission_reduction_achieved / 10))
        max_possible_score += 20

        # Ensure score is within 0-100 range and calculate the percentage score
        score = max(0, min(score, max_possible_score))
        percentage_score = (score / max_possible_score) * 100

        return percentage_score

    def visualize_emission_score(all_answers):
        # Calculate the emission reduction score
        emission_score = calculate_emission_score(all_answers)

        # Scoring components for visualization
        components = {
            'CO2 Emissions Monitoring': 5 if all_answers.get("65. Do you monitor CO2 emissions in your logistics operations?", "No") == "Yes" else 0,
            'Emission Reduction Targets': 5 if all_answers.get("66. Do you have emissions reduction targets in place for your logistics operations?", "No") == "Yes" else 0,
            'NOx and SOx Reduction Measures': 5 if all_answers.get("68. Are measures in place to reduce NOx and SOx emissions in your transportation equipment or facilities?", "No") == "Yes" else 0,
            'Particulate Matter Emission Initiatives': 5 if all_answers.get("69. Do you have initiatives to minimize particulate matter emissions?", "No") == "Yes" else 0,
            'Fuel-Efficient Technologies Adoption': 5 if all_answers.get("70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?", "No") == "Yes" else 0,
            'Management of Emissions from Refrigerated Cargo Containers': 5 if all_answers.get("71. Do you manage emissions from refrigerated cargo containers?", "No") == "Yes" else 0,
            'Strategies to Reduce Emissions from Idling Vehicles and Equipment': 5 if all_answers.get("72. Do you have strategies to reduce emissions from idling vehicles and equipment?", "No") == "Yes" else 0,
            'Emission-Reducing Practices in Lighting, Heating, and Cooling Systems': 5 if all_answers.get("73. Do you employ emission-reducing practices in your facility’s lighting, heating, and cooling systems?", "No") == "Yes" else 0,
            'Use of Renewable Energy Sources': 5 if all_answers.get("74. Are renewable energy sources used to power your logistics facilities?", "No") == "Yes" else 0,
            'Management of Emissions from Equipment Maintenance and Repair Activities': 5 if all_answers.get("75. How do you manage emissions from equipment maintenance and repair activities?", "No") == "Yes" else 0,
            'Specific Percentage Goals for Emission Reduction': 5 if all_answers.get("76. Do you have specific percentage goals for emission reduction in logistics operations?", "No") == "Yes" else 0,
            'Regular Audits or Assessments for Emission Reduction Efforts': 5 if all_answers.get("78. Are emission reduction efforts audited or assessed regularly?", "No") == "Yes" else 0,
            'Plans for Future Emission Reduction Initiatives': 5 if all_answers.get("79. Are there plans for future emission reduction initiatives in logistics?", "No") == "Yes" else 0,
            'Participation in Carbon Offset Programs': 5 if all_answers.get("80. Do you participate in any carbon offset programs?", "No") == "Yes" else 0,
            'System for Tracking and Reporting Emissions Data': 5 if all_answers.get("81. Is there a system for tracking and reporting emissions data?", "No") == "Yes" else 0,
            'Engagement in Partnerships or Collaborations for Emission Reduction Initiatives': 5 if all_answers.get("82. Do you engage in partnerships or collaborations for emission reduction initiatives?", "No") == "Yes" else 0,
            'Training or Awareness Programs on Emission Reduction for Employees': 5 if all_answers.get("83. Do you provide training or awareness programs on emission reduction for employees?", "No") == "Yes" else 0,
            'Integration of Emission Reduction Initiatives into Business Strategy': 5 if all_answers.get("84. Are emission reduction initiatives integrated into your overall business strategy?", "No") == "Yes" else 0,

            # Percentage-based components
            'Reduction Target for CO2 Emissions': min(10, int(all_answers.get("67. Percentage reduction target for CO2 emissions in the next year:", 0) / 10)),
            'Percentage of Goal Achieved Last Year': min(10, int(all_answers.get("77. Percentage of emission reduction goal achieved last year:", 0) / 10))
        }

        component_names = list(components.keys())
        component_scores = list(components.values())

        # Split the scores into positive and negative scores for the stacked bar chart
        positive_scores = [score if score > 0 else 0 for score in component_scores]
        negative_scores = [score if score < 0 else 0 for score in component_scores]

        # Create a stacked bar chart
        fig, ax = plt.subplots(figsize=(10, 8))
        ax.barh(component_names, positive_scores, color='skyblue', label='Positive Scores')
        ax.barh(component_names, negative_scores, color='salmon', label='Negative Scores')

        # Add emission score as text to the right of the bar
        for i, (pos_score, neg_score) in enumerate(zip(positive_scores, negative_scores)):
            total_score = pos_score + neg_score
            ax.text(max(total_score, 0) + 0.2, i,
                    f'{total_score:.1f}',
                    va='center', fontsize=10, fontweight='bold', color='grey')

        # Set labels and title
        ax.set_xlabel('Scores')
        ax.set_title(f'Emission Reduction Score: {emission_score:.1f}%')
        ax.legend()

        # Adjust layout
        plt.tight_layout()

        return fig


    explanation_E_metric = """
    The Emission Score reflects the commitment to reducing environmental emissions associated with logistics operations. It encompasses various factors that contribute to sustainable practices and emission reduction initiatives. Here's a detailed breakdown of how the Emission Score is composed:

    - **CO2 Emissions Monitoring:** Monitoring CO2 emissions in logistics operations positively impacts the score by indicating a commitment to tracking environmental impact.
    - **Emission Reduction Targets:** Having established targets for reducing emissions within logistics operations contributes positively to the score.
    - **NOx and SOx Reduction Measures:** Implementing measures to reduce NOx and SOx emissions in transportation equipment or facilities adds points to the score.
    - **Particulate Matter Emission Initiatives:** Initiatives aimed at minimizing particulate matter emissions contribute positively to the score.
    - **Fuel-Efficient Technologies Adoption:** Adoption of fuel-efficient technologies or alternative fuels within the logistics fleet impacts the score positively.
    - **Management of Emissions from Refrigerated Cargo Containers:** Efficiently managing emissions from refrigerated cargo containers adds to the score.
    - **Strategies to Reduce Emissions from Idling Vehicles and Equipment:** Having strategies in place to reduce emissions from idling vehicles and equipment positively impacts the score.
    - **Emission-Reducing Practices in Lighting, Heating, and Cooling Systems:** Employing emission-reducing practices in facility lighting, heating, and cooling systems contributes to a higher score.
    - **Use of Renewable Energy Sources:** Utilizing renewable energy sources to power logistics facilities adds points to the score.
    - **Management of Emissions from Equipment Maintenance and Repair Activities:** Efficiently managing emissions from equipment maintenance and repair activities impacts the score positively.
    - **Specific Percentage Goals for Emission Reduction:** Setting specific percentage goals for emission reduction within logistics operations adds to the score.
    - **Regular Audits or Assessments for Emission Reduction Efforts:** Regularly auditing or assessing emission reduction efforts contributes positively to the score.
    - **Plans for Future Emission Reduction Initiatives:** Having plans for future emission reduction initiatives within logistics operations adds points to the score.
    - **Participation in Carbon Offset Programs:** Actively participating in carbon offset programs impacts the score positively.
    - **System for Tracking and Reporting Emissions Data:** Implementing a system for tracking and reporting emissions data positively affects the score.
    - **Engagement in Partnerships or Collaborations for Emission Reduction Initiatives:** Engaging in partnerships or collaborations for emission reduction positively impacts the score.
    - **Training or Awareness Programs on Emission Reduction for Employees:** Providing training or awareness programs on emission reduction for employees adds points to the score.
    - **Integration of Emission Reduction Initiatives into Business Strategy:** Integrating emission reduction initiatives into the overall business strategy contributes positively to the score.
    - **Reduction Target for CO2 Emissions:** Setting targets for reducing CO2 emissions in the upcoming year adds to the score.
    - **Percentage of Goal Achieved Last Year:** The percentage of achieved emission reduction goals from the previous year impacts the score positively.

    A higher Emission Score reflects a stronger dedication to minimizing environmental emissions, implementing sustainable practices, and achieving emission reduction goals within logistics operations.

    """

    def evaluate_emission_sustainability_practice(score, df):
        # Counting 'Yes' responses for emission-related Yes/No questions
        emission_yes_no_questions = [
            question[0] for question in sections["Emission Reduction Initiatives"] if question[1] == 'radio'
        ]
        yes_count = sum(
            df[question].eq('Yes').sum() for question in emission_yes_no_questions if question in df.columns
        )
        yes_percentage = (yes_count / len(emission_yes_no_questions)) * 100 if emission_yes_no_questions else 0

        # Calculate a combined emission sustainability index
        combined_index = (0.6 * score) + (0.4 * yes_percentage)

        # Grading system with detailed advice for emission sustainability
        if combined_index >= 80:
            grade = "A (Eco-Champion 🌍)"
            st.image("Eco-Champion.png")
            explanation = "You demonstrate exemplary emission reduction practices, setting a high benchmark in sustainability."
            advice = "Continue leading and innovating in emission reduction, and share your successful practices with others."
        elif combined_index >= 60:
            grade = "B (Sustainability Steward πŸƒ)"
            st.image("Sustainability_Steward.png", use_column_width=True)
            explanation = "Your efforts in emission reduction reflect a strong commitment to sustainability."
            advice = "Keep improving your strategies for reducing emissions and explore new technologies for further reduction."
        elif combined_index >= 40:
            grade = "C (Eco-Advancer 🌿)"
            st.image("Eco-Advancer.png")
            explanation = "You're actively working towards better emission reduction but have room to grow."
            advice = "Enhance your emission reduction initiatives and consider partnerships or collaborations for wider impact."
        elif combined_index >= 20:
            grade = "D (Green Learner 🌼)"
            st.image("Green_Learner.png")
            explanation = "You've started to engage in sustainable emission reduction practices, but there's much to develop."
            advice = "Focus on establishing specific emission reduction goals and educate your team about their importance and implementation."
        else:
            grade = "E (Eco-Novice 🌱)"
            st.image("Eco-Novice.png", use_column_width=True)
            explanation = "You are at the early stages of adopting sustainable emission reduction practices."
            advice = "Begin by monitoring emissions, setting targets, and implementing basic strategies to reduce emissions."

        # Expanded advice on satisfying emission requirements
        advice += "\n\n**Advice on Satisfying Emission Requirements:**"
        advice += "\n- Ensure rigorous monitoring of emissions across all operations."
        advice += "\n- Set ambitious yet achievable targets for reducing emissions."
        advice += "\n- Implement measures to reduce various types of emissions, including CO2, NOx, SOx, and particulate matter."
        advice += "\n- Consider the adoption of fuel-efficient technologies and alternative fuels."
        advice += "\n- Regularly assess and audit emission reduction efforts to ensure effectiveness."
        advice += "\n- Establish strategies to engage in carbon offset programs or support renewable energy sources."
        advice += "\n- Integrate emission reduction initiatives into your overall business strategy for holistic impact."

        return f"**Sustainability Grade: {grade}** \n\n**Explanation:** \n{explanation} \n\n**Detailed Advice:** \n{advice}"

    def generate_swot_analysis(company_data):
       # Extracting relevant data from company_data
       logistics_sustainability_level = company_data.get("Logistics Sustainability Level", "None")
       annual_carbon_emissions = company_data.get("Annual Carbon Emissions (in metric tons)", 0)
       utilize_renewable_energy = company_data.get("Utilize Renewable Energy Sources", False)
       selected_certifications = company_data.get("Selected Logistics Certifications and Initiatives", [])
       company_summary = company_data.get("Company Summary", "No specific information provided.")

       # Constructing a dynamic SWOT analysis based on extracted data
       strengths = [
           "Utilization of Renewable Energy Sources" if utilize_renewable_energy else "None"
       ]

       weaknesses = [
           "Lack of Logistics Sustainability Level: " + logistics_sustainability_level,
           "Zero Annual Carbon Emissions" if annual_carbon_emissions == 0 else "Annual Carbon Emissions Present",
           "Company Summary: " + company_summary
       ]

       opportunities = [
           "Exploration of Logistics Certifications" if not selected_certifications else "None"
       ]

       threats = [
           "Competitive Disadvantage Due to Lack of Certifications" if not selected_certifications else "None"
       ]

       # Constructing a SWOT analysis prompt dynamically
       swot_analysis_prompt = f"""
       Strengths, Weaknesses, Opportunities, Threats (SWOT) Analysis:

       Strengths:
       Strengths Analysis:
       {", ".join(strengths)}

       Weaknesses:
       Weaknesses Analysis:
       {", ".join(weaknesses)}

       Opportunities:
       Opportunities Analysis:
       {", ".join(opportunities)}

       Threats:
       Threats Analysis:
       {", ".join(threats)}
       """

       # OpenAI API call for SWOT analysis
       response_swot = openai.ChatCompletion.create(
           model="gpt-3.5-turbo",
           messages=[
               {"role": "assistant", "content": "You are analyzing the company's sustainability practices."},
               {"role": "system", "content": "Conduct a SWOT analysis based on the provided company data."},
               {"role": "user", "content": swot_analysis_prompt}
           ],
           max_tokens=1000,
           temperature=0.5,
           top_p=1.0,
           frequency_penalty=0.5,
           presence_penalty=0.0
       )

       # Extracting the SWOT analysis content from the response
       swot_analysis_content = response_swot.choices[0].message['content']

       return swot_analysis_content

    def evaluate_emission_sustainability_report(all_answers, score):
        """Generates an Emission Sustainability report based on responses to a questionnaire."""
        extracted_data = extract_data(all_answers)

        # Consolidate data for emission sustainability
        co2_emissions_monitoring = extracted_data.get("65. Do you monitor CO2 emissions in your logistics operations?", "N/A")
        emission_reduction_targets = extracted_data.get("66. Do you have emissions reduction targets in place for your logistics operations?", "N/A")
        nox_sox_reduction_measures = extracted_data.get("68. Are measures in place to reduce NOx and SOx emissions in your transportation equipment or facilities?", "N/A")
        particulate_matter_emission_initiatives = extracted_data.get("69. Do you have initiatives to minimize particulate matter emissions?", "N/A")
        fuel_efficient_technologies = extracted_data.get("70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?", "N/A")
        # ... include more emissions-related data as needed ...

        emission_report = f"""
        Emission Sustainability Report
        Score: {score}/100
        Report Details:
        CO2 Emissions Monitoring: {co2_emissions_monitoring}
        Emission Reduction Targets: {emission_reduction_targets}
        NOx and SOx Reduction Measures: {nox_sox_reduction_measures}
        Particulate Matter Emission Initiatives: {particulate_matter_emission_initiatives}
        Fuel-Efficient Technologies Adoption: {fuel_efficient_technologies}
        Manage Emissions from Refrigerated Cargo Containers: {extracted_data.get("71. Do you manage emissions from refrigerated cargo containers?", "N/A")}
        Emission-Reducing Practices in Lighting, Heating, and Cooling Systems: {extracted_data.get("73. Do you employ emission-reducing practices in your facility’s lighting, heating, and cooling systems?", "N/A")}
        Use of Renewable Energy Sources to Power Logistics Facilities: {extracted_data.get("74. Are renewable energy sources used to power your logistics facilities?", "N/A")}
        Specific Percentage Goals for Emission Reduction in Logistics Operations: {extracted_data.get("76. Do you have specific percentage goals for emission reduction in logistics operations?", "N/A")}
        Percentage of Emission Reduction Goal Achieved Last Year: {extracted_data.get("77. Percentage of emission reduction goal achieved last year:", 0)}
        Regular Audits or Assessments for Emission Reduction Efforts: {extracted_data.get("78. Are emission reduction efforts audited or assessed regularly?", "N/A")}
        Plans for Future Emission Reduction Initiatives in Logistics: {extracted_data.get("79. Are there plans for future emission reduction initiatives in logistics?", "N/A")}
        Participation in Carbon Offset Programs: {extracted_data.get("80. Do you participate in any carbon offset programs?", "N/A")}
        System for Tracking and Reporting Emissions Data: {extracted_data.get("81. Is there a system for tracking and reporting emissions data?", "N/A")}
        """

        # Include further analysis via OpenAI API
        prompt = f"""
        As an emission sustainability advisor, analyze the Emission Sustainability Report with a score of {score}/100. Review the provided data points and offer a detailed analysis. Identify strengths, weaknesses, and areas for improvement in emission reduction practices. Provide specific recommendations to enhance emission sustainability considering the current emission reduction strategies and initiatives.

        Data Points:
        {emission_report}
        """

        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo-16k",
                messages=[
                    {"role": "system", "content": "Analyze the data and provide comprehensive insights and recommendations."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=3000,
                temperature=0.7,
                top_p=1.0,
                frequency_penalty=0,
                presence_penalty=0
            )

            evaluation_content = response.choices[0].message['content']

            refined_report = f"{emission_report}\n\n{evaluation_content}"
            return refined_report

        except Exception as e:
            return f"Error: {e}"

    # Function to format answer for better readability
    def format_answer(answer):
        if isinstance(answer, bool):
            return "Yes" if answer else "No"
        elif isinstance(answer, (int, float)):
            return str(answer)
        return answer  # Assume the answer is already in a string format

    # Function to extract and format data from a dictionary
    def extract_data(data):
        formatted_data = {}
        for key, value in data.items():
            formatted_data[key] = format_answer(value)
        return formatted_data

    #report = evaluate_emission_sustainability_report(all_answers, score)

    #st.write(report)

    #Manage Emissions from Refrigerated Cargo Containers: {extracted_data.get("71. Do you manage emissions from refrigerated cargo containers?", "N/A")}
    #- Strategies to Reduce Emissions from Idling Vehicles and Equipment: {extracted_data.get("72. Do you have strategies to reduce emissions from idling vehicles and equipment?", "N/A")}
    #- Emission-Reducing Practices in Lighting, Heating, and Cooling Systems: {extracted_data.get("73. Do you employ emission-reducing practices in your facility’s lighting, heating, and cooling systems?", "N/A")}
    #- Use of Renewable Energy Sources to Power Logistics Facilities: {extracted_data.get("74. Are renewable energy sources used to power your logistics facilities?", "N/A")}
    #- Participation in Carbon Offset Programs: {extracted_data.get("80. Do you participate in any carbon offset programs?", "N/A")}
    #- System for Tracking and Reporting Emissions Data: {extracted_data.get("81. Is there a system for tracking and reporting emissions data?", "N/A")}
    #- Engagement in Partnerships or Collaborations for Emission Reduction Initiatives: {extracted_data.get("82. Do you engage in partnerships or collaborations for emission reduction initiatives?", "N/A")}

    def get_emission_sustainability_strategy(all_answers, company_data):
        # Extracting and formatting data from all_answers and company_data
        extracted_all_answers = extract_data(all_answers)
        extracted_company_data = extract_data(company_data)

        # Forming the prompt with extracted data for emission sustainability
        prompt = f"""
        Based on the provided company and emission sustainability assessment data, provide an emission sustainability strategy:

        **Company Info**:
        - Logistics Sustainability Level: {extracted_company_data.get('Logistics Sustainability Level', 'N/A')}
        - Annual Carbon Emissions: {extracted_company_data.get('Annual Carbon Emissions (in metric tons)', 'N/A')} metric tons
        - Utilize Renewable Energy Sources: {extracted_company_data.get('Utilize Renewable Energy Sources', 'No')}
        - Certifications: {extracted_company_data.get('Selected Logistics Certifications and Initiatives', 'N/A')}
        - Company Summary: {extracted_company_data.get('Company Summary', 'N/A')}

        **Emission Sustainability Assessment Data**:
        - CO2 Emissions Monitoring: {extracted_all_answers.get("65. Do you monitor CO2 emissions in your logistics operations?", "N/A")}
        - Emission Reduction Targets: {extracted_all_answers.get("66. Do you have emissions reduction targets in place for your logistics operations?", "N/A")}
        - Particulate Matter Emission Initiatives: {extracted_all_answers.get("69. Do you have initiatives to minimize particulate matter emissions?", "N/A")}
        - Fuel-Efficient Technologies Adoption: {extracted_all_answers.get("70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?", "N/A")}
        - Training or Awareness Programs on Emission Reduction for Employees: {extracted_all_answers.get("83. Do you provide training or awareness programs on emission reduction for employees?", "N/A")}
        - Integration of Emission Reduction Initiatives into Overall Business Strategy: {extracted_all_answers.get("84. Are emission reduction initiatives integrated into your overall business strategy?", "N/A")}


        Offer an actionable strategy considering the company's specific context and emission sustainability data.
        """

        additional_context = f"Provide a detailed emission sustainability strategy using context data from the above company info and in responses to the emission sustainability assessment."
        # Assuming you have an API call here to generate a response based on the prompt
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-16k",
            messages=[
                {"role": "assistant", "content": "You are an emission sustainability strategy advisor."},
                {"role": "user", "content": prompt},
                {"role": "user", "content": additional_context}
            ],
            max_tokens=3000,
            temperature=0.7,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0
        )

        return response.choices[0].message['content']

    #strategy= get_emission_sustainability_strategy(all_answers, company_data)

    #st.write(strategy)

    def get_certification_details(certification_name):
        # Prepare the prompt for the API call
        messages = [
            {"role": "system", "content": "You are a knowledgeable assistant about global certifications."},
            {"role": "user", "content": f"Provide detailed information on how to obtain the {certification_name} certification."}
        ]

        # Query the OpenAI API for information on the certification process
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=messages,
            max_tokens=2000,
            temperature=0.3,
            top_p=1.0,
            frequency_penalty=0.5,
            presence_penalty=0.0
        )

        # Return the content of the response
        return response.choices[0].message['content']


    def advise_on_emission_sustainability_certification(company_data):
        # Check if company_data is a dictionary
        if not isinstance(company_data, dict):
            raise ValueError("company_data must be a dictionary")

        # Extract company data relevant to emission sustainability certifications
        co2_emissions_monitoring = company_data.get('Do you monitor CO2 emissions?', False)
        emission_reduction_targets = company_data.get('Have emissions reduction targets?', False)
        nox_sox_reduction_measures = company_data.get('Measures to reduce NOx and SOx emissions?', False)
        particulate_matter_initiatives = company_data.get('Initiatives to minimize particulate matter emissions?', False)
        renewable_energy_sources = company_data.get('Use renewable energy sources?', False)
        emission_management_certifications = company_data.get('Emission management certifications', [])

        # Initialize a string to store recommendations
        recommendations_text = ""

        # Determine which emission sustainability certifications to suggest based on the provided data
        emission_certifications_to_consider = {
            "CO2 Emissions Monitoring Certification": not co2_emissions_monitoring,
            "Emission Reduction Targets Certification": not emission_reduction_targets,
            "NOx and SOx Reduction Measures Certification": not nox_sox_reduction_measures,
            "Particulate Matter Emission Initiatives Certification": not particulate_matter_initiatives,
            "Renewable Energy Sources Certification": not renewable_energy_sources,
            "Advanced Emission Management Certification": "Advanced Emission Management" not in emission_management_certifications
        }

        for certification, consider in emission_certifications_to_consider.items():
            if consider:
                try:
                    certification_details = get_certification_details(certification)
                    recommendations_text += f"\n\nFor {certification}, here's what you need to know: {certification_details}"
                except Exception as e:
                    recommendations_text += f"\n\nError retrieving details for {certification}: {e}"

        # If no emission sustainability certifications are suggested, add a message
        if not recommendations_text.strip():
            recommendations_text = "Based on the provided data, there are no specific emission sustainability certifications recommended at this time."

        # Return the combined recommendations as a single formatted string
        return recommendations_text

    #strategy = advise_on_emission_sustainability_certification(company_data)

    #st.write(strategy)

    if st.button('Submit'):

        try:
           # Use a spinner for generating advice
           with st.spinner("Generating report and advice..."):

               st.subheader("Visualize Emission Data")
               visualize_emission_reduction_responses(all_answers)

               visualize_emission_reduction_data(all_answers)

               st.subheader("Emission Scores")

               score = calculate_emission_score(all_answers)

               # Display formatted score
               st.write(f"**Emission Sustainability Score:**")
               st.markdown(f"**{score:.1f}%**")

               st.subheader("Visualize Emission Scores")
               fig = visualize_emission_score(all_answers)
               #fig = visualize_waste_score(all_answers)
               st.pyplot(fig)

               st.markdown(explanation_E_metric)

               st.subheader("Visualize Sustainability Grade")
               # Call the function with the DataFrame

               st.markdown(evaluate_emission_sustainability_practice(score, answers_df), unsafe_allow_html=True)

               swot_analysis_content = generate_swot_analysis(company_data)
               #st.subheader("Energy Sustainability Strategy")
               st.subheader("Company SWOT Report")
               st.write(swot_analysis_content)

               strategy = get_emission_sustainability_strategy(all_answers, company_data)
               #strategy = get_energy_sustainability_advice(strategy, company_data)
               report = evaluate_emission_sustainability_report(all_answers, score)
               #st.subheader("Energy Sustainability Strategy")
               st.subheader("Emission Sustainability Report")
               st.write(report)
               st.download_button(
                   label="Download Emission Sustainability Report",
                       data=report,
                       file_name='sustainability_report.txt',
                       mime='text/txt',
                       key="download_report_button",  # Unique key for this button
                       )

               st.subheader("Sustainability Strategy")
               st.write(strategy)
               st.download_button(
                   label="Download Emission Sustainability Strategy",
                   data=strategy,
                   file_name='sustainability_strategy.txt',
                   mime='text/txt',
                   key="download_strategy_button",  # Unique key for this button
               )

               st.subheader("Advice on Sustainability Certification")
               #certification_advice = advise_on_transport_sustainability_certification(company_data)
               try:
                   advice = advise_on_emission_sustainability_certification(company_data)
                   st.write(advice)
               except ValueError as e:
                   print(e)

        # Embed a YouTube video after processing
           st.subheader("Watch More on Sustainability")
           video_urls = [
           "https://www.youtube.com/watch?v=RYzcE1OiwRE",
           #"https://www.youtube.com/watch?v=your_video_url_2",
           #"https://www.youtube.com/watch?v=your_video_url_3",
           # Add more video URLs as needed
           ]

           # Select a random video URL from the list
           random_video_url = random.choice(video_urls)

           # Display the random video
           st.video(random_video_url)

        except Exception as e:
           st.error(f"An error occurred: {e}")

        st.write("""
        ---
        *Powered by Streamlit, CarbonInterface API, and OpenAI.*
        """)

def page6():
    st.write("<center><h1>Carbon Footprint Calculator: Measure Your Environmental Impact</h1></center>", unsafe_allow_html=True)
    st.image("page11.1.png", use_column_width=True)
    #st.write("Assess and improve the sustainability of your logistics operations.")
    # Define the API endpoint and your API key
    API_URL = "https://www.carboninterface.com/api/v1/estimates"
    API_KEY = "XXtYmhThBssK41ufq2JJOA"
    # Define headers for the API call
    headers = {
      "Authorization": f"Bearer {API_KEY}",
      "Content-Type": "application/json"
    }

    # Streamlit UI
    #st.title("Carbon Emission Estimate Calculator for Shipping & Logistics")

    # Streamlined Subheader and Descriptions
    st.write("""
    ### Instructions:
    Input the necessary data related to your shipping and logistics operations to get an estimate of your carbon emissions.
    The calculator will provide actionable insights to reduce your carbon footprint based on the data provided.
    """)

    st.title("Carbon Footprint Information Extractor")

    # -- Shipping Routes --
    st.subheader("1. Shipping Routes")
    average_ship_distance = st.number_input("Average Distance Per Shipping Route (km)", min_value=1, value=500)
    most_common_ship_type = st.selectbox("Most Common Ship Type", ["Bulk Carrier", "Container Ship", "Tanker Ship", "Cargo Ship", "Passenger Ship", "Other"])

    # -- Warehousing and Storage --
    st.subheader("2. Warehousing and Storage")
    warehouse_energy_source = st.selectbox("Primary Energy Source", ["Coal", "Natural Gas", "Renewable (Wind/Solar)", "Nuclear", "Other"])
    warehouse_size = st.number_input("Total Warehouse Space (sq.m)", min_value=1, value=5000)
    warehouse_insulation = st.selectbox("Insulation Quality", ["Poor", "Average", "Good", "Excellent"])

    # -- Packaging --
    st.subheader("3. Packaging")
    packaging_material = st.selectbox("Primary Packaging Material", ["Plastic", "Cardboard", "Biodegradable", "Recycled", "Other"])

    # -- Fleet Management --
    st.subheader("4. Fleet Management")
    percentage_electric_vehicles = st.slider("Percentage of Electric Vehicles in Fleet", 0, 100, 10)
    average_age_of_ships = st.slider("Average Age of Ships (years)", 1, 50, 15)

    results = {}  # Initialize an empty dictionary to store results


    # Electricity
    st.subheader("5. Port Operations Electricity Consumption")
    st.write("****")
    electricity_unit = st.selectbox("Unit", ["mwh", "kwh"], key='electricity_unit')
    electricity_value = st.number_input("Value", min_value=0.1, value=42.0, key='electricity_value')
    #country = st.text_input("Country (ISO Code)", "US", key='country')
    country = "US"

    # Vehicle
    st.subheader("6. Vehicular Emissions")
    distance_unit_vehicle = st.selectbox("Distance Unit", ["mi", "km"], key='distance_unit_vehicle')
    distance_value_vehicle = st.number_input("Distance Value", min_value=0.1, value=100.0, key='distance_value_vehicle')
    #vehicle_model_id = st.text_input("Vehicle Model ID (Optional)", key='vehicle_model_id')
    vehicle_model_id = "7268a9b7-17e8-4c8d-acca-57059252afe9"

    # Flight
    st.subheader("7. Flight Emissions")
    passengers = st.number_input("Number of Passengers", min_value=1, value=2, key='passengers')

    # Section 4: Emission Reduction Goals
    st.subheader("8. Emission Reduction Goals")
    reduction_target = st.slider("Select Reduction Target (%)", 0, 100, 10)


    # List of sample IATA Codes
    iata_samples = [
      {
          "departure_airport": "SFO",
          "destination_airport": "YYZ"
      },
      {
          "departure_airport": "YYZ",
          "destination_airport": "SFO"
      }
    ]



    # Dropdown for Departure Airport
    #departure_airport = [sample["departure_airport"] for sample in iata_samples]
    #departure_airport = st.selectbox("Departure Airport (IATA Code)", departure_airport_options, key='departure_airport')
    departure_airport = "SFO"
    destination_airport = "YYZ"
    # Dropdown for Destination Airport
    # Filter destinations based on selected departure airport
    #destination_airport = [sample["destination_airport"] for sample in iata_samples if sample["departure_airport"] == departure_airport]
    #destination_airport = st.selectbox("Destination Airport (IATA Code)", destination_airport_options, key='destination_airport')

      # Simplified CO2 Emission Coefficients (in gCO2 per unit)
    COEFFICIENTS = {
      "diesel": 2640,  # gCO2 per liter
      "gasoline": 2392,  # gCO2 per liter
      "natural_gas": 1870,  # gCO2 per cubic meter
      "electricity": 0,  # gCO2 per kWh (placeholder, actual value varies)
    }

    fuel_source_units = {
      "diesel": ["gallons", "liters", "btu"],
      "gasoline": ["gallons", "liters", "btu"],
      "natural_gas": ["btu", "mcf", "therms"],
      #"electricity": ["kWh", "btu"],
    }

    def calculate_emissions(fuel_type, fuel_unit, fuel_value):
      # Conversion constants to standardize units to liters or cubic meters
      unit_conversion = {
          "gallons": 3.78541,  # 1 gallon to liters
          "mcf": 28.3168,  # 1 mcf to cubic meters
          "therms": 2.83168,  # 1 therm to cubic meters
          "btu": 0.000001  # Placeholder for BTU conversion, actual value depends on fuel type.
      }

      # Specific BTU conversions to liters equivalent for each fuel type
      btu_conversion = {
          "diesel": 0.000065,
          "gasoline": 0.000074,
          "natural_gas": 0.000036,  # Approximated value for natural gas
      }

      # Adjust BTU conversion based on fuel type
      if fuel_unit == "btu":
          unit_conversion["btu"] = btu_conversion.get(fuel_type, 0.000001)

      converted_value = fuel_value * unit_conversion.get(fuel_unit, 1)

      return COEFFICIENTS.get(fuel_type, 0) * converted_value

    # User Interface Simplification
    #st.write("**Fuel Combustion CO2 Emissions Calculator**")
    st.subheader("8. Fuel Combustion Emissions")
    # Reduced list of selectable fuel sources
    selected_fuel_sources = st.multiselect("Choose Fuel Source", ["diesel", "gasoline", "natural_gas"], key='fuel_source')

    # Initialize an empty dictionary to store results
    inputs = {}

    total_emissions = 0

    for fuel_source in selected_fuel_sources:
      st.write(f"### {fuel_source} Emissions")

      # Set the unit options based on the selected fuel source
      fuel_source_unit = st.selectbox(f"Unit of {fuel_source}", fuel_source_units[fuel_source], key=f'unit_{fuel_source}')

      # Input for fuel quantity
      fuel_source_value = st.number_input(f"Amount of {fuel_source}", min_value=0.1, value=2.0, step=0.1, key=f'value_{fuel_source}')

      # Calculate and display the emissions
      emission = calculate_emissions(fuel_source, fuel_source_unit, fuel_source_value)
      st.write(f"CO2 emissions for {fuel_source}: {emission:.2f} grams")

      total_emissions += emission


    # Button to trigger the calculations
    if st.button("Calculate Carbon Emission"):
        with st.spinner("Calculating..."):

            #results = {}  # Initialize an empty dictionary to store results

            # Electricity API Call
            payload_electricity = {
              "type": "electricity",
              "electricity_unit": electricity_unit,
              "electricity_value": electricity_value,
              "country": country
            }
            response_electricity = requests.post(API_URL, json=payload_electricity, headers=headers)
            if response_electricity.status_code == 201:
              results["Electricity"] = response_electricity.json().get("data", {}).get("attributes", {})
            else:
              results["Electricity Error"] = f"Error: {response_electricity.status_code} - {response_electricity.text}"

            # Vehicle API Call
            if vehicle_model_id:  # Only make the API call if a vehicle_model_id is provided
              payload_vehicle = {
                  "type": "vehicle",
                  "distance_unit": distance_unit_vehicle,
                  "distance_value": distance_value_vehicle,
                  "vehicle_model_id": vehicle_model_id
                  }
              response_vehicle = requests.post(API_URL, json=payload_vehicle, headers=headers)
              if response_vehicle.status_code == 201:
                  results["Vehicle"] = response_vehicle.json().get("data", {}).get("attributes", {})
              else:
                  results["Vehicle Error"] = f"Error: {response_vehicle.status_code} - {response_vehicle.text}"

              # Flight API Call
            payload_flight = {
              "type": "flight",
              "passengers": passengers,
              "legs": [
                  {"departure_airport": departure_airport, "destination_airport": destination_airport}
                  ]
              }
            response_flight = requests.post(API_URL, json=payload_flight, headers=headers)
            if response_flight.status_code == 201:
              results["Flight"] = response_flight.json().get("data", {}).get("attributes", {})
            else:
              results["Flight Error"] = f"Error: {response_flight.status_code} - {response_flight.text}"

            data_for_df = []
            for key, value in results.items():
              if not key.endswith("_error"):
                  try:
                      data_for_df.append((key, value['carbon_g']))
                  except TypeError:
                      st.error(f"Unexpected value type for key: {key}. Value: {value}")

            st.subheader("Carbon Emission Visual Analysis")
            df = pd.DataFrame(data_for_df, columns=["Segment", "Emissions (g)"])
            st.bar_chart(df.set_index("Segment"), use_container_width=True)
            #pie_chart_data = df.set_index("Segment")
            #st.pyplot(pie_chart_data.plot.pie(y='Emissions (g)', autopct='%1.1f%%', legend=False))
            # Set the index of your dataframe to 'Segment' for the pie chart
            pie_chart_data = df.set_index("Segment")

            # Create a pie chart as a Figure object
            fig, ax = plt.subplots()
            ax.pie(pie_chart_data['Emissions (g)'], labels=pie_chart_data.index, autopct='%1.1f%%')

            # Hide the legend if you don't want it
            ax.legend().set_visible(False)

            # Display the pie chart in Streamlit
            st.pyplot(fig)

            st.subheader("Table of Emission Factors")
            st.table(COEFFICIENTS)

            st.subheader("Emission Reduction Goals Visualization")

            # Use the total calculated emissions as the baseline
            total_emissions = df["Emissions (g)"].sum()

            # Assuming the goal is zero emissions (100% reduction)
            goal_emissions = 0

            # Calculate the emissions after the desired reduction target is applied
            emissions_after_reduction = total_emissions * (1 - (reduction_target / 100))

            # Create a bar chart to compare current and post-reduction emissions
            reduction_data = {
              "Emission Type": ["Current Emissions", "Emissions After Target"],
              "Amount": [total_emissions, emissions_after_reduction]
            }
            df_reduction = pd.DataFrame(reduction_data)
            st.bar_chart(df_reduction.set_index("Emission Type"))

                  # Calculate the current progress
            current_progress = reduction_target / 100

            # Display a label indicating the goal above the progress bar
            st.markdown(f"### Progress Towards Reduction Target ({reduction_target}% goal)")

            # Visualize the progress with a progress bar
            st.progress(current_progress)


            # Textual description of the reduction progress
            st.markdown(f"The reduction target is set to **{reduction_target}%**.")
            st.markdown(f"With current emissions at **{total_emissions} g**, the target after reduction is **{emissions_after_reduction} g**.")
            st.markdown(f"To reach the goal of zero emissions, a further reduction of **{total_emissions - emissions_after_reduction} g** is needed.")

            st.subheader("Emission Reduction Goals Visualization")

            # Constants
            price_per_ton_CO2 = 20  # $20 per ton of CO2
            conversion_factor = 1e6  # 1,000,000 grams in a ton
            transmission_factor = 0.8
            reduction_target = reduction_target  # Example reduction target percentage
            total_emissions = total_emissions  # Example total emissions in grams

            # Assuming two reduction targets: a specific target and 100%
            reduction_targets = set([reduction_target, 100])

            # Lists to store the results
            money_earned_list = []

            # Check if we have two distinct reduction targets
            if len(reduction_targets) != 2:
                raise ValueError("Reduction targets must be two distinct values.")

            reduction_targets_sorted = []

            # Calculate the money earned for each reduction target
            for target in sorted(reduction_targets):
                emissions_after_reduction = total_emissions * (1 - (target / 100))
                emissions_reduced = total_emissions - emissions_after_reduction
                emissions_reduced_in_tons = emissions_reduced / conversion_factor
                money_earned = emissions_reduced_in_tons * price_per_ton_CO2 * transmission_factor
                money_earned_list.append(money_earned)
                reduction_targets_sorted.append(target)

            money_earned_target = money_earned_list[0]  # For the specific reduction target
            money_earned_total = money_earned_list[1]  # For total reduction

            # Create DataFrame for plotting
            data = {"Reduction Target (%)": reduction_targets_sorted, "Money Earned ($)": money_earned_list}
            df_money = pd.DataFrame(data)

            # Using st.markdown to display the dynamic message in a Streamlit app
            # Displaying the assumptions
            st.markdown(f"Assuming a transmission factor of **{transmission_factor}** and a price of **${price_per_ton_CO2}** per ton of CO2,")

            # Displaying the potential gain with the specified reduction target
            st.markdown(f"your company is likely to gain an amount of **${money_earned_target:.2f}** with a **{reduction_target}%** reduction target,")

            # Displaying the potential gain with total carbon reduction
            st.markdown(f"and **${money_earned_total:.2f}** with total carbon reduction.")

            # Displaying the advisory note
            st.markdown("This is an assumption, and you are advised to look into carbon-cash exchange models for more accurate estimations.")

            # Plotting the data
            plt.figure(figsize=(10, 6))
            plt.plot(df_money["Reduction Target (%)"], df_money["Money Earned ($)"], marker='o')
            plt.title("Potential Money Earned by Reducing Carbon Emissions")
            plt.xlabel("Reduction Target (%)")
            plt.ylabel("Money Earned ($)")
            plt.grid(True)
            # Using st.pyplot() to display the plot in Streamlit
            st.pyplot(plt)


            responses = {
              "shipping_routes": {
                  "average_distance": "average_ship_distance",
                  "common_ship_type": "most_common_ship_type",
              },
              "warehousing": {
                  "energy_source": "warehouse_energy_source",
                  "size": "warehouse_size",
                  "insulation": "warehouse_insulation",
              },
              "packaging": {
                  "material": "packaging_material",
              },
              "fleet_management": {
                  "percentage_electric": "percentage_electric_vehicles",
                  "average_age": "average_age_of_ships",
              },
              "vehicular_emissions": {
                  "distance_unit": "distance_unit_vehicle",
                  "distance_value": "distance_value_vehicle",
                  "model_id": "vehicle_model_id",
              },
              "fuel_combustion_emissions": {
                  "selected_fuel_sources": "selected_fuel_sources",
                  "total_emissions": "total_emissions",
              },
              "emission_reduction_goals": {
              # Initialize with empty strings or appropriate placeholders
                  "current_emissions": "",
                  "emissions_after_target": "",
                  "reduction_target": "",
              },
            }

            #- Current total emissions and the goal of reaching zero emissions
            #- Reduction target for emissions
            #- Fuel combustion emissions
            #- Electricity use in port operations
            #- Fleet management practices
            #- Shipping route efficiency

            inputs = {
                "Average Shipping Distance (km)": average_ship_distance,
                "Most Common Ship Type": most_common_ship_type,
                "Primary Warehouse Energy Source": warehouse_energy_source,
                "Total Warehouse Space (sq.m)": warehouse_size,
                "Warehouse Insulation Quality": warehouse_insulation,
                "Primary Packaging Material": packaging_material,
                "Fleet Electric Vehicles (%)": percentage_electric_vehicles,
                "Average Age of Ships (years)": average_age_of_ships,
                "Port Operations Electricity Unit": electricity_unit,
                "Port Operations Electricity Consumption": electricity_value,
                "Vehicle Distance Unit": distance_unit_vehicle,
                "Vehicle Distance Traveled": distance_value_vehicle,
                "Emission Reduction Target (%)": reduction_target,
                "Total Annual Carbon Emissions (grams)": total_emissions
            }
            # Calculate the emissions after the desired reduction target is applied
            emissions_after_reduction = total_emissions * (1 - (reduction_target / 100))

            # Update the inputs dictionary with the new key-value pair
            inputs.update({
                f"Emissions After {reduction_target}% Reduction Target (grams)": emissions_after_reduction
            })

            #st.write(inputs)

            # Formulate the prompt for GPT
            # Constructing the prompt based on input parameters
            report_prompt = f"""
            Detailed Carbon Emission Analysis Report:

            - Total annual emissions: {inputs["Total Annual Carbon Emissions (grams)"]} grams
            - Emission reduction target: {inputs["Emission Reduction Target (%)"]}%
            - Impact of {inputs["Most Common Ship Type"]} and its average age ({inputs["Average Age of Ships (years)"]} years) on fuel combustion emissions.
            - Electricity consumption in port operations: {inputs["Port Operations Electricity Consumption"]} {inputs["Port Operations Electricity Unit"]}
            - Fleet management practices: {inputs["Fleet Electric Vehicles (%)"]} electric vehicles in the fleet.
            - Average shipping distance efficiency: {inputs["Average Shipping Distance (km)"]} km

            Please generate a detailed report analyzing the current carbon emissions scenario, considering the mentioned parameters, and propose recommendations to effectively reduce the organization's carbon footprint in shipping and logistics. The report should encompass comprehensive insights, statistical analysis, and a clear assessment of potential strategies and their impact on carbon reduction. Consider feasibility, cost-effectiveness, and alignment with industry best practices.
            """

            # OpenAI API call for the response
            response = openai.ChatCompletion.create(
              model="gpt-3.5-turbo-16k",
              messages=[
                  {"role": "assistant", "content": "You are a carbon management and reduction strategist."},
                  {"role": "system", "content": "Provide report based on the carbon emission data."},
                  {"role": "user", "content": report_prompt}
              ],
              max_tokens=700,
              temperature=0.5,
              top_p=1.0,
              frequency_penalty=0.5,
              presence_penalty=0.0
            )


            # Constructing a prompt for SWOT analysis based on provided data
            swot_analysis_prompt = f"""
            Strengths, Weaknesses, Opportunities, Threats (SWOT) Analysis:

            Strengths:
            Strengths Analysis:
            The company's carbon activities show several positive attributes:
            1. Efficient Shipping: Utilizing {inputs["Average Shipping Distance (km)"]} km as the average shipping distance showcases efficiency in transportation.
            2. Electric Vehicles: With {inputs["Fleet Electric Vehicles (%)"]} of the fleet being electric, it exhibits a commitment to eco-friendly transportation.
            3. Warehouse Insulation: The warehouse insulation quality, rated as {inputs["Warehouse Insulation Quality"]}, contributes positively to energy conservation.

            Weaknesses:
            Weaknesses Analysis:
            Despite positive aspects, the company's carbon activities display areas needing improvement:
            1. Fuel-Dependent Ships: The average age of ships ({inputs["Average Age of Ships (years)"]} years) and the prevalent ship type ({inputs["Most Common Ship Type"]}) might indicate higher fuel combustion emissions.
            2. Warehouse Energy Source: Dependency on {inputs["Primary Warehouse Energy Source"]} as the primary energy source might contribute to carbon emissions.
            3. Packaging Material Impact: The choice of {inputs["Primary Packaging Material"]} might have environmental implications.

            Opportunities:
            Opportunities Analysis:
            Exploring areas for growth or improvement in the company's carbon activities:
            1. Renewable Energy Adoption: Consider adopting renewable sources like solar or wind power for warehouses.
            2. Fleet Upgrade: Investing in newer, more fuel-efficient ship types can significantly reduce emissions.
            3. Sustainable Packaging: Explore and adopt environmentally friendly packaging alternatives.

            Threats:
            Threats Analysis:
            Identifying potential risks or threats affecting the company's carbon activities:
            1. Regulatory Changes: Anticipate changes in environmental regulations impacting carbon emissions in shipping and logistics.
            2. Rising Energy Costs: Potential increases in electricity prices may impact operational expenses.
            3. Market Shifts: Changes in market dynamics may affect shipping route efficiency or demand.
            """

            # OpenAI API call for SWOT analysis
            response_swot = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "assistant", "content": "You are analyzing the company's carbon activities."},
                    {"role": "system", "content": "Conduct a SWOT analysis based on the provided data."},
                    {"role": "user", "content": swot_analysis_prompt}
                ],
                max_tokens=1000,
                temperature=0.5,
                top_p=1.0,
                frequency_penalty=0.5,
                presence_penalty=0.0
            )




            # Constructing the prompt for the Carbon Reduction Strategy Advisor
            strategy_prompt = f"""
            Carbon Reduction Strategy Advisor:

            Given the specific parameters provided for carbon emissions in the shipping and logistics domain:

            - Total annual emissions: {inputs["Total Annual Carbon Emissions (grams)"]} grams
            - Emission reduction target: {inputs["Emission Reduction Target (%)"]}% reduction target
            - Fuel combustion emissions related to {inputs["Most Common Ship Type"]} with an average age of {inputs["Average Age of Ships (years)"]} years.
            - Electricity use in port operations: {inputs["Port Operations Electricity Consumption"]} {inputs["Port Operations Electricity Unit"]} used in port operations.
            - Fleet management practices: {inputs["Fleet Electric Vehicles (%)"]} of fleet being electric vehicles.
            - Shipping route efficiency: Average shipping distance is {inputs["Average Shipping Distance (km)"]} km.

            The objective is to achieve significant carbon reduction while considering cost-effectiveness and industry best practices.

            Please provide detailed strategies, innovative approaches, and practical steps to significantly reduce carbon emissions in the shipping and logistics operations. Focus on actionable advice, implementation frameworks, and potential challenges to consider when adopting these strategies.
            """

            # OpenAI API call for carbon reduction strategies
            response_strategies = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "assistant", "content": "You are a carbon management and reduction strategist."},
                    {"role": "system", "content": "Provide strategies to achieve significant carbon reduction."},
                    {"role": "user", "content": strategy_prompt}
                ],
                max_tokens=1000,
                temperature=0.5,
                top_p=1.0,
                frequency_penalty=0.5,
                presence_penalty=0.0
            )


        # Display the strategies to the user or use it as needed in your application
        # strategies_content contains the generated strategies for carbon reduction

            swot_result = response_swot.choices[0].message['content']

            # Display the advice to the user
            st.subheader("Carbon Swot Analysis")
            st.write(swot_result)
            st.download_button(
              label="Download SWOT Analysis",
              data=swot_result,
              file_name='SWOT_Anlysis.txt',
              mime='text/txt',
              key="download_SWOT_button",  # Unique key for this button
            )

            # Extracting the advice content from the response
            advice_content = response.choices[0].message['content']

            # Display the advice to the user
            st.subheader("Sustainability Report")
            st.write(advice_content)
            st.download_button(
              label="Download Sustainability advice",
              data=advice_content,
              file_name='sustainability_advice.txt',
              mime='text/txt',
              key="download_advice_button",  # Unique key for this button
            )

            # Extracting the strategies content from the response
            strategies_content = response_strategies.choices[0].message['content']

            # Display the advice to the user
            st.subheader("Carbon Reduction Strategy")
            st.write(strategies_content)
            st.download_button(
              label="Download Sustainability strategy",
              data=strategies_content,
              file_name='sustainability_strategy.txt',
              mime='text/txt',
              key="download_strategy_button",  # Unique key for this button
            )


    # Display a disclaimer message
    st.warning("Disclaimer: The carbon emission calculations provided here are based on certain assumptions and data sources. While we strive to provide accurate estimates, please be aware that the results should be considered as approximate. For the most accurate carbon emissions assessment, we recommend testing with globally accepted values and results.")

    st.write("""
    ---
    *Powered by Streamlit, CarbonInterface API, and OpenAI.*
    """)


def page7():
    # Load and set OpenAI API key from file
    os.environ["OPENAI_API_KEY"] = open("key.txt", "r").read().strip("\n")

    # Define the DB_DIR variable at the top of your script, so it's available in the scope of the function
    DB_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "db")

    # Make sure the directory exists, create if it does not
    os.makedirs(DB_DIR, exist_ok=True)

    # Function to process and store data once
    #@st.cache_data()
    def process_and_store_data(url):
        # Initialize loader and load data from the URL
        loader = WebBaseLoader(url)
        data = loader.load()

        # Initialize text splitter and split documents
        text_splitter = CharacterTextSplitter(separator='\n', chunk_size=900, chunk_overlap=50)
        docs = text_splitter.split_documents(data)

        # Initialize OpenAI embeddings
        openai_embeddings = OpenAIEmbeddings()

        # Create or load Chroma vector database
        vectordb = Chroma.from_documents(documents=docs, embedding=openai_embeddings, persist_directory=DB_DIR)
        vectordb.persist()

        # Return the retriever for later use
        return vectordb.as_retriever(search_kwargs={"k": 3})

    # Main function to define the Streamlit application
    st.write("<center><h1>🚒 EcoPorts: Navigating Towards Sustainable Seaports 🌱</h1></center>", unsafe_allow_html=True)

    st.title('')

    st.image("page12.1.png", use_column_width=True)

    st.subheader('Embark on a Voyage of Discovery in Port Sustainability')

    st.write(
        """
        Welcome to **EcoPorts**, your guide to sustainable practices in the world's seaports.

        As critical hubs for global trade, ports play a key role but also pose environmental challenges. From pollution to ecosystem disruptions, the impact is significant. 🏭🌊

        Seaports are now charting a course towards sustainability, adopting eco-friendly practices to protect our planet. πŸŒŽπŸƒ Dive into an exploration of port sustainability initiatives, ask questions, and discover how ports are becoming greener. Join us on a journey to sustainable port operations! πŸš’πŸ’š
        """
    )

        # Define a list of websites to choose from
    websites = {
        "Blue Economy Observatory News": "https://blue-economy-observatory.ec.europa.eu/news/antwerp-bruges-aims-become-worlds-greenest-port-2023-03-10_en",
        "Euronews Green": "https://www.euronews.com/green/2023/02/28/port-behind-10-of-belgiums-co2-emissions-adopts-carbon-slashing-tech",
        "Sustainable World Ports": "https://sustainableworldports.org/",
        "Port of Gothenburg Green Connection": "https://www.portofgothenburg.com/green-connection/",
        "Ship Technology Green Team Ports": "https://www.ship-technology.com/features/green-team-ports-leading-shipping-sustainability-drive/",
        "AD Ports Group Sustainability": "https://www.adportsgroup.com/en/sustainability",
        "World Shipping Council": "https://www.worldshipping.org/",
        "International Association of Ports and Harbors": "https://www.iaphworldports.org/",
        "GLA Family": "https://www.glafamily.com/",
        "Strategia e Sviluppo": "https://strategiaesviluppo.com/supply-chain-sustainability"
    }

    sustainability_questions = [
        "What initiatives are in place to reduce carbon emissions in ports?",
        "How are ports minimizing their environmental impact?",
        "What actions are taken to protect local ecosystems?",
        "How do ports manage waste and recycling?",
        "What strategies are employed to improve energy efficiency in ports?",
        "How do ports engage in community outreach and partnerships?",
        "What measures are taken to ensure social responsibility in ports?",
        "How are ports contributing to economic development in their communities?",
        "What investments are being made in renewable energy sources in ports?",
        "How are ports ensuring the well-being of future generations?",
        "How do ports align their operations with the United Nations' Sustainable Development Goals (SDGs)?",
        "What technologies are being adopted to promote sustainability in ports?",
        "How do ports manage water resources responsibly?",
        "What practices are implemented to promote sustainable supply chain practices in ports?",
        "How do ports mitigate the impact of operations on local wildlife and habitats?",
        "How is technology being utilized to enhance sustainable operations in ports?",
        "What role do ports play in reducing the carbon footprint of the shipping industry?",
        "How do ports safeguard marine life and biodiversity?",
        "What is the impact of port operations on air quality, and how is it being mitigated?",
        "How do ports plan to adapt to the challenges posed by climate change?",
        "What initiatives are in place to promote green transportation within and around ports?",
        "How are ports addressing noise pollution?",
        "What measures are in place to handle hazardous materials safely and sustainably?",
        "How are ports working towards reducing water pollution?",
        "What collaborations or partnerships are ports forming to enhance sustainability?",
        "How do ports facilitate and manage clean energy transition for vessels?",
        "What are the strategies adopted by ports to ensure economic sustainability?",
        "How are ports ensuring secure, transparent, and sustainable supply chains?",
        "What frameworks are used to measure and report sustainability in ports?",
        "How is sustainability integrated into the decision-making and operational processes of ports?",
        "What is the role of port authorities in ensuring sustainability within port precincts?",
        "What kind of training or awareness programs are in place for sustainability in ports?",
        "How are the local communities involved in sustainability initiatives by ports?",
        "What policies are in place to enhance social sustainability in port operations?",
    ]

        # Select box for choosing a website to query
    selected_website_name = st.selectbox("Select a website", options=list(websites.keys()))
    url = websites[selected_website_name]

    # Load and use the embeddings from the stored data
    retriever = process_and_store_data(url)

    # Input for user's question
    question = st.selectbox("Choose a standard question:", [""] + sustainability_questions)

    if question:
        prompt = question
    else:
        prompt = st.text_input("Or ask your own question:")

        #question = st.text_input("Ask your question about port sustainability:")

        # Process button to handle queries
    if st.button('Submit Query'):
        if question:
            with st.spinner('Fetching and Processing Data...'):
                # Initialize the LLM and retrieval QA chain
                llm = OpenAI(model_name='gpt-3.5-turbo')
                qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever)

                # Get the response using the QA chain
                response = qa(question)

                query = response.get("query")

                result = response.get("result")

                    # Formatting and Displaying the response within the button pressed block
                formatted_response = f"**Question:** {query}\n\n**Answer:** {result}"

                st.markdown(formatted_response)
        else:
            st.warning("Please enter a question to proceed.")

with st.sidebar:
    st.image("Logo.png")
    selected = option_menu(
        menu_title=None,
        options=["🏠 Home","β˜€οΈ Energy Sustainability","πŸš— Sustainable Transportation", "♻️ Waste Assessment",
        "πŸ₯· Trash Ninja","πŸ’¨ Emission Assessment", "πŸ‘£ Carbon Footprint", "πŸ—£οΈπŸŒ EcoPorts Query Engine", "❓About"],
        #icons = [
        #"home", "bus", "bolt", "cube", "ship",
        #"cloud", "trash", "exclamation-triangle",
        #"check-circle", "lightbulb-o", "eye", "paw", "❓"
    #],
        styles=css_style
        )

if selected == "🏠 Home":
    home_page()

elif selected == "β˜€οΈ Energy Sustainability":
    page1()

elif selected == "πŸš— Sustainable Transportation":
    page2()


elif selected == "♻️ Waste Assessment":
    page3()

elif selected == "πŸ₯· Trash Ninja":
    page4()


elif selected == "πŸ’¨ Emission Assessment":
    page5()

elif selected == "πŸ‘£ Carbon Footprint":
    page6()

elif selected == "πŸ—£οΈπŸŒ EcoPorts Query Engine":
    page7()

elif selected == "❓About":
    about_page()