sankalp2606's picture
Update app.py
e5f5c4e verified
import streamlit as st
import os
import google.generativeai as genai
st.set_page_config(
page_title="Samvidhan AI",
page_icon="πŸ“œ",
layout="wide"
)
# Custom CSS
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
color: #2E3A8C;
text-align: center;
margin-bottom: 0.5rem;
}
.subheader {
font-size: 1.2rem;
color: #3949AB;
text-align: center;
margin-bottom: 2rem;
}
.analysis-box {
background-color: #F8F9FA;
padding: 20px;
border-radius: 10px;
border-left: 4px solid #2E3A8C;
margin: 20px 0;
}
.example-box {
background-color: #E3F2FD;
padding: 15px;
border-radius: 8px;
margin: 10px 0;
border: 1px solid #BBDEFB;
}
.warning-box {
background-color: #FFF3E0;
padding: 15px;
border-radius: 8px;
border-left: 4px solid #FF9800;
margin: 20px 0;
}
</style>
""", unsafe_allow_html=True)
# Header
st.markdown('<p class="main-header">πŸ“œ Samvidhan AI</p>', unsafe_allow_html=True)
st.markdown('<p class="subheader">Constitutional Law Assistant for India</p>', unsafe_allow_html=True)
# Safe API key handling
api_key = st.secrets.get("GOOGLE_API_KEY", os.getenv("GOOGLE_API_KEY", ""))
if api_key:
try:
genai.configure(api_key=api_key)
except Exception as e:
st.error(f"❌ Error configuring API: {str(e)}")
else:
st.warning("⚠️ API key not found. The analysis feature will be disabled.")
def get_constitutional_analysis(scenario):
"""Generate constitutional analysis using Google Gemini"""
if not api_key:
return "❌ API key not configured. Please contact the space administrator."
try:
model = genai.GenerativeModel('gemini-1.5-flash')
prompt = f"""
You are a Constitutional law expert specializing in the Constitution of India.
Provide a comprehensive, factual, and unbiased analysis of the following scenario:
**Scenario:** {scenario}
**Please provide a detailed analysis including:**
1. **Relevant Constitutional Articles**: List specific articles with exact numbers and brief descriptions
2. **Legal Framework**: Explain how these constitutional provisions apply to this scenario
3. **Possible Interpretations**: Discuss different legal perspectives and potential outcomes
4. **Judicial Precedents**: Mention any relevant Supreme Court or High Court cases if applicable
5. **Constitutional Balance**: Explain any competing rights or principles involved
6. **Practical Implications**: What this means in real-world legal terms
7. **Areas of Uncertainty**: Any ambiguous aspects or evolving jurisprudence
"""
response = model.generate_content(prompt)
return response.text
except Exception as e:
return f"❌ Error generating analysis: {str(e)}"
# Example scenarios
examples = [
{
"title": "Free Speech vs Public Order",
"scenario": "A state government passes a law restricting online speech criticizing its ministers, citing maintenance of public order. Citizens argue this violates their fundamental right to free speech. Is this constitutional under Indian law?"
},
{
"title": "Religious Freedom in Education",
"scenario": "A private Christian school refuses admission to a Muslim student, stating they only admit Christian students to maintain their religious character. The student's parents file a complaint claiming discrimination. What does the Constitution say about this?"
},
{
"title": "Reservation Policy Challenge",
"scenario": "A general category student with 95% marks is denied admission to a medical college, while an SC category student with 70% marks gets admission under reservation. The general category student challenges this as violating equality. Is the reservation policy constitutional?"
},
{
"title": "Property Rights & Land Acquisition",
"scenario": "The government wants to acquire private agricultural land for a highway project. The farmer refuses to sell, claiming it violates his property rights. The government proceeds with compulsory acquisition. What are the constitutional provisions here?"
},
{
"title": "Emergency Powers",
"scenario": "During a natural disaster, a state government declares emergency and suspends all fundamental rights for 30 days, including the right to move freely and conduct business. A business owner challenges this in court. Is such action constitutionally valid?"
},
{
"title": "Right to Privacy vs National Security",
"scenario": "The government introduces a law requiring all citizens to provide biometric data and link it to all their activities. Citizens challenge this citing right to privacy. How does the Constitution balance privacy rights with national security?"
}
]
# Example section
st.markdown("## πŸ’‘ Example Constitutional Scenarios")
with st.expander("πŸ“‹ View Example Scenarios"):
for i, example in enumerate(examples, 1):
st.markdown(f"**{i}. {example['title']}**")
st.markdown(f"<div class='example-box'>{example['scenario']}</div>", unsafe_allow_html=True)
selected_example = st.selectbox(
"Select an example or choose 'Custom' to write your own:",
["Custom Scenario"] + [ex["title"] for ex in examples]
)
if selected_example == "Custom Scenario":
scenario = st.text_area("πŸ“ Describe your constitutional law scenario:", height=200)
else:
selected_scenario = next((ex['scenario'] for ex in examples if ex['title'] == selected_example), "")
scenario = st.text_area("πŸ“ Selected scenario (you can modify it):", value=selected_scenario, height=200)
# Analysis button
if st.button("πŸ” **Analyze Constitutional Implications**", use_container_width=True):
if scenario.strip():
with st.spinner("πŸ”„ Analyzing constitutional aspects..."):
analysis = get_constitutional_analysis(scenario.strip())
st.markdown("---")
st.markdown("## πŸ“œ **Constitutional Analysis**")
st.markdown(f'<div class="analysis-box">{analysis}</div>', unsafe_allow_html=True)
st.download_button(
label="πŸ“„ Download Analysis",
data=f"Scenario:\n{scenario}\n\nAnalysis:\n{analysis}",
file_name="constitutional_analysis.txt",
mime="text/plain"
)
else:
st.warning("⚠️ Please enter a scenario to analyze.")
# Sidebar
with st.sidebar:
st.info("**Samvidhan AI** helps analyze constitutional law scenarios in India.")
if api_key:
if st.button("πŸ§ͺ Test API Connection"):
try:
model = genai.GenerativeModel('gemini-1.5-flash')
resp = model.generate_content("What is Article 21 of the Indian Constitution?")
if resp.text and len(resp.text) > 50:
st.success("βœ… API connection successful!")
else:
st.warning("⚠️ API response seems incomplete.")
except Exception as e:
st.error(f"❌ API test failed: {str(e)}")
else:
st.error("❌ API not configured. Analysis disabled.")
# Hugging Face auto-run support
if __name__ == "__main__":
import sys
port = int(os.environ.get("PORT", 7860))
sys.argv = ["streamlit", "run", "app.py", "--server.port", str(port), "--server.address", "0.0.0.0"]
from streamlit.web import cli as stcli
sys.exit(stcli.main())