CoolFace
Apppublic

Param56/Environmental_Ass

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py170 linesDownload Raw Back to root
1# Install required libraries
2# !pip install gradio transformers torch spacy networkx matplotlib diffusers sentencepiece accelerate ftfy
3# !python -m spacy download en_core_web_sm
4
5import gradio as gr
6from transformers import pipeline
7import spacy
8import networkx as nx
9import matplotlib.pyplot as plt
10from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForMaskedLM
11from diffusers import StableDiffusionPipeline
12import torch
13import warnings
14warnings.filterwarnings("ignore")
15
16# Initialize models
17classifier = None
18image_pipe = None
19ner_pipe = None
20mask_filler = None
21
22def download_models():
23    global classifier, image_pipe, ner_pipe, mask_filler
24    
25    # Sentence Classification Model
26    print("Downloading sentence classification model...")
27    classifier = pipeline(
28        "text-classification",
29        model="distilbert-base-uncased-finetuned-sst-2-english"
30    )
31    
32    # Image Generation Model
33    print("Downloading image generation model...")
34    image_pipe = StableDiffusionPipeline.from_pretrained(
35        "CompVis/stable-diffusion-v1-4",
36        torch_dtype=torch.float16,
37        use_auth_token=True
38    ).to("cuda" if torch.cuda.is_available() else "cpu")
39    
40    # NER Model
41    print("Downloading NER model...")
42    ner_pipe = pipeline(
43        "ner",
44        model="dbmdz/bert-large-cased-finetuned-conll03-english",
45        grouped_entities=True
46    )
47    
48    # Mask Filling Model
49    print("Downloading mask filling model...")
50    mask_filler = pipeline(
51        "fill-mask",
52        model="bert-large-uncased"
53    )
54    return "All models downloaded successfully!"
55
56def classify_text(text):
57    environment_categories = {
58        'POSITIVE': 'Environmentally Positive',
59        'NEGATIVE': 'Environmentally Negative',
60        'NEUTRAL': 'Environmentally Neutral',
61        'POLICY': 'Environmental Policy',
62        'SCIENCE': 'Environmental Science'
63    }
64    
65    result = classifier(text)[0]
66    label = result['label']
67    score = result['score']
68    
69    if label in ['LABEL_0', 'NEGATIVE']:
70        return f"Category: {environment_categories['NEGATIVE']}\nConfidence: {score:.2f}"
71    elif label in ['LABEL_1', 'POSITIVE']:
72        return f"Category: {environment_categories['POSITIVE']}\nConfidence: {score:.2f}"
73    else:
74        return f"Category: {environment_categories['NEUTRAL']}\nConfidence: {score:.2f}"
75
76def generate_environment_image(prompt):
77    generator = torch.Generator("cuda" if torch.cuda.is_available() else "cpu").manual_seed(42)
78    image = image_pipe(
79        f"environmental {prompt}, high quality, detailed, nature, realistic",
80        generator=generator,
81        num_inference_steps=50
82    ).images[0]
83    return image
84
85def create_ner_graph(text):
86    ner_results = ner_pipe(text)
87    G = nx.Graph()
88    
89    for entity in ner_results:
90        entity_text = entity['word']
91        entity_type = entity['entity_group']
92        G.add_node(entity_text, type=entity_type)
93    
94    for i in range(len(ner_results)-1):
95        node1 = ner_results[i]['word']
96        node2 = ner_results[i+1]['word']
97        G.add_edge(node1, node2)
98    
99    plt.figure(figsize=(12, 8))
100    pos = nx.spring_layout(G)
101    colors = []
102    for node in G.nodes():
103        if G.nodes[node]['type'] == 'PER':
104            colors.append('red')
105        elif G.nodes[node]['type'] == 'ORG':
106            colors.append('blue')
107        elif G.nodes[node]['type'] == 'LOC':
108            colors.append('green')
109        else:
110            colors.append('yellow')
111    
112    nx.draw(G, pos, with_labels=True, node_color=colors, node_size=2000, font_size=12)
113    plt.title("Environmental NER Graph")
114    plt.axis("off")
115    plt.savefig("ner_graph.png")
116    plt.close()
117    return "ner_graph.png"
118
119def fill_environment_mask(text_with_mask):
120    results = mask_filler(text_with_mask)
121    top_result = results[0]
122    return {
123        "filled_text": text_with_mask.replace("[MASK]", top_result['token_str']),
124        "options": [r['token_str'] for r in results]
125    }
126
127# Gradio Interface
128with gr.Blocks(title="Environmental AI Assistant") as demo:
129    gr.Markdown("# ๐ŸŒ Environmental AI Assistant")
130    gr.Markdown("Analyze and generate environmental content using AI models")
131    
132    with gr.Tab("Sentence Classification"):
133        gr.Markdown("### Classify text into environmental categories")
134        text_input = gr.Textbox(label="Enter environmental text")
135        classify_btn = gr.Button("Classify")
136        classification_output = gr.Textbox(label="Classification Result")
137        classify_btn.click(classify_text, inputs=text_input, outputs=classification_output)
138    
139    with gr.Tab("Image Generation"):
140        gr.Markdown("### Generate environmental images from text")
141        prompt_input = gr.Textbox(label="Describe the environmental scene")
142        generate_btn = gr.Button("Generate Image")
143        image_output = gr.Image(label="Generated Image")
144        generate_btn.click(generate_environment_image, inputs=prompt_input, outputs=image_output)
145    
146    with gr.Tab("NER Graph"):
147        gr.Markdown("### Extract entities and visualize relationships")
148        ner_text_input = gr.Textbox(label="Input text with environmental content")
149        ner_btn = gr.Button("Extract Entities")
150        ner_graph_output = gr.Image(label="Entity Relationship Graph")
151        ner_btn.click(create_ner_graph, inputs=ner_text_input, outputs=ner_graph_output)
152    
153    with gr.Tab("Fill Mask"):
154        gr.Markdown("### Complete environmental sentences with AI")
155        mask_examples = [
156            "Reducing [MASK] emissions is critical for climate change.",
157            "The [MASK] is home to many endangered species.",
158            "We should recycle more [MASK] to help the environment."
159        ]
160        mask_input = gr.Textbox(label="Enter sentence with [MASK]", value=mask_examples[0])
161        fill_btn = gr.Button("Fill Mask")
162        filled_output = gr.Textbox(label="Completed Sentence")
163        options_output = gr.HighlightedText(label="Alternative Options")
164        fill_btn.click(lambda x: fill_environment_mask(x), inputs=mask_input, outputs=[filled_output, options_output])
165        gr.Examples(examples=mask_examples, inputs=mask_input)
166
167print("Downloading models... (this may take several minutes)")
168download_status = download_models()
169print(download_status)
170demo.launch(share=True)