Skip to content

Commit

Permalink
added weather classifier
Browse files Browse the repository at this point in the history
  • Loading branch information
Amruth-Vamshi committed Dec 11, 2023
1 parent 671fa8e commit 2679e3a
Show file tree
Hide file tree
Showing 4 changed files with 138 additions and 3 deletions.
6 changes: 5 additions & 1 deletion src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ export class PromptDto {
conversationId?: string;
@IsOptional()
identifier?: string;
@IsOptional()
location?: any;
}

@Controller()
Expand Down Expand Up @@ -373,7 +375,9 @@ export class AppController {
inputLanguage: prompt.inputLanguage,
lastAadhaarDigits:'',
state:'onGoing',
isOTPVerified: false
isOTPVerified: false,
lat: prompt.input?.location?.lat,
long: prompt.input?.location?.long
}

let botFlowService = interpret(botFlowMachine.withContext(conversation || defaultContext)).start();
Expand Down
31 changes: 31 additions & 0 deletions src/modules/aiTools/ai-tools.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ export class AiToolsService {

let textArray = text.split("\n")
for(let i=0;i<textArray.length;i++){
textArray[i] = textArray[i].trim()
if(!textArray[i]) continue;
let response: any = await this.computeBhashini(
bhashiniConfig?.pipelineInferenceAPIEndPoint?.inferenceApiKey?.value,
"translation",
Expand Down Expand Up @@ -220,6 +222,35 @@ export class AiToolsService {
}
}

async textClassificationForWeather(text: string) {
try{
var myHeaders = new Headers();
myHeaders.append("accept", "application/json");
myHeaders.append("X-API-Key", `Bearer ${this.configService.get("CLASSIFIER_API_KEY")}`);
let body = {
text: text
}
let response: any;
do{
response = await fetch(`${this.configService.get("HUGGINGFACE_TEXT_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].label
return response
} catch(error){
console.log(error)
return {
error
}
}
}

async textClassification(text: string) {
try{
var myHeaders = new Headers();
Expand Down
53 changes: 51 additions & 2 deletions src/xstate/prompt/prompt.machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -786,7 +786,9 @@ export const botFlowMachine3:any =
state:'onGoing',
userId:'',
isOTPVerified: false,
isWadhwaniResponse: "false"
isWadhwaniResponse: "false",
lat: '',
long: '',
},
states: {
checkStateAndJump: {
Expand Down Expand Up @@ -838,7 +840,7 @@ export const botFlowMachine3:any =
]
},
{
target:"questionClassifier",
target:"questionClassifierWeather",
actions:[
assign({
userQuestion: (_,event) => event.data.query,
Expand Down Expand Up @@ -872,6 +874,53 @@ export const botFlowMachine3:any =
}
}
},
questionClassifierWeather: {
invoke: {
src: "weatherClassifier",
onDone: [
{
cond: "ifInvalidClassifier",
target: "questionClassifier"
},
{
target: 'getWeatherInfo'
}
],
onError: {
target: 'error',
actions: [
assign({
error: (_, event) => event.data.message,
type: ''
})
]
}
}
},
getWeatherInfo:{
invoke: {
src: "getWeatherInfo",
onDone: [
{
target: 'endFlow',
actions: [
assign({
response: (_, event) => event.data,
})
]
}
],
onError: {
target: 'error',
actions: [
assign({
error: (_, event) => event.data.message,
type: ''
})
]
}
}
},
questionClassifier: {
invoke: {
src: "questionClassifier",
Expand Down
51 changes: 51 additions & 0 deletions src/xstate/prompt/prompt.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ export class PromptServices {
async getInput (context) {
return context
}

async weatherClassifier(context) {
try{
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"
else {
return "invalid"
}
} catch (error){
return Promise.reject(error)
}
}

async questionClassifier (context) {
try{
Expand Down Expand Up @@ -206,6 +219,42 @@ export class PromptServices {
}
}

async getWeatherInfo (context) {
try{
if(!context.lat || !context.long){
return "Please enable location and try again."
}
var requestOptions: RequestInit= {
method: 'GET',
redirect: 'follow'
};

let weather: any = await fetch(`https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/${context.lat},${context.long}?unitGroup=metric&key=${this.configService.get('WEATHER_PROVIDER_API_KEY')}&contentType=json`, requestOptions)
.then(response => response.json())
.then(result => {return result})
.catch(error => console.log('error', error));
let weatherString = '🌦️ *Weather Forecast for the Next 10 Days*';
weather.days.slice(0,10).forEach((data,index)=>{
weatherString+=`
*Day ${index+1}:*
- Date: ${data.datetime}
- Temperature: ${data.temp}°C
- Conditions: ${data.conditions}
- Precipitation: ${data.precip*10}%
`
})
weatherString+=`
Feel free to reach out if you need more details or have any specific concerns. Happy farming! 🚜🌾
The data is shared from https://weather.visualcrossing.com
`
return weatherString
} catch (error){
return Promise.reject(error)
}
}

allFunctions() {
return {
getInput: this.getInput.bind(this),
Expand All @@ -215,6 +264,8 @@ export class PromptServices {
validateOTP: this.validateOTP.bind(this),
fetchUserData: this.fetchUserData.bind(this),
wadhwaniClassifier: this.wadhwaniClassifier.bind(this),
weatherClassifier: this.weatherClassifier.bind(this),
getWeatherInfo: this.getWeatherInfo.bind(this)
}
}

Expand Down

0 comments on commit 2679e3a

Please sign in to comment.