File size: 8,441 Bytes
54ce02f
437d774
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54ce02f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437d774
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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)