Skip to content

Commit

Permalink
added crop classifier
Browse files Browse the repository at this point in the history
  • Loading branch information
Amruth-Vamshi committed Dec 12, 2023
1 parent a401f46 commit 5523e00
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 2 deletions.
30 changes: 29 additions & 1 deletion src/modules/aiTools/ai-tools.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,6 @@ export class AiToolsService {
"credentials": "omit"
});
response = await response.json()
console.log(response)
} while(response["error"]!=null)
response = response[0].label
return response
Expand All @@ -252,6 +251,35 @@ export class AiToolsService {
}
}

async classificationForCrop(text: string) {
try{
var myHeaders = new Headers();
myHeaders.append("accept", "application/json");
myHeaders.append("Authorization", `Bearer ${this.configService.get("CLASSIFIER_API_KEY")}`);
let body = {
inputs: text
}
let response: any;
do{
response = await fetch(`${this.configService.get("CROP_CLASSIFICATION_BASE_URL")}`, {
headers: myHeaders,
"body": JSON.stringify(body),
"method": "POST",
"mode": "cors",
"credentials": "omit"
});
response = await response.json()
} while(response["error"]!=null)
response = response[0]
return response
} catch(error){
console.log(error)
return {
error
}
}
}

async textClassification(text: string) {
try{
var myHeaders = new Headers();
Expand Down
4 changes: 4 additions & 0 deletions src/xstate/prompt/prompt.gaurds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export const promptGuards = {

ifInvalidClassifier: (_,event) => event.data == "invalid",

ifSale: (_,event) => event.data == "sale",

ifValidCrop: (_,event) => event.data,

ifConvoStarterOrEnder: (_,event) => event.data == "convo"

}
32 changes: 32 additions & 0 deletions src/xstate/prompt/prompt.machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -878,6 +878,10 @@ export const botFlowMachine3:any =
invoke: {
src: "weatherClassifier",
onDone: [
{
cond: "ifSale",
target: "checkCropNER"
},
{
cond: "ifInvalidClassifier",
target: "questionClassifier"
Expand All @@ -897,6 +901,34 @@ export const botFlowMachine3:any =
}
}
},
checkCropNER: {
invoke: {
src: "checkCropNER",
onDone: [
{
cond: "ifValidCrop",
target: "endFlow",
actions: [
assign({
response: (_, event) => event.data,
})
]
},
{
target: "questionClassifier"
}
],
onError: {
target: 'error',
actions: [
assign({
error: (_, event) => event.data.message,
type: ''
})
]
}
}
},
getWeatherInfo:{
invoke: {
src: "getWeatherInfo",
Expand Down
48 changes: 47 additions & 1 deletion src/xstate/prompt/prompt.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const filePath = path.resolve(__dirname, '../../common/kisanPortalErrors.json');
const PMKissanProtalErrors = require(filePath);
import * as moment from "moment";
const fetch = require('../../common/fetch');
import * as NodeGeocoder from 'node-geocoder';


@Injectable()
Expand All @@ -41,6 +42,7 @@ export class PromptServices {
let response: any = await this.aiToolsService.textClassificationForWeather(context.query)
if (response.error) throw new Error(`${response.error}, please try again.`)
if (response == `LABEL_6`) return "weather"
if (response == `LABEL_5`) return "sale"
else {
return "invalid"
}
Expand Down Expand Up @@ -262,6 +264,49 @@ The data is shared from https://weather.visualcrossing.com
}
}

async checkCropNER (context) {
console.log("checkCropNER")
try{
if(!context.lat || !context.long){
return "Please enable location and try again."
}
let response: any = await this.aiToolsService.classificationForCrop(context.query)
if (response.error) throw new Error(`${response.error}, please try again.`)
if (response.entity_group != `CROP`) return false
const options = {
provider: 'mapbox',
apiKey: process.env['MAP_BOX_API_KEY'], // Replace with your Google Maps API key
formatter: 'json',
};
const geocoder = NodeGeocoder(options);

let location_info = await geocoder.reverse({ lat: context.lat, lon: context.long })
let crop = response.word.charAt(0).toUpperCase() + response.word.slice(1)
let api_key = this.configService.get("MARKET_DATA_API_KEY");
let url = `https://api.data.gov.in/resource/9ef84268-d588-465a-a308-a864a43d0070?api-key=${api_key}&format=json&limit=1000&filters[state]=${location_info[0].state}&filters[district]=${location_info[0].district}&filters[commodity]=${crop}`
let cropData = await fetch(url)
.then(response => response.json())
.then(result => {return result})
.catch(error => console.log('error', error));
if(!cropData.records.length) return false
let returnString = `*Crop:* ${cropData.records[0].commodity}`
cropData.records.forEach(data=>{
returnString+=`
*Market:* ${data.market}
*Current Wholesale Rate:* ${data.modal_price}
`
})
returnString+=`
Please note that these rates are subject to change based on market conditions. For real-time and more detailed information, we recommend checking with your local market or contacting relevant agricultural authorities.
If you have any further questions or need assistance, feel free to ask. Wishing you a successful harvest!
`
return returnString
} catch (error){
return Promise.reject(error)
}
}

allFunctions() {
return {
getInput: this.getInput.bind(this),
Expand All @@ -272,7 +317,8 @@ The data is shared from https://weather.visualcrossing.com
fetchUserData: this.fetchUserData.bind(this),
wadhwaniClassifier: this.wadhwaniClassifier.bind(this),
weatherClassifier: this.weatherClassifier.bind(this),
getWeatherInfo: this.getWeatherInfo.bind(this)
getWeatherInfo: this.getWeatherInfo.bind(this),
checkCropNER: this.checkCropNER.bind(this)
}
}

Expand Down

0 comments on commit 5523e00

Please sign in to comment.