CoolFace
Apppublic

Nimzi/Environment

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py102 linesDownload Raw Back to root
1import os2import pandas as pd3from langchain.vectorstores import FAISS4from langchain.embeddings import SentenceTransformerEmbeddings5from groq import Groq6import gradio as gr7 8# Load data from uploaded CSV9def load_data():10    file_path = "environmental_project_data.csv"  # Make sure the file is uploaded in the root directory11    if not os.path.exists(file_path):12        raise FileNotFoundError("The CSV file is missing. Please upload the file to the app directory.")13    return pd.read_csv(file_path)14 15# Index documents16def index_documents(df):17    if "Mitigation measures" not in df.columns:18        raise ValueError("The CSV file must contain a 'Mitigation measures' column.")19    documents = [{"content": row} for row in df["Mitigation measures"].dropna().tolist()]20    embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")21    vector_store = FAISS.from_texts([doc["content"] for doc in documents], embeddings)22    return vector_store23 24# Setup Groq API25def setup_groq_api():26    os.environ["GROQ_API_KEY"] = "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"27    api_key = os.environ.get("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")28    if not api_key:29        raise ValueError("GROQ_API_KEY environment variable is not set.")30    client = Groq(api_key=api_key)31    return client32 33# Generate report34def generate_report(project_details, vector_store, client):35    try:36        retriever = vector_store.as_retriever()37        relevant_docs = retriever.get_relevant_documents(project_details)38 39        if not relevant_docs:40            return "No relevant documents found for the given project details."41 42        context = "\n".join([doc["content"] for doc in relevant_docs])43        prompt = f"""44        Using the following context, write an environmental input assessment report:45        Context:46        {context}47        Project Details:48        {project_details}49        """50 51        chat_completion = client.chat.completions.create(52            messages=[{"role": "user", "content": prompt}],53            model="llama3-8b-8192",54            stream=False,55        )56        return chat_completion.choices[0].message.content57    except Exception as e:58        return f"Error during report generation: {e}"59 60# Build Gradio interface61def build_interface(vector_store, client):62    def wrapper(project_details):63        return generate_report(project_details, vector_store, client)64 65    with gr.Blocks() as interface:66        gr.Markdown("# Environmental Assessment Report Generator")67        project_details = gr.Textbox(68            label="Enter Project Details",69            placeholder="Describe the project (e.g., type, location, environmental factors)."70        )71        generate_button = gr.Button("Generate Report")72        report_output = gr.Textbox(label="Generated Report", lines=10)73 74        generate_button.click(75            fn=wrapper,76            inputs=[project_details],77            outputs=[report_output]78        )79    return interface80 81# Main script82if __name__ == "__main__":83    try:84        # Load data85        print("Loading data...")86        df = load_data()87 88        # Index documents89        print("Indexing documents...")90        vector_store = index_documents(df)91 92        # Setup Groq API93        print("Setting up Groq API...")94        client = setup_groq_api()95 96        # Launch Gradio interface97        print("Launching the app...")98        interface = build_interface(vector_store, client)99        interface.launch(server_name="0.0.0.0", server_port=7860)100    except Exception as e:101        print(f"Error: {e}")102