polymer / app.py
SyedWaqad's picture
Update app.py
f65d68e verified
## 🧠 3. **app.py** (slightly cleaned and deployment-safe)
##✅ Minor improvements:
## Prints installed packages on startup (for debugging on Spaces)
##- More descriptive error message if `groq` isn’t installed
##- Compatible with both local and Space environments
##```python
import os
import gradio as gr
from dotenv import load_dotenv
import subprocess
# ----------------------------------------------
# Print installed packages (for debugging on HF Spaces)
# ----------------------------------------------
print("🔍 Checking installed packages...")
subprocess.run(["pip", "list"])
# ----------------------------------------------
# Load environment variables
# ----------------------------------------------
load_dotenv()
# Ensure Groq API key exists
if not os.getenv("GROQ_API_KEY"):
raise ValueError("Missing GROQ_API_KEY. Add it in .env or Space secrets.")
# ----------------------------------------------
# Import Groq safely
# ----------------------------------------------
try:
from groq import Groq
except ModuleNotFoundError:
Groq = None
def evaluate_suitability(*args):
return "❌ Error: 'groq' module not installed. Make sure 'groq' is in requirements.txt and rebuild the Space."
# ----------------------------------------------
# Polymer data
# ----------------------------------------------
polymer_choices = [
"Polyacrylamide",
"Chitosan",
"Polyamine",
"Polyacrylic Acid",
"Cellulose"
]
details_dict = {
"Polyacrylamide": """
Polyacrylamide (PAM) is a synthetic polymer used in water treatment.
Types: Anionic, Cationic, Non-ionic.
Properties: Water-soluble, high molecular weight, charge varies by type.
Applications: Flocculation and coagulation.
Advantages: Efficient particle aggregation.
Disadvantages: Potential toxicity from residual monomers.
""",
"Chitosan": """
Chitosan is a natural polymer derived from chitin.
Properties: Biodegradable, non-toxic, cationic in acidic pH.
Applications: Heavy metal and dye adsorption.
Advantages: Eco-friendly and renewable.
Disadvantages: Performance sensitive to pH.
""",
"Polyamine": """
Polyamine is a synthetic cationic polymer.
Applications: Water treatment and papermaking.
Advantages: Effective on negative charge suspensions.
Disadvantages: Limited scope.
""",
"Polyacrylic Acid": """
Synthetic anionic polymer with strong chelating properties.
Applications: Dye and pollutant adsorption.
Advantages: Customizable and strong chelation.
Disadvantages: Cost and potential gel formation.
""",
"Cellulose": """
Natural polymer from plants.
Applications: Metal removal and wastewater treatment.
Advantages: Eco-friendly, low-cost.
Disadvantages: Limited strength and purity variability.
"""
}
# ----------------------------------------------
# Helper functions
# ----------------------------------------------
def get_polymer_details(polymer):
return details_dict.get(polymer, "No details available.")
def evaluate_suitability(polymer, treatment):
if Groq is None:
return "❌ Error: The 'groq' module is not installed. Please ensure it’s listed in requirements.txt and rebuild."
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
properties = details_dict.get(polymer, "Unknown properties")
prompt = f"""
Evaluate if the polymer {polymer} is suitable for {treatment} applications.
Consider its chemical properties: {properties}.
Provide pros, cons, and reasoning based on known literature.
"""
try:
response = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model="llama3-70b-8192",
temperature=0.7,
max_tokens=500
)
return response.choices[0].message.content
except Exception as e:
return f"⚠️ Error while evaluating: {str(e)}"
# ----------------------------------------------
# Gradio UI
# ----------------------------------------------
with gr.Blocks(title="Polymer Evaluation Tool") as demo:
gr.Markdown("# 🧪 Polymer Selection and Evaluation Tool")
polymer = gr.Dropdown(choices=polymer_choices, label="Select Polymer")
details_output = gr.Textbox(label="Polymer Details", lines=10, interactive=False)
treatment = gr.Dropdown(choices=["Water Treatment"], label="Select Treatment Type")
eval_output = gr.Textbox(label="AI Suitability Evaluation", lines=15, interactive=False)
polymer.change(fn=get_polymer_details, inputs=polymer, outputs=details_output)
submit_btn = gr.Button("Evaluate Suitability")
submit_btn.click(fn=evaluate_suitability, inputs=[polymer, treatment], outputs=eval_output)
demo.launch()