Spaces:
Sleeping
Sleeping
please work
Browse files
app.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import geopandas as gpd
|
| 2 |
+
import sqlite3
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import torch
|
| 5 |
+
import faiss
|
| 6 |
+
import numpy as np
|
| 7 |
+
import os
|
| 8 |
+
from shapely.geometry import shape
|
| 9 |
+
from sentence_transformers import SentenceTransformer
|
| 10 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 11 |
+
import streamlit as st
|
| 12 |
+
|
| 13 |
+
# Set the environment variables for GPU usage in Hugging Face
|
| 14 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # Hugging Face uses GPU 0 by default
|
| 15 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 16 |
+
|
| 17 |
+
# Set device to GPU if available
|
| 18 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 19 |
+
st.write(f"Using device: {device}")
|
| 20 |
+
|
| 21 |
+
# Step 1: Load and Process Floodland Data
|
| 22 |
+
conn = sqlite3.connect('NY.db')
|
| 23 |
+
cursor = conn.cursor()
|
| 24 |
+
|
| 25 |
+
# Load shapefile
|
| 26 |
+
gdf = gpd.read_file('S_FLD_HAZ_AR.shp')
|
| 27 |
+
|
| 28 |
+
# Validate geometries
|
| 29 |
+
gdf['geometry'] = gdf['geometry'].apply(lambda geom: geom if geom.is_valid else None)
|
| 30 |
+
gdf = gdf.dropna(subset=['geometry'])
|
| 31 |
+
|
| 32 |
+
# Convert CRS to UTM Zone 18N (New York)
|
| 33 |
+
gdf = gdf.to_crs(epsg=32618)
|
| 34 |
+
|
| 35 |
+
# Calculate acreage (1 square meter = 0.000247105 acres)
|
| 36 |
+
gdf['acreage'] = gdf.geometry.area * 0.000247105
|
| 37 |
+
|
| 38 |
+
# Define flood-prone zones and calculate usable area
|
| 39 |
+
flood_prone_zones = ['A', 'AE', 'AH', 'AO', 'VE']
|
| 40 |
+
gdf['usable_area'] = gdf.apply(lambda row: row['acreage'] if row['FLD_ZONE'] not in flood_prone_zones else 0, axis=1)
|
| 41 |
+
|
| 42 |
+
# Convert geometry to WKT format
|
| 43 |
+
gdf['wkt_geometry'] = gdf['geometry'].apply(lambda geom: geom.wkt)
|
| 44 |
+
|
| 45 |
+
# Step 2: Load Embedding Model (Sentence-Transformer)
|
| 46 |
+
embedder = SentenceTransformer('all-MiniLM-L6-v2')
|
| 47 |
+
|
| 48 |
+
# Convert floodland descriptions into text
|
| 49 |
+
gdf['text'] = gdf.apply(
|
| 50 |
+
lambda row: f"Flood Zone: {row['FLD_ZONE']}, Subtype: {row['ZONE_SUBTY']}, Acreage: {row['acreage']:.2f} acres, Usable Area: {row['usable_area']:.2f} acres",
|
| 51 |
+
axis=1
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# Generate text embeddings
|
| 55 |
+
embeddings = embedder.encode(gdf['text'].tolist(), show_progress_bar=True)
|
| 56 |
+
|
| 57 |
+
# Create FAISS index
|
| 58 |
+
d = embeddings.shape[1]
|
| 59 |
+
index = faiss.IndexFlatL2(d)
|
| 60 |
+
index.add(embeddings)
|
| 61 |
+
|
| 62 |
+
# Store embeddings in DataFrame
|
| 63 |
+
gdf['embedding'] = list(embeddings)
|
| 64 |
+
|
| 65 |
+
# Step 3: Load LLaMA Model for Summarization
|
| 66 |
+
llama_model_name = "meta-llama/Llama-2-7b-chat-hf"
|
| 67 |
+
tokenizer = AutoTokenizer.from_pretrained(llama_model_name)
|
| 68 |
+
model = AutoModelForCausalLM.from_pretrained(llama_model_name, torch_dtype=torch.float16, device_map="auto")
|
| 69 |
+
|
| 70 |
+
# Function to Generate Summary using LLaMA
|
| 71 |
+
def llama_summarize(text, total_acreage, usable_acreage, location_data, max_length=250):
|
| 72 |
+
input_text = f"""
|
| 73 |
+
**Total Land Area**: {total_acreage:.2f} acres
|
| 74 |
+
**Usable Area**: {usable_acreage:.2f} acres
|
| 75 |
+
**Flood-prone Zones**:
|
| 76 |
+
{location_data}
|
| 77 |
+
|
| 78 |
+
Summarization in sentence
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
inputs = tokenizer(input_text, return_tensors="pt").to(device)
|
| 82 |
+
|
| 83 |
+
# Calculate max_new_tokens based on input size
|
| 84 |
+
input_length = inputs['input_ids'].shape[1]
|
| 85 |
+
max_new_tokens = max_length - input_length
|
| 86 |
+
if max_new_tokens <= 0:
|
| 87 |
+
max_new_tokens = 200 # Ensure at least a few tokens are generated
|
| 88 |
+
|
| 89 |
+
with torch.no_grad():
|
| 90 |
+
output_tokens = model.generate(
|
| 91 |
+
**inputs,
|
| 92 |
+
max_new_tokens=max_new_tokens, # Use max_new_tokens to control the generated length
|
| 93 |
+
temperature=0.7,
|
| 94 |
+
top_k=50,
|
| 95 |
+
top_p=0.9,
|
| 96 |
+
repetition_penalty=1.2
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
summary = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
|
| 100 |
+
return summary
|
| 101 |
+
|
| 102 |
+
# Step 4: RAG Summarization Function
|
| 103 |
+
def rag_summarize(query, gdf, index, k=5):
|
| 104 |
+
query = query.lower().strip()
|
| 105 |
+
query_embedding = embedder.encode([query])[0]
|
| 106 |
+
|
| 107 |
+
# Retrieve top-k relevant documents
|
| 108 |
+
distances, indices = index.search(np.array([query_embedding]), k)
|
| 109 |
+
retrieved_docs = gdf.iloc[indices[0]]
|
| 110 |
+
|
| 111 |
+
# Aggregate data
|
| 112 |
+
total_acreage = retrieved_docs['acreage'].sum()
|
| 113 |
+
usable_acreage = retrieved_docs['usable_area'].sum()
|
| 114 |
+
location_data = "\n".join([
|
| 115 |
+
f"- **Flood Zone**: {row['FLD_ZONE']}, **Subtype**: {row['ZONE_SUBTY']}, "
|
| 116 |
+
f"**Acreage**: {row['acreage']:.2f}, **Usable Area**: {row['usable_area']:.2f} acres"
|
| 117 |
+
for _, row in retrieved_docs.iterrows()
|
| 118 |
+
])
|
| 119 |
+
|
| 120 |
+
# Use LLaMA for summarization
|
| 121 |
+
summary = llama_summarize(query, total_acreage, usable_acreage, location_data)
|
| 122 |
+
|
| 123 |
+
return summary
|
| 124 |
+
|
| 125 |
+
# Streamlit Interface
|
| 126 |
+
st.title("🌊 Floodland Summary Bot (Powered by LLaMA-2)")
|
| 127 |
+
|
| 128 |
+
# Input for location
|
| 129 |
+
user_input = st.text_input("Enter a location (e.g., New York)", "")
|
| 130 |
+
|
| 131 |
+
# When the user inputs a query, display the summary
|
| 132 |
+
if user_input:
|
| 133 |
+
query = user_input.lower().strip()
|
| 134 |
+
summary = rag_summarize(query, gdf, index)
|
| 135 |
+
st.write(summary)
|