AGRI_SCHEMES / app.py
AdityaAdaki
a
54ce02f
from flask import Flask, render_template, jsonify, request
import json
import re
import os
app = Flask(__name__)
def load_schemes():
with open('schemes.json', 'r') as f:
data = json.load(f)
schemes = {}
for scheme in data['schemes']:
scheme_id = scheme['name'].lower().replace(' ', '-').replace('(', '').replace(')', '').replace('.', '')
# Handle Exclusions formatting
if isinstance(scheme['Eligibility Criteria'], dict):
exclusions = scheme['Eligibility Criteria'].get('Exclusions', [])
if isinstance(exclusions, str):
# Convert string to list if it's a single string
exclusions = [exclusions]
scheme['Eligibility Criteria']['Exclusions'] = exclusions
# Generate keywords for filtering
keywords = []
# Extract keyword categories
if 'income' in scheme['Introduction'].lower():
keywords.append('income')
if 'insurance' in scheme['Introduction'].lower():
keywords.append('insurance')
if 'infrastructure' in scheme['Introduction'].lower():
keywords.append('infrastructure')
if 'irrigation' in scheme['Introduction'].lower() or 'water' in scheme['Introduction'].lower():
keywords.append('irrigation')
if 'organic' in scheme['Introduction'].lower():
keywords.append('organic')
if 'credit' in scheme['Introduction'].lower() or 'loan' in scheme['Introduction'].lower():
keywords.append('credit')
if 'market' in scheme['Introduction'].lower():
keywords.append('market')
if 'soil' in scheme['Introduction'].lower():
keywords.append('soil')
# Extract beneficiary types
beneficiary_text = ""
if isinstance(scheme['Eligibility Criteria'], dict):
if isinstance(scheme['Eligibility Criteria']['Eligible Beneficiaries'], list):
beneficiary_text = " ".join(scheme['Eligibility Criteria']['Eligible Beneficiaries'])
else:
beneficiary_text = scheme['Eligibility Criteria']['Eligible Beneficiaries']
else:
beneficiary_text = str(scheme['Eligibility Criteria'])
if 'all farmers' in beneficiary_text.lower():
keywords.append('all farmers')
if 'small' in beneficiary_text.lower() or 'marginal' in beneficiary_text.lower():
keywords.append('small')
if 'tenant' in beneficiary_text.lower():
keywords.append('tenant')
if 'sharecropper' in beneficiary_text.lower():
keywords.append('sharecroppers')
if 'fpo' in beneficiary_text.lower() or 'farmer producer' in beneficiary_text.lower():
keywords.append('fpo')
if 'landholding' in beneficiary_text.lower():
keywords.append('landholding')
# Extract benefit types
benefits_text = " ".join(scheme['Benefits']) if isinstance(scheme['Benefits'], list) else scheme['Benefits']
if 'financial' in benefits_text.lower():
keywords.append('financial')
if 'subsidy' in benefits_text.lower():
keywords.append('subsidy')
if 'insurance' in benefits_text.lower():
keywords.append('insurance')
if 'credit' in benefits_text.lower() or 'loan' in benefits_text.lower():
keywords.append('credit')
if 'income' in benefits_text.lower():
keywords.append('income')
if 'infrastructure' in benefits_text.lower():
keywords.append('infrastructure')
if 'training' in benefits_text.lower() or 'education' in benefits_text.lower():
keywords.append('training')
schemes[scheme_id] = {
'name': scheme['name'],
'introduction': scheme['Introduction'],
'objective': scheme['Objective'],
'benefits': scheme['Benefits'],
'eligibility': {
'eligible': (
[scheme['Eligibility Criteria']['Eligible Beneficiaries']]
if isinstance(scheme['Eligibility Criteria'], dict) and isinstance(scheme['Eligibility Criteria']['Eligible Beneficiaries'], str)
else scheme['Eligibility Criteria']['Eligible Beneficiaries']
if isinstance(scheme['Eligibility Criteria'], dict)
else [str(scheme['Eligibility Criteria'])]
),
'exclusions': (
scheme['Eligibility Criteria']['Exclusions']
if isinstance(scheme['Eligibility Criteria'], dict)
else []
)
},
'application_process': scheme['Application Process & Required Documents']['Application Process'],
'documents_required': scheme['Application Process & Required Documents']['Documents Required'],
'contact': {
'helpline': str(scheme['Helpline & Website'].get('Helpline Number', '')),
'email': str(scheme['Helpline & Website'].get('Email', '')),
'website': str(scheme['Helpline & Website'].get('Official Website', ''))
},
'keywords': ' '.join(keywords)
}
return schemes
schemes = load_schemes()
@app.route('/')
def index():
return render_template('index.html', schemes=schemes)
# Add this new route for the chatbot
@app.route('/chatbot')
def chatbot():
return render_template('chatbot.html')
# Add this new API endpoint to process chatbot queries
@app.route('/api/recommend', methods=['POST'])
def recommend_schemes():
data = request.json
answers = data.get('answers', {})
# Get farmer type
farmer_type = answers.get('farmer_type', '')
# Get farming interests
interests = answers.get('interests', [])
# Get financial needs
financial_needs = answers.get('financial_needs', [])
# Get region/state
region = answers.get('region', '')
# Get land area
land_area = answers.get('land_area', '')
# Algorithm to find matching schemes
recommended_schemes = []
for scheme_id, scheme in schemes.items():
score = 0
keywords = scheme['keywords'].lower()
# Check farmer type match
if farmer_type == 'small' and 'small' in keywords:
score += 3
elif farmer_type == 'tenant' and 'tenant' in keywords:
score += 3
elif farmer_type == 'fpo' and 'fpo' in keywords:
score += 3
elif farmer_type == 'all' and 'all farmers' in keywords:
score += 1
# Check interests
for interest in interests:
if interest in keywords:
score += 2
# Check financial needs
for need in financial_needs:
if need in keywords:
score += 2
# Only include schemes with a score of 2 or higher
if score >= 2:
recommended_schemes.append({
'id': scheme_id,
'name': scheme['name'],
'introduction': scheme['introduction'],
'score': score
})
# Sort schemes by score (highest first)
recommended_schemes.sort(key=lambda x: x['score'], reverse=True)
# Limit to top 5 schemes
recommended_schemes = recommended_schemes[:5]
return jsonify({
'schemes': recommended_schemes
})
@app.route('/scheme/<scheme_id>')
def scheme_details(scheme_id):
scheme = schemes.get(scheme_id)
if scheme:
return render_template('scheme_details.html', scheme=scheme)
return 'Scheme not found', 404
if __name__ == '__main__':
# Use the port defined by Hugging Face Spaces or default to 7860
port = int(os.environ.get('PORT', 7860))
# Set host to 0.0.0.0 to make it accessible externally
app.run(host='0.0.0.0', port=port)