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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -116
app.py CHANGED
@@ -52,33 +52,27 @@ st.markdown('<p class="main-header">πŸ“œ Samvidhan AI</p>', unsafe_allow_html=Tr
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
@@ -86,32 +80,13 @@ def get_constitutional_analysis(scenario):
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",
@@ -139,54 +114,35 @@ examples = [
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
  )
@@ -195,60 +151,25 @@ if analyze_button:
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
- )
 
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 = st.secrets.get("GOOGLE_API_KEY", os.getenv("GOOGLE_API_KEY", ""))
56
+
57
+ if api_key:
58
+ try:
59
  genai.configure(api_key=api_key)
60
+ except Exception as e:
61
+ st.error(f"❌ Error configuring API: {str(e)}")
62
+ else:
63
+ st.warning("⚠️ API key not found. The analysis feature will be disabled.")
64
 
65
  def get_constitutional_analysis(scenario):
66
  """Generate constitutional analysis using Google Gemini"""
 
67
  if not api_key:
68
  return "❌ API key not configured. Please contact the space administrator."
 
69
  try:
70
  model = genai.GenerativeModel('gemini-1.5-flash')
 
71
  prompt = f"""
72
  You are a Constitutional law expert specializing in the Constitution of India.
73
  Provide a comprehensive, factual, and unbiased analysis of the following scenario:
 
74
  **Scenario:** {scenario}
 
75
  **Please provide a detailed analysis including:**
 
76
  1. **Relevant Constitutional Articles**: List specific articles with exact numbers and brief descriptions
77
  2. **Legal Framework**: Explain how these constitutional provisions apply to this scenario
78
  3. **Possible Interpretations**: Discuss different legal perspectives and potential outcomes
 
80
  5. **Constitutional Balance**: Explain any competing rights or principles involved
81
  6. **Practical Implications**: What this means in real-world legal terms
82
  7. **Areas of Uncertainty**: Any ambiguous aspects or evolving jurisprudence
 
 
 
83
  """
 
84
  response = model.generate_content(prompt)
85
  return response.text
 
86
  except Exception as e:
87
+ return f"❌ Error generating analysis: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
88
 
89
  # Example scenarios
 
 
 
90
  examples = [
91
  {
92
  "title": "Free Speech vs Public Order",
 
114
  }
115
  ]
116
 
117
+ # Example section
118
+ st.markdown("## πŸ’‘ Example Constitutional Scenarios")
119
  with st.expander("πŸ“‹ View Example Scenarios"):
120
  for i, example in enumerate(examples, 1):
121
  st.markdown(f"**{i}. {example['title']}**")
122
  st.markdown(f"<div class='example-box'>{example['scenario']}</div>", unsafe_allow_html=True)
123
 
 
124
  selected_example = st.selectbox(
125
  "Select an example or choose 'Custom' to write your own:",
126
+ ["Custom Scenario"] + [ex["title"] for ex in examples]
127
  )
128
 
 
129
  if selected_example == "Custom Scenario":
130
+ scenario = st.text_area("πŸ“ Describe your constitutional law scenario:", height=200)
 
 
 
 
 
131
  else:
 
132
  selected_scenario = next((ex['scenario'] for ex in examples if ex['title'] == selected_example), "")
133
+ scenario = st.text_area("πŸ“ Selected scenario (you can modify it):", value=selected_scenario, height=200)
 
 
 
 
134
 
135
  # Analysis button
136
+ if st.button("πŸ” **Analyze Constitutional Implications**", use_container_width=True):
137
+ if scenario.strip():
138
+ with st.spinner("πŸ”„ Analyzing constitutional aspects..."):
 
 
 
 
 
139
  analysis = get_constitutional_analysis(scenario.strip())
 
140
  st.markdown("---")
141
  st.markdown("## πŸ“œ **Constitutional Analysis**")
142
  st.markdown(f'<div class="analysis-box">{analysis}</div>', unsafe_allow_html=True)
 
 
143
  st.download_button(
144
  label="πŸ“„ Download Analysis",
145
+ data=f"Scenario:\n{scenario}\n\nAnalysis:\n{analysis}",
146
  file_name="constitutional_analysis.txt",
147
  mime="text/plain"
148
  )
 
151
 
152
  # Sidebar
153
  with st.sidebar:
154
+ st.info("**Samvidhan AI** helps analyze constitutional law scenarios in India.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  if api_key:
156
  if st.button("πŸ§ͺ Test API Connection"):
157
+ try:
158
+ model = genai.GenerativeModel('gemini-1.5-flash')
159
+ resp = model.generate_content("What is Article 21 of the Indian Constitution?")
160
+ if resp.text and len(resp.text) > 50:
161
+ st.success("βœ… API connection successful!")
162
+ else:
163
+ st.warning("⚠️ API response seems incomplete.")
164
+ except Exception as e:
165
+ st.error(f"❌ API test failed: {str(e)}")
 
166
  else:
167
+ st.error("❌ API not configured. Analysis disabled.")
168
+
169
+ # Hugging Face auto-run support
170
+ if __name__ == "__main__":
171
+ import sys
172
+ port = int(os.environ.get("PORT", 7860))
173
+ sys.argv = ["streamlit", "run", "app.py", "--server.port", str(port), "--server.address", "0.0.0.0"]
174
+ from streamlit.web import cli as stcli
175
+ sys.exit(stcli.main())