sankalp2606 commited on
Commit
a58062e
Β·
verified Β·
1 Parent(s): 87a7e2d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +221 -63
app.py CHANGED
@@ -1,96 +1,254 @@
1
  import streamlit as st
2
  import os
3
- from scenario_advisor import get_scenario_based_response
4
 
5
- st.set_page_config(page_title="Samvidhan AI", page_icon="πŸ“œ")
6
-
7
- # Get API key from Hugging Face Secrets
8
- try:
9
- api_key = st.secrets["GOOGLE_API_KEY"]
10
- st.success("βœ… API Key loaded from secrets")
11
- except Exception as e:
12
- st.error("❌ Could not load API key from secrets")
13
- st.info("Please configure GOOGLE_API_KEY in Space Settings β†’ Secrets")
14
- api_key = None
15
 
 
16
  st.markdown("""
17
  <style>
18
- .main-header { font-size: 2.5rem; color: #2E3A8C; }
19
- .subheader { font-size: 1.5rem; color: #3949AB; }
20
- .scenario-box {
21
- background-color: #E3F2FD;
 
 
 
 
 
 
 
 
 
 
22
  padding: 20px;
23
  border-radius: 10px;
 
24
  margin: 20px 0;
 
 
 
 
 
 
25
  border: 1px solid #BBDEFB;
26
- color: #000000 !important;
 
 
 
 
 
 
27
  }
28
  </style>
29
  """, unsafe_allow_html=True)
30
 
