pythonflaskclipsclipspy

How to get a fact value in clipspy and store it in a python variable


Say I have inserted a rule :

(defrule matching
    (fever ?fever)
    (headache ?headache)
    (disease (fever ?fever) (disname ?disname1) (headache ?headache))
    =>
    (assert (dis ?disname1)))

Now I want to fetch the value of ?disname1 into a python variable so that I can display it on a webpage,

Flask code -

import clips
from flask import Flask , render_template ,request
app = Flask(__name__)

env = clips.Environment()

env.load("clips.clp")

env.reset()



@app.route('/')
def home():
   return render_template('main.html')

@app.route('/result' , methods = ['POST', 'GET'])
def result():
    if request.method == 'POST':
        if  request.form.get('fever'):
            env.assert_string("(fever true) ")

        if request.form.get('headache'):
            env.assert_string("(headache true)")
            
        
        rule = """ (defrule matching 
                      (fever ?fever) (headache ?headache) 
                        (disease (fever ?fever) (disname ?disname1) (headache ?headache))
                        =>
                          (assert ( dis ?disname1 )) """

        env.build(rule)
       
        

    return render_template('next.html')

env.run()

if __name__ == '__main__':
   app.run(debug= True)

So after the rule is build ( dis ?disname) is asserted as a fact into clips so now ,I want to retrieve the value of ?disname which will give me the illness a person is facing , into a python variable so that I can pass it to html template and display it.


Solution

  • You can access to the environment facts via the facts iterator.

    Depending whether the fact is ordered or unordered you can access to its content via indexes or keys.

    for fact in env.facts():
        if fact.template.name == 'dis':
            print(fact[0])
    

    Regarding your question in the comments, it depends on your application. In your case, I would recommend to use facts to represent the decision outcome. Expert systems knowledge is represented by facts and therefore it's a good fit.

    You can use the generated knowledge to further reason and activate more rules which, for example, could react to the fact the User is ill and take actions accordingly.