Chintan Donda commited on
Commit
d2ef46d
1 Parent(s): 35c01e8

Updating Mandi Price widget to auto-populate sub-dropdown lists based on the selection of the above dropdown

Browse files
Files changed (4) hide show
  1. app.py +152 -50
  2. src/constants.py +40 -65
  3. src/langchain_utils.py +23 -23
  4. src/mandi_price.py +83 -2
app.py CHANGED
@@ -27,7 +27,8 @@ class DomState:
27
  self.answer = ''
28
  self.summary = ''
29
  self.mandi_price = ''
30
- self.mandi_from_date = (datetime.datetime.now() - datetime.timedelta(days=5)).strftime('%Y-%m-%d')
 
31
  self.mandi_to_date = datetime.datetime.now().strftime('%Y-%m-%d')
32
  self.weather_info = ''
33
  self.weather_forecast = ''
@@ -86,29 +87,6 @@ class DomState:
86
  return self.answer
87
 
88
 
89
- def click_handler_for_mandi_price(
90
- self,
91
- state_name,
92
- apmc_name,
93
- commodity_name,
94
- from_date,
95
- to_date
96
- ):
97
- if state_name and apmc_name and commodity_name and from_date and to_date:
98
- self.mandi_price = self.kkms_kssw_obj.mandi_utils_obj.get_mandi_price(state_name, apmc_name, commodity_name, from_date, to_date)
99
-
100
- # NOTE: Below code is only to display Mandi Prices in Gradio front-end. It could be removed when Engineering team writes a wrapper on top of app.py.
101
- self.mandi_price = sorted(self.mandi_price['data'], key=lambda x: x.get('created_at', ''), reverse=True)
102
- mandi_price = ''
103
- for ids in self.mandi_price:
104
- mandi_price += f'='*100 + '\n'
105
- for id, val in ids.items():
106
- mandi_price += '%-30s: %s\n' % (id, val)
107
- self.mandi_price = mandi_price
108
-
109
- return self.mandi_price
110
-
111
-
112
  def click_handler_for_get_weather(
113
  self,
114
  city
@@ -176,6 +154,62 @@ class DomState:
176
  return self.kkms_kssw_obj.weather_utils_obj.get_weather_forecast(state, district)
177
 
178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  def click_handler_for_feedback(
180
  self,
181
  question_category,
@@ -370,9 +404,11 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
370
  label="Select Question Category",
371
  value=constants_utils.INDEX_CATEGORY[0]
372
  )
 
373
  question = gr.Textbox(label="Enter your question", placeholder='Type the question here')
374
  # Get the Relevant paragraphs for the question asked
375
  relevant_paragraphs = gr.Textbox(label="Relevant paragraphs are:", value=dom.relevant_paragraphs, interactive=False)
 
376
  b_relevant_paragraphs = gr.Button("Get Relevant paragraphs").style(size='sm')
377
  b_relevant_paragraphs.click(
378
  fn=dom.click_handler_for_get_relevant_paragraphs,
@@ -384,6 +420,7 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
384
  with gr.Tab(label='Sources of relevant paragraphs'):
385
  # Get the Sources of relevant paragraphs
386
  sources_relevant_paragraphs = gr.Textbox(label="Sources of relevant paragraphs are:", interactive=False)
 
387
  relevant_paragraphs.change(
388
  dom.click_handler_for_relevant_paragraphs_source,
389
  relevant_paragraphs,
@@ -394,6 +431,7 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
394
  with gr.Column(scale=1, min_width=600):
395
  with gr.Tab(label='Answer'):
396
  answer = gr.Textbox(label="Answer is:", value=dom.answer, interactive=False)
 
397
  relevant_paragraphs.change(
398
  dom.click_handler_for_get_answer,
399
  [relevant_paragraphs, question],
@@ -409,14 +447,22 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
409
  label="Select language",
410
  value=list(constants_utils.INDIC_LANGUAGE.keys())[0]
411
  )
 
412
  indic_lang_answer = gr.Textbox(label="Answer in the selected language is:", interactive=False)
 
 
413
  answer.change(
414
- dom.click_handler_for_get_indic_translation,
415
- answer,
416
- indic_lang_answer
417
- )
418
- b_indic_lang_answer = gr.Button("Get answer in selected language").style(size='sm')
419
- b_indic_lang_answer.click(fn=dom.click_handler_for_get_indic_translation, inputs=[answer, language], outputs=[indic_lang_answer])
 
 
 
 
 
420
 
421
  with gr.Column(scale=1, min_width=600):
422
  with gr.Tab(label='Feedback'):
@@ -425,12 +471,13 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
425
  [
426
  "Correct",
427
  "Incorrect",
428
- "Partially Correct and contains irrelevant text",
429
  "Correct but not complete",
 
430
  ],
431
  label="Answer is",
432
  value="Correct"
433
  )
 
434
  b_feedback = gr.Button("Submit Feedback").style(size='sm')
435
  b_feedback.click(
436
  fn=dom.click_handler_for_feedback,
@@ -444,38 +491,84 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
444
  with gr.Column(scale=1, min_width=600):
445
  chatbot = gr.Chatbot()
446
  msg = gr.Textbox()
447
- submit = gr.Button("Submit")
448
- clear = gr.Button("Clear")
449
- submit.click(
450
- dom.kkms_kssw_obj.langchain_utils_obj.user, [msg, chatbot], [msg, chatbot]
451
- ).then(dom.kkms_kssw_obj.langchain_utils_obj.bot, chatbot, chatbot)
452
- clear.click(
453
- dom.kkms_kssw_obj.langchain_utils_obj.clear_history, None, chatbot, queue=False)
 
 
 
454
 
455
 
456
  #############################################################################
457
  # Widget for Mandi Price
458
  with gr.Row(visible=False) as rowMandiPrice:
459
  with gr.Column(scale=1, min_width=600):
460
- # Select State
461
  state_name = gr.Dropdown(
462
- constants_utils.MANDI_PRICE_STATES,
463
- label="Select state",
464
- value=constants_utils.MANDI_PRICE_STATES[0]
465
  )
466
- # APMC name
467
- apmc_name = gr.Textbox(label="Enter APMC name", placeholder='Type the APMC name here')
468
- # APMC name
469
- commodity_name = gr.Textbox(label="Enter Commodity name", placeholder='Type the Commodity name here')
470
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
  # From/To date in yyyy-mm-dd format
472
- from_date = gr.Textbox(label="From date?", value=dom.mandi_from_date, placeholder='Please enter the From date here in yyyy-mm-dd format')
473
- to_date = gr.Textbox(label="To date?", value=dom.mandi_to_date, placeholder='Please enter the To date here in yyyy-mm-dd format')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
 
475
  with gr.Column(scale=1, min_width=600):
476
  mandi_price = gr.Textbox(label=f"Mandi Price is:", value=dom.mandi_price, interactive=False)
 
 
 
 
 
 
 
477
  b_summary = gr.Button("Get Mandi Price").style(size='sm')
478
- b_summary.click(fn=dom.click_handler_for_mandi_price, inputs=[state_name, apmc_name, commodity_name, from_date, to_date], outputs=[mandi_price])
479
 
480
 
481
  #############################################################################
@@ -516,6 +609,7 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
516
  with gr.Tab(label='Weather Forecast Summary'):
517
  # Get the summary of the weather forecast
518
  weather_forecast_summary = gr.Textbox(label="Weather Forecast Summary is:", interactive=False)
 
519
  district.change(
520
  dom.click_handler_for_weather_forecast_summary,
521
  district_weather,
@@ -531,6 +625,7 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
531
  label="Select language",
532
  value=list(constants_utils.INDIC_LANGUAGE.keys())[0]
533
  )
 
534
  indic_weather_forecast_summary = gr.Textbox(label="Weather Forecast Summary in the selected language is:", interactive=False)
535
 
536
  # By default display weather forecast summary in Hindi. User can change it later on.
@@ -574,12 +669,14 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
574
  with gr.Row(visible=True) as rowUploadPdf:
575
  with gr.Column(scale=1, min_width=600):
576
  file_output = gr.File()
 
577
  upload_button = gr.UploadButton(
578
  "Click to Upload PDF Files",
579
  file_types=['.pdf'],
580
  file_count="multiple"
581
  )
582
  upload_button.upload(dom._upload_file, upload_button, file_output)
 
583
  b_files = gr.Button("Load PDF Files").style(size='sm')
584
  b_files.click(
585
  fn=dom.click_handler_for_load_files_urls,
@@ -589,6 +686,7 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
589
  with gr.Row(visible=False) as rowUploadOnlinePdf:
590
  with gr.Column(scale=1, min_width=600):
591
  urls = gr.Textbox(label="Enter URLs for Online PDF (Supports uploading from multiple URLs. Enter the URLs in comma (,) separated format.)", placeholder='Type the URLs here')
 
592
  b_urls = gr.Button("Load Online PDFs").style(size='sm')
593
  b_urls.click(
594
  fn=dom.click_handler_for_load_files_urls,
@@ -598,12 +696,14 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
598
  with gr.Row(visible=False) as rowUploadTextFile:
599
  with gr.Column(scale=1, min_width=600):
600
  file_output = gr.File()
 
601
  upload_button = gr.UploadButton(
602
  "Click to Upload Text Files",
603
  file_types=['.txt'],
604
  file_count="multiple"
605
  )
606
  upload_button.upload(dom._upload_file, upload_button, file_output)
 
607
  b_files = gr.Button("Load Text Files").style(size='sm')
608
  b_files.click(
609
  fn=dom.click_handler_for_load_files_urls,
@@ -613,6 +713,7 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
613
  with gr.Row(visible=False) as rowUploadUrls:
614
  with gr.Column(scale=1, min_width=600):
615
  urls = gr.Textbox(label="Enter URLs (Supports uploading from multiple URLs. Enter the URLs in comma (,) separated format.)", placeholder='Type the URLs here')
 
616
  b_urls = gr.Button("Load URLs").style(size='sm')
617
  b_urls.click(
618
  fn=dom.click_handler_for_load_files_urls,
@@ -637,6 +738,7 @@ with gr.Blocks(title='KKMS-Smart-Search-Demo') as demo:
637
  with gr.Column(scale=1, min_width=600):
638
  with gr.Tab(label='Following PDFs, Text files, and URLs have been ingested and indexed in the Knowledge Base and are available for querying.'):
639
  kb_sources = gr.Textbox(label=f"Data loaded from:", value=dom.kb_sources, interactive=False)
 
640
  b_kb_sources = gr.Button("Display Data Sources").style(size='sm')
641
  b_kb_sources.click(
642
  fn=dom.click_handler_for_get_kb_sources,
 
27
  self.answer = ''
28
  self.summary = ''
29
  self.mandi_price = ''
30
+ # At max past 7 days of data can be fetched for Mandi price
31
+ self.mandi_from_date = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d')
32
  self.mandi_to_date = datetime.datetime.now().strftime('%Y-%m-%d')
33
  self.weather_info = ''
34
  self.weather_forecast = ''
 
87
  return self.answer
88
 
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  def click_handler_for_get_weather(
91
  self,
92
  city
 
154
  return self.kkms_kssw_obj.weather_utils_obj.get_weather_forecast(state, district)
155
 
156
 
157
+ def click_handler_for_mandi_price(
158
+ self,
159
+ state_name,
160
+ apmc_name,
161
+ commodity,
162
+ from_date,
163
+ to_date
164
+ ):
165
+ if state_name and apmc_name and commodity and from_date and to_date:
166
+ self.mandi_price = self.kkms_kssw_obj.mandi_utils_obj.get_mandi_price(state_name, apmc_name, commodity, from_date, to_date)
167
+
168
+ # NOTE: Below code is only to display Mandi Prices in Gradio front-end. It could be removed when Engineering team writes a wrapper on top of app.py.
169
+ if isinstance(self.mandi_price, dict) and 'data' in self.mandi_price:
170
+ self.mandi_price = sorted(self.mandi_price['data'], key=lambda x: x.get('created_at', ''), reverse=True)
171
+ mandi_price = ''
172
+ for ids in self.mandi_price:
173
+ mandi_price += f'='*100 + '\n'
174
+ for id, val in ids.items():
175
+ mandi_price += '%-30s: %s\n' % (id, val)
176
+ self.mandi_price = mandi_price
177
+ else:
178
+ self.mandi_price = f'Mandi Price for {state_name} - {apmc_name} - {commodity} - from {from_date} to {to_date} is not available. Please select the correct State name, APMC name, Commodity with different dates.'
179
+ else:
180
+ self.mandi_price = 'Please select all the fields State name, APMC name, Commodity and from-to dates.'
181
+
182
+ return self.mandi_price
183
+
184
+
185
+ def click_handler_for_mandi_price_apmc_name_dropdown_list_update(
186
+ self,
187
+ state_name,
188
+ apmc_name
189
+ ):
190
+ return gr.update(
191
+ choices=self.kkms_kssw_obj.mandi_utils_obj.get_mandi_apmcs(state_name)
192
+ )
193
+
194
+
195
+ def click_handler_for_mandi_price_commodity_dropdown_list_update(
196
+ self,
197
+ state_name,
198
+ apmc_name,
199
+ from_date,
200
+ to_date,
201
+ commodity
202
+ ):
203
+ return gr.update(
204
+ choices=self.kkms_kssw_obj.mandi_utils_obj.get_mandi_commodity(
205
+ state_name,
206
+ apmc_name,
207
+ from_date,
208
+ to_date
209
+ )
210
+ )
211
+
212
+
213
  def click_handler_for_feedback(
214
  self,
215
  question_category,
 
404
  label="Select Question Category",
405
  value=constants_utils.INDEX_CATEGORY[0]
406
  )
407
+
408
  question = gr.Textbox(label="Enter your question", placeholder='Type the question here')
409
  # Get the Relevant paragraphs for the question asked
410
  relevant_paragraphs = gr.Textbox(label="Relevant paragraphs are:", value=dom.relevant_paragraphs, interactive=False)
411
+
412
  b_relevant_paragraphs = gr.Button("Get Relevant paragraphs").style(size='sm')
413
  b_relevant_paragraphs.click(
414
  fn=dom.click_handler_for_get_relevant_paragraphs,
 
420
  with gr.Tab(label='Sources of relevant paragraphs'):
421
  # Get the Sources of relevant paragraphs
422
  sources_relevant_paragraphs = gr.Textbox(label="Sources of relevant paragraphs are:", interactive=False)
423
+
424
  relevant_paragraphs.change(
425
  dom.click_handler_for_relevant_paragraphs_source,
426
  relevant_paragraphs,
 
431
  with gr.Column(scale=1, min_width=600):
432
  with gr.Tab(label='Answer'):
433
  answer = gr.Textbox(label="Answer is:", value=dom.answer, interactive=False)
434
+
435
  relevant_paragraphs.change(
436
  dom.click_handler_for_get_answer,
437
  [relevant_paragraphs, question],
 
447
  label="Select language",
448
  value=list(constants_utils.INDIC_LANGUAGE.keys())[0]
449
  )
450
+
451
  indic_lang_answer = gr.Textbox(label="Answer in the selected language is:", interactive=False)
452
+
453
+ # Automatically translate answer in the selected language upon change in the answer
454
  answer.change(
455
+ dom.click_handler_for_get_indic_translation,
456
+ answer,
457
+ indic_lang_answer
458
+ )
459
+
460
+ # Automatically translate answer in the selected language upon change in the language selection
461
+ language.change(
462
+ dom.click_handler_for_get_indic_translation,
463
+ [answer, language],
464
+ indic_lang_answer
465
+ )
466
 
467
  with gr.Column(scale=1, min_width=600):
468
  with gr.Tab(label='Feedback'):
 
471
  [
472
  "Correct",
473
  "Incorrect",
 
474
  "Correct but not complete",
475
+ "Partially Correct and also contains irrelevant text",
476
  ],
477
  label="Answer is",
478
  value="Correct"
479
  )
480
+
481
  b_feedback = gr.Button("Submit Feedback").style(size='sm')
482
  b_feedback.click(
483
  fn=dom.click_handler_for_feedback,
 
491
  with gr.Column(scale=1, min_width=600):
492
  chatbot = gr.Chatbot()
493
  msg = gr.Textbox()
494
+
495
+ with gr.Row():
496
+ submit = gr.Button("Submit")
497
+ submit.click(
498
+ dom.kkms_kssw_obj.langchain_utils_obj.user, [msg, chatbot], [msg, chatbot]
499
+ ).then(dom.kkms_kssw_obj.langchain_utils_obj.bot, chatbot, chatbot)
500
+
501
+ clear = gr.Button("Clear")
502
+ clear.click(
503
+ dom.kkms_kssw_obj.langchain_utils_obj.clear_history, None, chatbot, queue=False)
504
 
505
 
506
  #############################################################################
507
  # Widget for Mandi Price
508
  with gr.Row(visible=False) as rowMandiPrice:
509
  with gr.Column(scale=1, min_width=600):
510
+ # Select State name
511
  state_name = gr.Dropdown(
512
+ list(constants_utils.MANDI_PRICE_STATES_IDS.keys()),
513
+ label="Select state name",
514
+ value=list(constants_utils.MANDI_PRICE_STATES_IDS.keys())[0]
515
  )
516
+
517
+ # Select APMC Name
518
+ apmc_name = gr.Dropdown(
519
+ choices=[],
520
+ label="Select APMC Name"
521
+ )
522
+
523
+ # Select Commodity
524
+ commodity = gr.Dropdown(
525
+ choices=[],
526
+ label="Select Commodity"
527
+ )
528
+
529
+ # Get APMC of the selected state name
530
+ state_name.change(
531
+ dom.click_handler_for_mandi_price_apmc_name_dropdown_list_update,
532
+ state_name,
533
+ apmc_name
534
+ )
535
+
536
  # From/To date in yyyy-mm-dd format
537
+ from_date = gr.Textbox(label="From date", value=dom.mandi_from_date, placeholder='Please enter the From date here in yyyy-mm-dd format')
538
+ to_date = gr.Textbox(label="To date", value=dom.mandi_to_date, placeholder='Please enter the To date here in yyyy-mm-dd format')
539
+
540
+ # Get Commodity of the selected State name - APMC name - From/To Date
541
+ apmc_name.change(
542
+ dom.click_handler_for_mandi_price_commodity_dropdown_list_update,
543
+ [state_name, apmc_name, from_date, to_date],
544
+ commodity
545
+ )
546
+
547
+ # NOTE: Commodity changes whenever there is a change in From/To date selection
548
+ from_date.change(
549
+ dom.click_handler_for_mandi_price_commodity_dropdown_list_update,
550
+ [state_name, apmc_name, from_date, to_date],
551
+ commodity
552
+ )
553
+
554
+ # NOTE: Commodity changes whenever there is a change in From/To date selection
555
+ to_date.change(
556
+ dom.click_handler_for_mandi_price_commodity_dropdown_list_update,
557
+ [state_name, apmc_name, from_date, to_date],
558
+ commodity
559
+ )
560
 
561
  with gr.Column(scale=1, min_width=600):
562
  mandi_price = gr.Textbox(label=f"Mandi Price is:", value=dom.mandi_price, interactive=False)
563
+
564
+ commodity.change(
565
+ dom.click_handler_for_mandi_price,
566
+ [state_name, apmc_name, commodity, from_date, to_date],
567
+ mandi_price
568
+ )
569
+
570
  b_summary = gr.Button("Get Mandi Price").style(size='sm')
571
+ b_summary.click(fn=dom.click_handler_for_mandi_price, inputs=[state_name, apmc_name, commodity, from_date, to_date], outputs=[mandi_price])
572
 
573
 
574
  #############################################################################
 
609
  with gr.Tab(label='Weather Forecast Summary'):
610
  # Get the summary of the weather forecast
611
  weather_forecast_summary = gr.Textbox(label="Weather Forecast Summary is:", interactive=False)
612
+
613
  district.change(
614
  dom.click_handler_for_weather_forecast_summary,
615
  district_weather,
 
625
  label="Select language",
626
  value=list(constants_utils.INDIC_LANGUAGE.keys())[0]
627
  )
628
+
629
  indic_weather_forecast_summary = gr.Textbox(label="Weather Forecast Summary in the selected language is:", interactive=False)
630
 
631
  # By default display weather forecast summary in Hindi. User can change it later on.
 
669
  with gr.Row(visible=True) as rowUploadPdf:
670
  with gr.Column(scale=1, min_width=600):
671
  file_output = gr.File()
672
+
673
  upload_button = gr.UploadButton(
674
  "Click to Upload PDF Files",
675
  file_types=['.pdf'],
676
  file_count="multiple"
677
  )
678
  upload_button.upload(dom._upload_file, upload_button, file_output)
679
+
680
  b_files = gr.Button("Load PDF Files").style(size='sm')
681
  b_files.click(
682
  fn=dom.click_handler_for_load_files_urls,
 
686
  with gr.Row(visible=False) as rowUploadOnlinePdf:
687
  with gr.Column(scale=1, min_width=600):
688
  urls = gr.Textbox(label="Enter URLs for Online PDF (Supports uploading from multiple URLs. Enter the URLs in comma (,) separated format.)", placeholder='Type the URLs here')
689
+
690
  b_urls = gr.Button("Load Online PDFs").style(size='sm')
691
  b_urls.click(
692
  fn=dom.click_handler_for_load_files_urls,
 
696
  with gr.Row(visible=False) as rowUploadTextFile:
697
  with gr.Column(scale=1, min_width=600):
698
  file_output = gr.File()
699
+
700
  upload_button = gr.UploadButton(
701
  "Click to Upload Text Files",
702
  file_types=['.txt'],
703
  file_count="multiple"
704
  )
705
  upload_button.upload(dom._upload_file, upload_button, file_output)
706
+
707
  b_files = gr.Button("Load Text Files").style(size='sm')
708
  b_files.click(
709
  fn=dom.click_handler_for_load_files_urls,
 
713
  with gr.Row(visible=False) as rowUploadUrls:
714
  with gr.Column(scale=1, min_width=600):
715
  urls = gr.Textbox(label="Enter URLs (Supports uploading from multiple URLs. Enter the URLs in comma (,) separated format.)", placeholder='Type the URLs here')
716
+
717
  b_urls = gr.Button("Load URLs").style(size='sm')
718
  b_urls.click(
719
  fn=dom.click_handler_for_load_files_urls,
 
738
  with gr.Column(scale=1, min_width=600):
739
  with gr.Tab(label='Following PDFs, Text files, and URLs have been ingested and indexed in the Knowledge Base and are available for querying.'):
740
  kb_sources = gr.Textbox(label=f"Data loaded from:", value=dom.kb_sources, interactive=False)
741
+
742
  b_kb_sources = gr.Button("Display Data Sources").style(size='sm')
743
  b_kb_sources.click(
744
  fn=dom.click_handler_for_get_kb_sources,
src/constants.py CHANGED
@@ -1,6 +1,7 @@
1
  import os
2
  import src.web_crawler as web_crawler_utils
3
  import src.weather as weather_utils
 
4
 
5
  # Wheater to load the existing index store or create from scratch?
6
  LOAD_FROM_EXISTING_INDEX_STORE = True
@@ -51,45 +52,23 @@ DATA_SOURCES = {
51
 
52
  # LangChain related constants
53
  SIMILARITY_TOP_K = 1
 
54
  MODE = 'embedding'
55
  RESPONSE_MODE = 'default'
56
  TEXT_SPLITTER_CHUNK_SIZE = 1000
57
  TEXT_SPLITTER_CHUNK_OVERLAP = 0
58
  TEXT_SPLITTER_SEPARATOR = '\n\n'
59
 
 
 
 
60
 
61
- URLS = [
62
- # Govt. Schemes
63
- 'https://agricoop.nic.in/en/Major#gsc.tab=0'
64
- 'https://agricoop.nic.in/#gsc.tab=0',
65
-
66
- 'https://dmi.gov.in/Documents/GrantCAGrapes.pdf',
67
- 'https://dmi.gov.in/Documents/organicfaq.pdf',
68
- 'https://dmi.gov.in/Documents/CAGMOrganic-III.pdf',
69
- 'https://dmi.gov.in/GradesStandard.aspx',
70
- 'https://www.india.gov.in/topics/agriculture',
71
- 'https://www.india.gov.in/farmers-portal',
72
-
73
- # Pest Management related
74
- 'https://niphm.gov.in/IPMPackages/Maize.pdf',
75
-
76
- # Banned Pesticides
77
- 'https://ppqs.gov.in/divisions/cib-rc/registered-products', # Online PDF links on the page
78
-
79
- # Mandi Price related
80
- 'https://agmarknet.gov.in/',
81
-
82
- # General information related: Information of interests are present on the 2nd level url
83
- 'https://www.manage.gov.in/nf/nf.asp',
84
-
85
- # Weather forecast related
86
- 'https://nwp.imd.gov.in/blf/blf_temp/', # need to select state -> district (on the new page) -> displays detailed table -> can get info at the block level as well from the same page on selection
87
- 'https://nwp.imd.gov.in/blf/blf_temp/dis.php?value=12gujarat', # to get weather forecast for the given state
88
- 'https://nwp.imd.gov.in/blf/blf_temp/block.php?dis=12BHAVNAGAR', # to get the weather forecast for the given district
89
- ]
90
-
91
 
92
  # Supported Indian laguages for translating the English text to Indian language
 
93
  INDIC_LANGUAGE = {
94
  'Hindi': 'hi',
95
  'Gujarati': 'gu',
@@ -102,41 +81,6 @@ INDIC_LANGUAGE = {
102
  'Malayalam': 'ml',
103
  }
104
 
105
- # State list used in the Mandi Price widget dropdown list
106
- MANDI_PRICE_STATES = [
107
- 'ANDAMAN AND NICOBAR ISLANDS',
108
- 'ANDHRA PRADESH',
109
- 'ASSAM',
110
- 'BIHAR',
111
- 'CHANDIGARH',
112
- 'CHHATTISGARH',
113
- 'GOA',
114
- 'GUJARAT',
115
- 'HARYANA',
116
- 'HIMACHAL PRADESH',
117
- 'JAMMU AND KASHMIR',
118
- 'JHARKHAND',
119
- 'KARNATAKA',
120
- 'KERALA',
121
- 'MADHYA PRADESH',
122
- 'MAHARASHTRA',
123
- 'NAGALAND',
124
- 'ODISHA',
125
- 'PUDUCHERRY',
126
- 'PUNJAB',
127
- 'RAJASTHAN',
128
- 'TAMIL NADU',
129
- 'TELANGANA',
130
- 'TRIPURA',
131
- 'UTTAR PRADESH',
132
- 'UTTARAKHAND',
133
- 'WEST BENGAL'
134
- ]
135
-
136
- # State list used in the Weather forecast widget dropdown list
137
- weather_utils_obj = weather_utils.WEATHER()
138
- WEATHER_FORECAST_STATE_CODES = weather_utils_obj.get_state_names_codes()
139
-
140
  # LIST OF PESTICIDES WHICH ARE BANNED AND RESTRICTED USE (List created from: https://pib.gov.in/PressReleaseIframePage.aspx?PRID=1896140)
141
  BANNED_PESTICIDES_FORMULATIONS = [
142
  'Alachlor',
@@ -152,3 +96,34 @@ BANNED_PESTICIDES_FORMULATIONS = [
152
  'Copper Acetoarsenite',
153
  ]
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import src.web_crawler as web_crawler_utils
3
  import src.weather as weather_utils
4
+ import src.mandi_price as mandi_utils
5
 
6
  # Wheater to load the existing index store or create from scratch?
7
  LOAD_FROM_EXISTING_INDEX_STORE = True
 
52
 
53
  # LangChain related constants
54
  SIMILARITY_TOP_K = 1
55
+ ANSWER_SIMILARITY_TOP_K = 3
56
  MODE = 'embedding'
57
  RESPONSE_MODE = 'default'
58
  TEXT_SPLITTER_CHUNK_SIZE = 1000
59
  TEXT_SPLITTER_CHUNK_OVERLAP = 0
60
  TEXT_SPLITTER_SEPARATOR = '\n\n'
61
 
62
+ # State list used in the Mandi Price widget dropdown list
63
+ mandi_utils_obj = mandi_utils.MANDI_PRICE()
64
+ MANDI_PRICE_STATES_IDS = mandi_utils_obj.get_mandi_states()
65
 
66
+ # State list used in the Weather forecast widget dropdown list
67
+ weather_utils_obj = weather_utils.WEATHER()
68
+ WEATHER_FORECAST_STATE_CODES = weather_utils_obj.get_state_names_codes()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  # Supported Indian laguages for translating the English text to Indian language
71
+ # NOTE: Add mappings here to add the support for any other Indic language
72
  INDIC_LANGUAGE = {
73
  'Hindi': 'hi',
74
  'Gujarati': 'gu',
 
81
  'Malayalam': 'ml',
82
  }
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  # LIST OF PESTICIDES WHICH ARE BANNED AND RESTRICTED USE (List created from: https://pib.gov.in/PressReleaseIframePage.aspx?PRID=1896140)
85
  BANNED_PESTICIDES_FORMULATIONS = [
86
  'Alachlor',
 
96
  'Copper Acetoarsenite',
97
  ]
98
 
99
+ # URLs used by FTAs at different KCCs
100
+ URLS = [
101
+ # Govt. Schemes
102
+ 'https://agricoop.nic.in/en/Major#gsc.tab=0'
103
+ 'https://agricoop.nic.in/#gsc.tab=0',
104
+
105
+ 'https://dmi.gov.in/Documents/GrantCAGrapes.pdf',
106
+ 'https://dmi.gov.in/Documents/organicfaq.pdf',
107
+ 'https://dmi.gov.in/Documents/CAGMOrganic-III.pdf',
108
+ 'https://dmi.gov.in/GradesStandard.aspx',
109
+ 'https://www.india.gov.in/topics/agriculture',
110
+ 'https://www.india.gov.in/farmers-portal',
111
+
112
+ # Pest Management related
113
+ 'https://niphm.gov.in/IPMPackages/Maize.pdf',
114
+
115
+ # Banned Pesticides
116
+ 'https://ppqs.gov.in/divisions/cib-rc/registered-products', # Online PDF links on the page
117
+
118
+ # Mandi Price related
119
+ 'https://enam.gov.in/web/dashboard/trade-data', # Currently Mandi Price widget fetches data from this url
120
+ 'https://agmarknet.gov.in/',
121
+
122
+ # General information related: Information of interests are present on the 2nd level url
123
+ 'https://www.manage.gov.in/nf/nf.asp',
124
+
125
+ # Weather forecast related
126
+ 'https://nwp.imd.gov.in/blf/blf_temp/', # need to select state -> district (on the new page) -> displays detailed table -> can get info at the block level as well from the same page on selection
127
+ 'https://nwp.imd.gov.in/blf/blf_temp/dis.php?value=12gujarat', # to get weather forecast for the given state
128
+ 'https://nwp.imd.gov.in/blf/blf_temp/block.php?dis=12BHAVNAGAR', # to get the weather forecast for the given district
129
+ ]
src/langchain_utils.py CHANGED
@@ -82,28 +82,6 @@ class LANGCHAIN_UTILS:
82
  self.index_category_doc_type_wise_data_sources = {}
83
 
84
 
85
- def generate_prompt_template(
86
- self,
87
- prompt_type='general'
88
- ):
89
- prompt_template = ''
90
-
91
- if prompt_type == 'general':
92
- prompt_template = """Write a concise summary of the following:
93
-
94
- {text}
95
-
96
- SUMMARIZE IN ENGLISH:"""
97
-
98
- elif prompt_type == 'weather':
99
- prompt_template = """
100
- What would be the weather based on the below data:
101
- {text}
102
- """
103
-
104
- return prompt_template
105
-
106
-
107
  def user(
108
  self,
109
  user_message,
@@ -140,6 +118,28 @@ class LANGCHAIN_UTILS:
140
  return None
141
 
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  def get_textual_summary(
144
  self,
145
  text,
@@ -213,7 +213,7 @@ class LANGCHAIN_UTILS:
213
  )
214
 
215
  # Search for the similar docs
216
- docs = docsearch.similarity_search(question, k=3)
217
 
218
  llm = OpenAI(temperature=0)
219
  # Create a Chain for question answering
 
82
  self.index_category_doc_type_wise_data_sources = {}
83
 
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  def user(
86
  self,
87
  user_message,
 
118
  return None
119
 
120
 
121
+ def generate_prompt_template(
122
+ self,
123
+ prompt_type='general'
124
+ ):
125
+ prompt_template = ''
126
+
127
+ if prompt_type == 'general':
128
+ prompt_template = """Write a concise summary of the following:
129
+
130
+ {text}
131
+
132
+ SUMMARIZE IN ENGLISH:"""
133
+
134
+ elif prompt_type == 'weather':
135
+ prompt_template = """
136
+ What would be the weather based on the below data:
137
+ {text}
138
+ """
139
+
140
+ return prompt_template
141
+
142
+
143
  def get_textual_summary(
144
  self,
145
  text,
 
213
  )
214
 
215
  # Search for the similar docs
216
+ docs = docsearch.similarity_search(question, k=constants_utils.ANSWER_SIMILARITY_TOP_K)
217
 
218
  llm = OpenAI(temperature=0)
219
  # Create a Chain for question answering
src/mandi_price.py CHANGED
@@ -3,9 +3,9 @@ import requests
3
 
4
  class MANDI_PRICE:
5
  def __init__(self):
 
6
  self.base_url = "https://enam.gov.in/web/Ajax_ctrl/trade_data_list"
7
- # "https://enam.gov.in/web/dashboard/trade-data",
8
- # "https://enam.gov.in/web/dashboard/trade_data_list",
9
 
10
 
11
  def get_mandi_price(self,
@@ -31,3 +31,84 @@ class MANDI_PRICE:
31
  )
32
 
33
  return response.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  class MANDI_PRICE:
5
  def __init__(self):
6
+ # Base URL to get the Mandi Price details
7
  self.base_url = "https://enam.gov.in/web/Ajax_ctrl/trade_data_list"
8
+ # self.base_url = "https://enam.gov.in/web/dashboard/trade-data"
 
9
 
10
 
11
  def get_mandi_price(self,
 
31
  )
32
 
33
  return response.json()
34
+
35
+
36
+ def get_mandi_states(
37
+ self
38
+ ):
39
+ base_url = 'https://enam.gov.in/web/ajax_ctrl/states_name'
40
+ headers = {
41
+ 'Accept': 'application/json, text/javascript, */*; q=0.01',
42
+ }
43
+
44
+ response = requests.get(
45
+ base_url,
46
+ headers=headers,
47
+ )
48
+
49
+ response = response.json()
50
+ response = response.get('data', [])
51
+ # state_names = [i for i in map(lambda x: x.get('state_name', ''), response)]
52
+ state_names_ids = {}
53
+ for state in response:
54
+ if state.get('state_name', ''):
55
+ state_names_ids[state.get('state_name')] = state.get('state_id', '')
56
+
57
+ return state_names_ids
58
+
59
+
60
+ def get_mandi_apmcs(
61
+ self,
62
+ state_name
63
+ ):
64
+ base_url = 'https://enam.gov.in/web/Ajax_ctrl/apmc_list'
65
+ headers = {
66
+ "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
67
+ "Referer": "https://enam.gov.in/web/dashboard/trade-data",
68
+ "Accept": "application/json, text/javascript, */*; q=0.01",
69
+ }
70
+ payload = f'state_id={self.get_mandi_states().get(state_name)}'
71
+
72
+ response = requests.post(
73
+ base_url,
74
+ data=payload,
75
+ headers=headers
76
+ )
77
+
78
+ response = response.json()
79
+ response = response.get('data', [])
80
+ # apmc_names = [i for i in map(lambda x: x.get('apmc_name', ''), response)]
81
+ apmc_names_ids = {}
82
+ for apmc in response:
83
+ if apmc.get('apmc_name', ''):
84
+ apmc_names_ids[apmc.get('apmc_name')] = apmc.get('apmc_id', '')
85
+
86
+ return list(apmc_names_ids.keys())
87
+
88
+
89
+ def get_mandi_commodity(
90
+ self,
91
+ state_name,
92
+ apmc_name,
93
+ from_date,
94
+ to_date
95
+ ):
96
+ base_url = 'https://enam.gov.in/web/Ajax_ctrl/commodity_list'
97
+ headers = {
98
+ "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
99
+ "Accept": "application/json, text/javascript, */*; q=0.01",
100
+ "Referer": "https://enam.gov.in/web/dashboard/trade-data"
101
+ }
102
+ payload = f'language=en&stateName={state_name}&apmcName={apmc_name}&fromDate={from_date}&toDate={to_date}'
103
+
104
+ response = requests.post(
105
+ base_url,
106
+ data=payload,
107
+ headers=headers
108
+ )
109
+
110
+ response = response.json()
111
+ commodity_names_ids = response.get('data', [])
112
+ commodity_list = [i for i in map(lambda x: x.get('commodity', ''), commodity_names_ids)]
113
+ return commodity_list
114
+