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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
import networkx as nx
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import torch
|
| 7 |
+
from diffusers import StableDiffusionPipeline
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
# 1. Page Configuration
|
| 11 |
+
st.set_page_config(
|
| 12 |
+
page_title="GreenAI - Environmental Intelligence Dashboard",
|
| 13 |
+
layout="wide",
|
| 14 |
+
initial_sidebar_state="expanded"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# Custom CSS for a modern look (optional, but enhances aesthetics)
|
| 18 |
+
st.markdown("""
|
| 19 |
+
<style>
|
| 20 |
+
.stApp {
|
| 21 |
+
background-color: #f0f2f6;
|
| 22 |
+
color: #333333;
|
| 23 |
+
}
|
| 24 |
+
.stTabs [data-baseweb="tab-list"] button [data-testid="stMarkdownContainer"] p {
|
| 25 |
+
font-size: 1.1rem;
|
| 26 |
+
font-weight: bold;
|
| 27 |
+
}
|
| 28 |
+
h1, h2, h3, h4, h5, h6 {
|
| 29 |
+
color: #0068c9;
|
| 30 |
+
}
|
| 31 |
+
.stButton>button {
|
| 32 |
+
background-color: #4CAF50;
|
| 33 |
+
color: white;
|
| 34 |
+
font-size: 1rem;
|
| 35 |
+
padding: 10px 20px;
|
| 36 |
+
border-radius: 8px;
|
| 37 |
+
border: none;
|
| 38 |
+
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
|
| 39 |
+
transition: 0.3s;
|
| 40 |
+
}
|
| 41 |
+
.stButton>button:hover {
|
| 42 |
+
background-color: #45a049;
|
| 43 |
+
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
|
| 44 |
+
}
|
| 45 |
+
.stTextInput>div>div>input {
|
| 46 |
+
border-radius: 8px;
|
| 47 |
+
border: 1px solid #ccc;
|
| 48 |
+
padding: 10px;
|
| 49 |
+
}
|
| 50 |
+
.stTextArea>div>div>textarea {
|
| 51 |
+
border-radius: 8px;
|
| 52 |
+
border: 1px solid #ccc;
|
| 53 |
+
padding: 10px;
|
| 54 |
+
}
|
| 55 |
+
</style>
|
| 56 |
+
""", unsafe_allow_html=True)
|
| 57 |
+
|
| 58 |
+
st.title("π± GreenAI: Smart Environmental AI Assistant")
|
| 59 |
+
st.markdown("Detects pollution types, generates visuals, fills blanks, and maps entities.")
|
| 60 |
+
|
| 61 |
+
# 2. Load models
|
| 62 |
+
@st.cache_resource
|
| 63 |
+
def load_models():
|
| 64 |
+
with st.spinner("π Loading AI models... This might take a moment."):
|
| 65 |
+
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
|
| 66 |
+
ner = pipeline("ner", model="dslim/bert-base-NER", grouped_entities=True)
|
| 67 |
+
fill_mask = pipeline("fill-mask", model="roberta-base")
|
| 68 |
+
|
| 69 |
+
# Stable Diffusion via diffusers
|
| 70 |
+
if torch.cuda.is_available():
|
| 71 |
+
image_gen = StableDiffusionPipeline.from_pretrained(
|
| 72 |
+
"runwayml/stable-diffusion-v1-5",
|
| 73 |
+
torch_dtype=torch.float16,
|
| 74 |
+
).to("cuda")
|
| 75 |
+
else:
|
| 76 |
+
image_gen = StableDiffusionPipeline.from_pretrained(
|
| 77 |
+
"runwayml/stable-diffusion-v1-5"
|
| 78 |
+
).to("cpu")
|
| 79 |
+
st.success("β
All models loaded successfully!")
|
| 80 |
+
return classifier, ner, fill_mask, image_gen
|
| 81 |
+
|
| 82 |
+
classifier, ner, fill_mask, image_gen = load_models()
|
| 83 |
+
|
| 84 |
+
# 3. Define functions
|
| 85 |
+
def classify_text(text):
|
| 86 |
+
labels = ["Waste Management", "Water Management", "Air Pollution", "Recycling", "Energy Conservation"]
|
| 87 |
+
result = classifier(text, candidate_labels=labels)
|
| 88 |
+
return f"**Label:** {result['labels'][0]}, **Score:** {result['scores'][0]:.2f}"
|
| 89 |
+
|
| 90 |
+
def generate_image(prompt):
|
| 91 |
+
# Add a loading spinner for image generation
|
| 92 |
+
with st.spinner("π¨ Generating image... This can take up to a minute."):
|
| 93 |
+
image = image_gen(prompt).images[0]
|
| 94 |
+
return image
|
| 95 |
+
|
| 96 |
+
ENV_TERMS = [
|
| 97 |
+
# Pollution
|
| 98 |
+
"pollution", "air", "water", "soil", "noise", "radiation", "smog", "contamination",
|
| 99 |
+
"runoff", "eutrophication", "emission", "discharge",
|
| 100 |
+
|
| 101 |
+
# Waste
|
| 102 |
+
"waste", "garbage", "litter", "plastic", "microplastic", "sewage", "industrial",
|
| 103 |
+
"landfill", "toxic", "hazardous", "e-waste", "compost", "recyclables",
|
| 104 |
+
|
| 105 |
+
# Natural Resources
|
| 106 |
+
"river", "ocean", "lake", "forest", "biodiversity", "wildlife", "wetland",
|
| 107 |
+
"coral", "marine", "vegetation", "habitat",
|
| 108 |
+
|
| 109 |
+
# Climate
|
| 110 |
+
"climate", "warming", "greenhouse", "carbon", "dioxide", "methane", "ozone",
|
| 111 |
+
"temperature", "drought", "flood", "acid rain", "co2", "ghg",
|
| 112 |
+
|
| 113 |
+
# Sustainability
|
| 114 |
+
"recycle", "reuse", "compost", "conservation", "renewable", "solar", "wind",
|
| 115 |
+
"hydro", "clean energy", "green tech", "sustainable", "biodegradable",
|
| 116 |
+
"energy efficiency", "net zero",
|
| 117 |
+
|
| 118 |
+
# Industrial
|
| 119 |
+
"factory", "industry", "agriculture", "vehicle", "transport", "plant",
|
| 120 |
+
"chemical", "refinery", "pesticide", "fertilizer", "manufacturing"
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
def ner_with_graph(text):
|
| 124 |
+
entities = ner(text)
|
| 125 |
+
G = nx.Graph()
|
| 126 |
+
|
| 127 |
+
seen_words = set()
|
| 128 |
+
|
| 129 |
+
# Add NER entities
|
| 130 |
+
for ent in entities:
|
| 131 |
+
raw_label = ent["entity_group"]
|
| 132 |
+
clean_label = {
|
| 133 |
+
"PER": "Person", "LOC": "Location", "ORG": "Organization", "MISC": "Misc"
|
| 134 |
+
}.get(raw_label, raw_label)
|
| 135 |
+
|
| 136 |
+
word = ent["word"].replace("##", "").strip()
|
| 137 |
+
if word not in seen_words:
|
| 138 |
+
G.add_node(word, label=clean_label)
|
| 139 |
+
seen_words.add(word)
|
| 140 |
+
|
| 141 |
+
# Add environmental terms
|
| 142 |
+
words = text.split()
|
| 143 |
+
for word in words:
|
| 144 |
+
clean_word = word.lower().strip(",.")
|
| 145 |
+
if clean_word in ENV_TERMS:
|
| 146 |
+
if word not in seen_words:
|
| 147 |
+
G.add_node(word, label="Environmental")
|
| 148 |
+
seen_words.add(word)
|
| 149 |
+
|
| 150 |
+
# Link nodes in order of appearance
|
| 151 |
+
all_nodes = list(G.nodes()) # Use G.nodes() after adding all nodes
|
| 152 |
+
for i in range(len(all_nodes) - 1):
|
| 153 |
+
G.add_edge(all_nodes[i], all_nodes[i + 1])
|
| 154 |
+
|
| 155 |
+
# Draw the graph
|
| 156 |
+
fig, ax = plt.subplots(figsize=(10, 7)) # Increased figure size for better readability
|
| 157 |
+
pos = nx.spring_layout(G, seed=42, k=0.7) # Adjusted k for better spacing
|
| 158 |
+
|
| 159 |
+
labels = nx.get_node_attributes(G, "label")
|
| 160 |
+
color_map = {
|
| 161 |
+
"Person": "orange", "Location": "skyblue", "Organization": "lightgray",
|
| 162 |
+
"Misc": "violet", "Environmental": "lightgreen"
|
| 163 |
+
}
|
| 164 |
+
node_colors = [color_map.get(labels.get(node, ""), "white") for node in G.nodes]
|
| 165 |
+
|
| 166 |
+
# Draw with enhanced styling
|
| 167 |
+
nx.draw(
|
| 168 |
+
G, pos, with_labels=False, node_color=node_colors, edge_color="gray",
|
| 169 |
+
node_size=3000, font_weight="bold", alpha=0.9, linewidths=1.5, edgecolors="black"
|
| 170 |
+
)
|
| 171 |
+
# Add labels with background for better visibility
|
| 172 |
+
for node, (x, y) in pos.items():
|
| 173 |
+
text_label = f"{node}\n({labels[node]})" if node in labels else node
|
| 174 |
+
ax.text(x, y, text_label, horizontalalignment='center', verticalalignment='center',
|
| 175 |
+
fontsize=9, color='black', bbox=dict(facecolor='white', alpha=0.7, edgecolor='none', boxstyle='round,pad=0.3'))
|
| 176 |
+
|
| 177 |
+
st.pyplot(fig) # Display the plot directly in Streamlit
|
| 178 |
+
plt.close(fig) # Close the figure to free up memory
|
| 179 |
+
|
| 180 |
+
def fill_blank(text):
|
| 181 |
+
if "<mask>" not in text:
|
| 182 |
+
st.error("β Please include exactly one `<mask>` token in your sentence.")
|
| 183 |
+
return []
|
| 184 |
+
try:
|
| 185 |
+
results = fill_mask(text)
|
| 186 |
+
return [r["sequence"] for r in results]
|
| 187 |
+
except Exception as e:
|
| 188 |
+
st.error(f"Error: {str(e)}")
|
| 189 |
+
return []
|
| 190 |
+
|
| 191 |
+
# 4. Streamlit UI
|
| 192 |
+
tab1, tab2, tab3, tab4 = st.tabs([
|
| 193 |
+
"1οΈβ£ Sentence Classification",
|
| 194 |
+
"2οΈβ£ Image Generation",
|
| 195 |
+
"3οΈβ£ NER + Entity Graph",
|
| 196 |
+
"4οΈβ£ Fill-in-the-Blank"
|
| 197 |
+
])
|
| 198 |
+
|
| 199 |
+
with tab1:
|
| 200 |
+
st.header("Sentence Classification")
|
| 201 |
+
st.write("Automatically categorize environmental sentences.")
|
| 202 |
+
text_input = st.text_area("π Enter an environmental sentence:", height=100,
|
| 203 |
+
placeholder="Example: The factory discharged toxic waste into the river.")
|
| 204 |
+
if st.button("π Classify Sentence"):
|
| 205 |
+
if text_input:
|
| 206 |
+
result = classify_text(text_input)
|
| 207 |
+
st.info(result)
|
| 208 |
+
else:
|
| 209 |
+
st.warning("Please enter some text to classify.")
|
| 210 |
+
|
| 211 |
+
with tab2:
|
| 212 |
+
st.header("Image Generation")
|
| 213 |
+
st.write("Generate environmental images from text prompts.")
|
| 214 |
+
img_prompt_input = st.text_area("π¨ Prompt for environmental image:", height=100,
|
| 215 |
+
placeholder="Example: A serene forest with clean river and diverse wildlife.")
|
| 216 |
+
if st.button("π§ Generate Image"):
|
| 217 |
+
if img_prompt_input:
|
| 218 |
+
generated_image = generate_image(img_prompt_input)
|
| 219 |
+
st.image(generated_image, caption=img_prompt_input, use_column_width=True)
|
| 220 |
+
else:
|
| 221 |
+
st.warning("Please enter a prompt to generate an image.")
|
| 222 |
+
|
| 223 |
+
with tab3:
|
| 224 |
+
st.header("Named Entity Recognition (NER) & Entity Graph")
|
| 225 |
+
st.write("Extract and visualize named entities and environmental terms from text.")
|
| 226 |
+
ner_input_text = st.text_area("π Sentence with named entities:", height=100,
|
| 227 |
+
value="The CEO of EcoCorp announced a new initiative in London to reduce plastic waste.",
|
| 228 |
+
placeholder="Example: John lives in New York and works for Google.")
|
| 229 |
+
if st.button("π Extract & Visualize Entities"):
|
| 230 |
+
if ner_input_text:
|
| 231 |
+
st.info("Generating entity graph...")
|
| 232 |
+
ner_with_graph(ner_input_text)
|
| 233 |
+
else:
|
| 234 |
+
st.warning("Please enter some text for entity extraction.")
|
| 235 |
+
|
| 236 |
+
with tab4:
|
| 237 |
+
st.header("Fill-in-the-Blank")
|
| 238 |
+
st.write("Predict missing words in environmental sentences using `<mask>`.")
|
| 239 |
+
fill_input_text = st.text_area("π§© Enter sentence with `<mask>`:", height=100,
|
| 240 |
+
value="Air <mask> is harmful to public health.",
|
| 241 |
+
placeholder="Example: The Amazon <mask> is a vital ecosystem.")
|
| 242 |
+
if st.button("π Predict Missing Word(s)"):
|
| 243 |
+
if fill_input_text:
|
| 244 |
+
predictions = fill_blank(fill_input_text)
|
| 245 |
+
if predictions:
|
| 246 |
+
st.subheader("π Top Predictions:")
|
| 247 |
+
for i, pred in enumerate(predictions):
|
| 248 |
+
st.write(f"{i+1}. {pred}")
|
| 249 |
+
else:
|
| 250 |
+
st.warning("Please enter a sentence with `<mask>`.")
|
| 251 |
+
|
| 252 |
+
st.markdown("---")
|
| 253 |
+
st.markdown("Developed with β€οΈ for a greener future.")
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
transformers
|
| 3 |
+
networkx
|
| 4 |
+
matplotlib
|
| 5 |
+
torch
|
| 6 |
+
diffusers
|
| 7 |
+
accelerate # Highly recommended for faster Stable Diffusion on GPU
|