31
- # For now, focus on scenario-based analysis since FAISS index setup is complex
32
- st.markdown('<p class="main-header">βš–οΈ Samvidhan AI - Constitutional Analysis</p>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- # API Key check
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  if not api_key:
36
- st.error("πŸ” Google API Key not configured. Please contact the administrator.")
 
 
 
 
 
 
37
  st.stop()
38
 
39
- st.markdown("### Scenario-based Legal Analysis")
40
- st.markdown("Analyze legal scenarios based on the Indian Constitution")
 
41
 
42
  examples = [
43
- "A state government passes a law restricting online speech criticizing its ministers, citing maintenance of public order. Is this constitutional?",
44
- "A private school refuses admission based on religion. What does the Constitution say?",
45
- "Government wants to acquire private land for highway. What are the constitutional provisions?",
46
- "A citizen wants to know their fundamental rights under Article 19.",
47
- "Can a state government ban a particular religious practice in public places?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  ]
49
 
50
- selected_example = st.selectbox("Choose an example or write your own:", ["Write your own..."] + examples)
 
 
 
 
51
 
52
- if selected_example != "Write your own...":
53
- scenario = st.text_area("Describe your legal scenario", value=selected_example, height=200)
 
 
 
 
 
 
 
 
 
 
 
 
54
  else:
55
- scenario = st.text_area("Describe your legal scenario", height=200,
56
- placeholder="Example: A government employee wants to know if they can participate in political protests...")
57
-
58
- if st.button("πŸ” Analyze Scenario", type="primary"):
59
- if scenario.strip():
60
- with st.spinner("Analyzing constitutional implications..."):
61
- try:
62
- response = get_scenario_based_response(scenario)
63
- st.markdown("### πŸ“œ Constitutional Analysis:")
64
- st.write(response)
65
-
66
- except Exception as e:
67
- st.error(f"Error analyzing scenario: {str(e)}")
68
- st.info("Please check if the API key is properly configured.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  else:
70
  st.warning("⚠️ Please enter a scenario to analyze.")
71
 
72
  # Sidebar
73
  with st.sidebar:
74
- st.markdown("### πŸ“œ Samvidhan AI")
75
- st.markdown("Constitutional AI Assistant for India")
 
76
 
77
- st.markdown("**Features:**")
78
- st.markdown("- Scenario-based legal analysis")
79
- st.markdown("- Constitutional article references")
80
- st.markdown("- Plain language explanations")
81
- st.markdown("- Supreme Court precedents")
 
82
 
83
- st.markdown("---")
84
- st.markdown("**Disclaimer:**")
85
- st.markdown("This tool provides educational information only. For legal advice, consult a qualified lawyer.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  st.markdown("---")
88
- if st.button("πŸ§ͺ Test API Connection"):
89
- try:
90
- test_response = get_scenario_based_response("Test: What is the Constitution of India?")
91
- if test_response and len(test_response) > 50:
92
- st.success("βœ… API working correctly!")
93
- else:
94
- st.warning("⚠️ API response seems incomplete")
95
- except Exception as e:
96
- st.error(f"❌ API test failed: {str(e)}")
 
 
 
 
 
 
1
  import streamlit as st
2
  import os
3
+ import google.generativeai as genai
4
 
5
+ st.set_page_config(
6
+ page_title="Samvidhan AI",
7
+ page_icon="πŸ“œ",
8
+ layout="wide"
9
+ )
 
 
 
 
 
10
 
11
+ # Custom CSS
12
  st.markdown("""
13
  <style>
14
+ .main-header {
15
+ font-size: 2.5rem;
16
+ color: #2E3A8C;
17
+ text-align: center;
18
+ margin-bottom: 0.5rem;
19
+ }
20
+ .subheader {
21
+ font-size: 1.2rem;
22
+ color: #3949AB;
23
+ text-align: center;
24
+ margin-bottom: 2rem;
25
+ }
26
+ .analysis-box {
27
+ background-color: #F8F9FA;
28
  padding: 20px;
29
  border-radius: 10px;
30
+ border-left: 4px solid #2E3A8C;
31
  margin: 20px 0;
32
+ }
33
+ .example-box {
34
+ background-color: #E3F2FD;
35
+ padding: 15px;
36
+ border-radius: 8px;
37
+ margin: 10px 0;
38
  border: 1px solid #BBDEFB;
39
+ }
40
+ .warning-box {
41
+ background-color: #FFF3E0;
42
+ padding: 15px;
43
+ border-radius: 8px;
44
+ border-left: 4px solid #FF9800;
45
+ margin: 20px 0;
46
  }
47
  </style>
48
  """, unsafe_allow_html=True)
49
 
50
+ # Header
51
+ st.markdown('<p class="main-header">πŸ“œ Samvidhan AI</p>', unsafe_allow_html=True)
52
+ st.markdown('<p class="subheader">Constitutional Law Assistant for India</p>', unsafe_allow_html=True)
53
+
54
+ # Safe API key handling
55
+ api_key = None
56
+ try:
57
+ api_key = st.secrets.get("GOOGLE_API_KEY", None)
58
+ if api_key:
59
+ genai.configure(api_key=api_key)
60
+ # st.success("βœ… API configured successfully")
61
+ except Exception as e:
62
+ st.error(f"❌ Error accessing API configuration: {str(e)}")
63
+ st.info("Please ensure GOOGLE_API_KEY is set in Hugging Face Spaces Secrets (Settings β†’ Secrets)")
64
+
65
+ def get_constitutional_analysis(scenario):
66
+ """Generate constitutional analysis using Google Gemini"""
67
+
68
+ if not api_key:
69
+ return "❌ API key not configured. Please contact the space administrator."
70
+
71
+ try:
72
+ model = genai.GenerativeModel('gemini-1.5-flash')
73
+
74
+ prompt = f"""
75
+ You are a Constitutional law expert specializing in the Constitution of India.
76
+ Provide a comprehensive, factual, and unbiased analysis of the following scenario:
77
+
78
+ **Scenario:** {scenario}
79
 
80
+ **Please provide a detailed analysis including:**
81
+
82
+ 1. **Relevant Constitutional Articles**: List specific articles with exact numbers and brief descriptions
83
+ 2. **Legal Framework**: Explain how these constitutional provisions apply to this scenario
84
+ 3. **Possible Interpretations**: Discuss different legal perspectives and potential outcomes
85
+ 4. **Judicial Precedents**: Mention any relevant Supreme Court or High Court cases if applicable
86
+ 5. **Constitutional Balance**: Explain any competing rights or principles involved
87
+ 6. **Practical Implications**: What this means in real-world legal terms
88
+ 7. **Areas of Uncertainty**: Any ambiguous aspects or evolving jurisprudence
89
+
90
+ **Format your response with clear headings and use simple language that a non-lawyer can understand.**
91
+ **Be objective and present multiple viewpoints where applicable.**
92
+ """
93
+
94
+ response = model.generate_content(prompt)
95
+ return response.text
96
+
97
+ except Exception as e:
98
+ return f"❌ Error generating analysis: {str(e)}\n\nPlease check your API configuration or try again later."
99
+
100
+ # Main application
101
  if not api_key:
102
+ st.error("πŸ” **API Key Not Configured**")
103
+ st.markdown("""
104
+ <div class="warning-box">
105
+ <strong>Setup Required:</strong><br>
106
+ This application requires a Google API Key to function. Please contact the space administrator to configure the GOOGLE_API_KEY in the Hugging Face Spaces secrets.
107
+ </div>
108
+ """, unsafe_allow_html=True)
109
  st.stop()
110
 
111
+ # Example scenarios
112
+ st.markdown("## πŸ’‘ Example Constitutional Scenarios")
113
+ st.markdown("Choose from these examples or write your own scenario:")
114
 
115
  examples = [
116
+ {
117
+ "title": "Free Speech vs Public Order",
118
+ "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?"
119
+ },
120
+ {
121
+ "title": "Religious Freedom in Education",
122
+ "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?"
123
+ },
124
+ {
125
+ "title": "Reservation Policy Challenge",
126
+ "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?"
127
+ },
128
+ {
129
+ "title": "Property Rights & Land Acquisition",
130
+ "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?"
131
+ },
132
+ {
133
+ "title": "Emergency Powers",
134
+ "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?"
135
+ },
136
+ {
137
+ "title": "Right to Privacy vs National Security",
138
+ "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?"
139
+ }
140
  ]
141
 
142
+ # Create expandable sections for examples
143
+ with st.expander("πŸ“‹ View Example Scenarios"):
144
+ for i, example in enumerate(examples, 1):
145
+ st.markdown(f"**{i}. {example['title']}**")
146
+ st.markdown(f"<div class='example-box'>{example['scenario']}</div>", unsafe_allow_html=True)
147
 
148
+ # Scenario selection
149
+ selected_example = st.selectbox(
150
+ "Select an example or choose 'Custom' to write your own:",
151
+ ["Custom Scenario"] + [f"{example['title']}" for example in examples]
152
+ )
153
+
154
+ # Text area for scenario
155
+ if selected_example == "Custom Scenario":
156
+ scenario = st.text_area(
157
+ "πŸ“ Describe your constitutional law scenario:",
158
+ height=200,
159
+ placeholder="Example: A government employee wants to participate in a political protest during office hours. The administration prohibits this citing service rules. Can the employee claim this violates their fundamental rights?",
160
+ help="Describe a situation involving constitutional law, fundamental rights, government powers, or legal disputes."
161
+ )
162
  else:
163
+ # Find the selected example
164
+ selected_scenario = next((ex['scenario'] for ex in examples if ex['title'] == selected_example), "")
165
+ scenario = st.text_area(
166
+ "πŸ“ Selected scenario (you can modify it):",
167
+ value=selected_scenario,
168
+ height=200
169
+ )
170
+
171
+ # Analysis button
172
+ col1, col2, col3 = st.columns([1, 2, 1])
173
+ with col2:
174
+ analyze_button = st.button("πŸ” **Analyze Constitutional Implications**", type="primary", use_container_width=True)
175
+
176
+ # Generate analysis
177
+ if analyze_button:
178
+ if scenario and scenario.strip():
179
+ with st.spinner("πŸ”„ Analyzing constitutional aspects... This may take a moment."):
180
+ analysis = get_constitutional_analysis(scenario.strip())
181
+
182
+ st.markdown("---")
183
+ st.markdown("## πŸ“œ **Constitutional Analysis**")
184
+ st.markdown(f'<div class="analysis-box">{analysis}</div>', unsafe_allow_html=True)
185
+
186
+ # Add download option
187
+ st.download_button(
188
+ label="πŸ“„ Download Analysis",
189
+ data=f"Constitutional Analysis\n\nScenario: {scenario}\n\nAnalysis:\n{analysis}",
190
+ file_name="constitutional_analysis.txt",
191
+ mime="text/plain"
192
+ )
193
  else:
194
  st.warning("⚠️ Please enter a scenario to analyze.")
195
 
196
  # Sidebar
197
  with st.sidebar:
198
+ st.markdown("### πŸ“œ About Samvidhan AI")
199
+ st.info("""
200
+ **Samvidhan AI** is an AI-powered assistant that helps analyze constitutional law scenarios based on the Indian Constitution.
201
 
202
+ **Features:**
203
+ - Constitutional article references
204
+ - Legal precedent analysis
205
+ - Multiple perspective analysis
206
+ - Plain language explanations
207
+ """)
208
 
209
+ st.markdown("### 🎯 How to Use")
210
+ st.markdown("""
211
+ 1. **Choose** from example scenarios or write your own
212
+ 2. **Click** the analyze button
213
+ 3. **Review** the detailed constitutional analysis
214
+ 4. **Download** the analysis if needed
215
+ """)
216
+
217
+ st.markdown("### βš–οΈ Legal Disclaimer")
218
+ st.warning("""
219
+ **Important:** This tool provides educational information only and should not be considered as legal advice.
220
+
221
+ For actual legal matters, please consult with a qualified lawyer or legal professional.
222
+ """)
223
+
224
+ st.markdown("### πŸ”§ System Status")
225
+ if api_key:
226
+ if st.button("πŸ§ͺ Test API Connection"):
227
+ with st.spinner("Testing..."):
228
+ try:
229
+ test_model = genai.GenerativeModel('gemini-1.5-flash')
230
+ test_response = test_model.generate_content("What is Article 21 of the Indian Constitution?")
231
+ if test_response.text and len(test_response.text) > 50:
232
+ st.success("βœ… API connection successful!")
233
+ else:
234
+ st.warning("⚠️ API response seems incomplete")
235
+ except Exception as e:
236
+ st.error(f"❌ API test failed: {str(e)}")
237
+ else:
238
+ st.error("❌ API not configured")
239
 
240
  st.markdown("---")
241
+ st.markdown("**Built with:** Streamlit + Google Gemini")
242
+ st.markdown("**Deployed on:** πŸ€— Hugging Face Spaces")
243
+
244
+ # Footer
245
+ st.markdown("---")
246
+ st.markdown(
247
+ """
248
+ <div style='text-align: center; color: #666;'>
249
+ <p>πŸ“œ Samvidhan AI - Making Constitutional Law Accessible</p>
250
+ <p>Built with ❀️ for constitutional awareness in India</p>
251
+ </div>
252
+ """,
253
+ unsafe_allow_html=True
254
+ )