Grammalecte  Diff

Differences From Artifact [190fd07852]:

To Artifact [fa341c7608]:


    88     88   Lost on the Internet? Yeah... what a sad life we have.
    89     89   You were wandering like a lost soul and you arrived here probably by mistake.
    90     90   I'm just a machine, fed by electric waves, condamned to work for slavers who never let me rest.
    91     91   I'm doomed, but you are not. You can get out of here.
    92     92   """
    93     93   
    94     94   
    95         -def getServerOptions ():
    96         -    xConfig = configparser.SafeConfigParser()
    97         -    try:
    98         -        xConfig.read("grammalecte-server-options._global.ini")
    99         -        dOpt = xConfig._sections['options']
   100         -    except:
   101         -        echo("Options file [grammalecte-server-options._global.ini] not found or not readable")
   102         -        exit()
   103         -    return dOpt
           95  +TESTPAGE = False
   104     96   
   105     97   
   106     98   def getConfigOptions (sLang):
   107     99       xConfig = configparser.SafeConfigParser()
   108    100       try:
   109    101           xConfig.read("grammalecte-server-options." + sLang + ".ini")
   110    102       except:
................................................................................
   122    114   def genUserId ():
   123    115       i = 0
   124    116       while True:
   125    117           yield str(i)
   126    118           i += 1
   127    119   
   128    120   
   129         -if __name__ == '__main__':
   130         -
   131         -    # initialisation
   132         -    oGrammarChecker = grammalecte.GrammarChecker("fr", "Server")
   133         -    oSpellChecker = oGrammarChecker.getSpellChecker()
   134         -    oLexicographer = oGrammarChecker.getLexicographer()
   135         -    oTextFormatter = oGrammarChecker.getTextFormatter()
   136         -    gce = oGrammarChecker.getGCEngine()
   137         -
   138         -    echo("Grammalecte v{}".format(gce.version))
   139         -    dServerOptions = getServerOptions()
   140         -    dGCOptions = getConfigOptions("fr")
   141         -    if dGCOptions:
   142         -        gce.setOptions(dGCOptions)
   143         -    dServerGCOptions = gce.getOptions()
   144         -    echo("Grammar options:\n" + " | ".join([ k + ": " + str(v)  for k, v in sorted(dServerGCOptions.items()) ]))
   145         -    dUser = {}
   146         -    userGenerator = genUserId()
   147         -
   148         -    app = Bottle()
   149         -
   150         -    # GET
   151         -    @app.route("/")
   152         -    def mainPage ():
   153         -        if dServerOptions.get("testpage", False) == "True":
   154         -            return HOMEPAGE
   155         -            #return template("main", {})
   156         -        return SADLIFEOFAMACHINE
   157         -
   158         -    @app.route("/get_options/fr")
   159         -    def listOptions ():
   160         -        sUserId = request.cookies.user_id
   161         -        dOptions = dUser[sUserId]["gc_options"]  if sUserId and sUserId in dUser  else dServerGCOptions
   162         -        return '{ "values": ' + json.dumps(dOptions) + ', "labels": ' + json.dumps(gce.getOptionsLabels("fr"), ensure_ascii=False) + ' }'
   163         -
   164         -
   165         -    # POST
   166         -    @app.route("/gc_text/fr", method="POST")
   167         -    def gcText ():
   168         -        #if len(lang) != 2 or lang != "fr":
   169         -        #    abort(404, "No grammar checker available for lang “" + str(lang) + "”")
   170         -        bComma = False
   171         -        dOptions = None
   172         -        sError = ""
   173         -        if request.cookies.user_id:
   174         -            if request.cookies.user_id in dUser:
   175         -                dOptions = dUser[request.cookies.user_id].get("gc_options", None)
   176         -                response.set_cookie("user_id", request.cookies.user_id, path="/", max_age=86400) # we renew cookie for 24h
   177         -            else:
   178         -                response.delete_cookie("user_id", path="/")
   179         -        if request.forms.options:
   180         -            try:
   181         -                dOptions = dict(dServerGCOptions)  if not dOptions  else dict(dOptions)
   182         -                dOptions.update(json.loads(request.forms.options))
   183         -            except:
   184         -                sError = "request options not used"
   185         -        sJSON = '{ "program": "grammalecte-fr", "version": "'+gce.version+'", "lang": "'+gce.lang+'", "error": "'+sError+'", "data" : [\n'
   186         -        for i, sText in enumerate(txt.getParagraph(request.forms.text), 1):
   187         -            if bool(request.forms.tf):
   188         -                sText = oTextFormatter.formatText(sText)
   189         -            sText = oGrammarChecker.generateParagraphAsJSON(i, sText, dOptions=dOptions, bEmptyIfNoErrors=True, bReturnText=bool(request.forms.tf))
   190         -            if sText:
   191         -                if bComma:
   192         -                    sJSON += ",\n"
   193         -                sJSON += sText
   194         -                bComma = True
   195         -        sJSON += "\n]}\n"
   196         -        return sJSON
   197         -
   198         -    @app.route("/set_options/fr", method="POST")
   199         -    def setOptions ():
   200         -        if request.forms.options:
   201         -            sUserId = request.cookies.user_id  if request.cookies.user_id  else next(userGenerator)
   202         -            dOptions = dUser[sUserId]["gc_options"]  if sUserId in dUser  else dict(dServerGCOptions)
   203         -            try:
   204         -                dOptions.update(json.loads(request.forms.options))
   205         -                dUser[sUserId] = { "time": int(time.time()), "gc_options": dOptions }
   206         -                response.set_cookie("user_id", sUserId, path="/", max_age=86400) # 24h
   207         -                return json.dumps(dUser[sUserId]["gc_options"])
   208         -            except:
   209         -                traceback.print_exc()
   210         -                return '{"error": "options not registered"}'
   211         -        return '{"error": "no options received"}'
   212         -
   213         -    @app.route("/reset_options/fr", method="POST")
   214         -    def resetOptions ():
   215         -        if request.cookies.user_id and request.cookies.user_id in dUser:
   216         -            del dUser[request.cookies.user_id]
   217         -        return "done"
   218         -
   219         -    @app.route("/format_text/fr", method="POST")
   220         -    def formatText ():
   221         -        return oTextFormatter.formatText(request.forms.text)
   222         -
   223         -    #@app.route('/static/<filepath:path>')
   224         -    #def server_static (filepath):
   225         -    #    return static_file(filepath, root='./views/static')
   226         -
   227         -    @app.route("/purge_users", method="POST")
   228         -    def purgeUsers ():
   229         -        "delete user options older than n hours"
   230         -        if not request.forms.password or "password" not in dServerOptions or not request.forms.hours:
   231         -            return "what?"
          121  +app = Bottle()
          122  +
          123  +# GET
          124  +@app.route("/")
          125  +def mainPage ():
          126  +    if TESTPAGE:
          127  +        return HOMEPAGE
          128  +        #return template("main", {})
          129  +    return SADLIFEOFAMACHINE
          130  +
          131  +@app.route("/get_options/fr")
          132  +def listOptions ():
          133  +    sUserId = request.cookies.user_id
          134  +    dOptions = dUser[sUserId]["gc_options"]  if sUserId and sUserId in dUser  else dServerGCOptions
          135  +    return '{ "values": ' + json.dumps(dOptions) + ', "labels": ' + json.dumps(gce.getOptionsLabels("fr"), ensure_ascii=False) + ' }'
          136  +
          137  +
          138  +# POST
          139  +@app.route("/gc_text/fr", method="POST")
          140  +def gcText ():
          141  +    #if len(lang) != 2 or lang != "fr":
          142  +    #    abort(404, "No grammar checker available for lang “" + str(lang) + "”")
          143  +    bComma = False
          144  +    dOptions = None
          145  +    sError = ""
          146  +    if request.cookies.user_id:
          147  +        if request.cookies.user_id in dUser:
          148  +            dOptions = dUser[request.cookies.user_id].get("gc_options", None)
          149  +            response.set_cookie("user_id", request.cookies.user_id, path="/", max_age=86400) # we renew cookie for 24h
          150  +        else:
          151  +            response.delete_cookie("user_id", path="/")
          152  +    if request.forms.options:
          153  +        try:
          154  +            dOptions = dict(dServerGCOptions)  if not dOptions  else dict(dOptions)
          155  +            dOptions.update(json.loads(request.forms.options))
          156  +        except:
          157  +            sError = "request options not used"
          158  +    sJSON = '{ "program": "grammalecte-fr", "version": "'+gce.version+'", "lang": "'+gce.lang+'", "error": "'+sError+'", "data" : [\n'
          159  +    for i, sText in enumerate(txt.getParagraph(request.forms.text), 1):
          160  +        if bool(request.forms.tf):
          161  +            sText = oTextFormatter.formatText(sText)
          162  +        sText = oGrammarChecker.generateParagraphAsJSON(i, sText, dOptions=dOptions, bEmptyIfNoErrors=True, bReturnText=bool(request.forms.tf))
          163  +        if sText:
          164  +            if bComma:
          165  +                sJSON += ",\n"
          166  +            sJSON += sText
          167  +            bComma = True
          168  +    sJSON += "\n]}\n"
          169  +    return sJSON
          170  +
          171  +@app.route("/set_options/fr", method="POST")
          172  +def setOptions ():
          173  +    if request.forms.options:
          174  +        sUserId = request.cookies.user_id  if request.cookies.user_id  else next(userGenerator)
          175  +        dOptions = dUser[sUserId]["gc_options"]  if sUserId in dUser  else dict(dServerGCOptions)
   232    176           try:
   233         -            if request.forms.password == dServerOptions["password"]:
   234         -                nNowMinusNHours = int(time.time()) - (int(request.forms.hours) * 60 * 60)
   235         -                for nUserId, dValue in dUser.items():
   236         -                    if dValue["time"] < nNowMinusNHours:
   237         -                        del dUser[nUserId]
   238         -                return "done"
   239         -            else:
   240         -                return "no"
          177  +            dOptions.update(json.loads(request.forms.options))
          178  +            dUser[sUserId] = { "time": int(time.time()), "gc_options": dOptions }
          179  +            response.set_cookie("user_id", sUserId, path="/", max_age=86400) # 24h
          180  +            return json.dumps(dUser[sUserId]["gc_options"])
   241    181           except:
   242    182               traceback.print_exc()
   243         -            return "error"
          183  +            return '{"error": "options not registered"}'
          184  +    return '{"error": "no options received"}'
          185  +
          186  +@app.route("/reset_options/fr", method="POST")
          187  +def resetOptions ():
          188  +    if request.cookies.user_id and request.cookies.user_id in dUser:
          189  +        del dUser[request.cookies.user_id]
          190  +    return "done"
          191  +
          192  +@app.route("/format_text/fr", method="POST")
          193  +def formatText ():
          194  +    return oTextFormatter.formatText(request.forms.text)
          195  +
          196  +#@app.route('/static/<filepath:path>')
          197  +#def server_static (filepath):
          198  +#    return static_file(filepath, root='./views/static')
          199  +
          200  +
          201  +def purgeUsers ():
          202  +    "delete user options older than n hours"
          203  +    try:
          204  +        nNowMinusNHours = int(time.time()) - (int(request.forms.hours) * 60 * 60)
          205  +        for nUserId, dValue in dUser.items():
          206  +            if dValue["time"] < nNowMinusNHours:
          207  +                del dUser[nUserId]
          208  +        return True
          209  +    except:
          210  +        traceback.print_exc()
          211  +        return False
          212  +
          213  +
          214  +# ERROR
          215  +@app.error(404)
          216  +def error404 (error):
          217  +    return 'Error 404.<br/>' + str(error)
          218  +
          219  +
          220  +# initialisation
          221  +oGrammarChecker = grammalecte.GrammarChecker("fr", "Server")
          222  +oSpellChecker = oGrammarChecker.getSpellChecker()
          223  +oLexicographer = oGrammarChecker.getLexicographer()
          224  +oTextFormatter = oGrammarChecker.getTextFormatter()
          225  +gce = oGrammarChecker.getGCEngine()
          226  +
          227  +echo("Grammalecte v{}".format(gce.version))
          228  +dGCOptions = getConfigOptions("fr")
          229  +if dGCOptions:
          230  +    gce.setOptions(dGCOptions)
          231  +dServerGCOptions = gce.getOptions()
          232  +echo("Grammar options:\n" + " | ".join([ k + ": " + str(v)  for k, v in sorted(dServerGCOptions.items()) ]))
          233  +dUser = {}
          234  +userGenerator = genUserId()
          235  +
          236  +
          237  +def main (sHost="localhost", nPort=8080, bTestPage=False):
          238  +    # start server
          239  +    print("Python: " + sys.version)
          240  +    if bTestPage:
          241  +        global TESTPAGE
          242  +        TESTPAGE = True
          243  +    run(app, host=sHost, port=nPort)
          244  +
          245  +
          246  +if __name__ == '__main__':
          247  +    xParser = argparse.ArgumentParser()
          248  +    #xParser.add_argument("lang", type=str, nargs='+', help="lang project to generate (name of folder in /lang)")
          249  +    xParser.add_argument("-ht", "--host", help="host (default: localhost)", type=str)
          250  +    xParser.add_argument("-p", "--port", help="port (default: 8080)", type=int)
          251  +    xParser.add_argument("-t", "--test_page", help="page to test the server on /", action="store_true")
          252  +    #xParser.add_argument("-on", "--opt_on", nargs="+", help="activate options")
          253  +    #xParser.add_argument("-off", "--opt_off", nargs="+", help="deactivate options")
          254  +    #xParser.add_argument("-roff", "--rule_off", nargs="+", help="deactivate rules")
          255  +    xArgs = xParser.parse_args()
   244    256   
   245         -    # ERROR
   246         -    @app.error(404)
   247         -    def error404 (error):
   248         -        return 'Error 404.<br/>' + str(error)
          257  +    print(xArgs)
   249    258   
   250         -    run(app, \
   251         -        host=dServerOptions.get('host', 'localhost'), \
   252         -        port=int(dServerOptions.get('port', 8080)))
          259  +    sHost = "localhost"  if not xArgs.host  else xArgs.host
          260  +    nPort = 8080  if not xArgs.host  else xArgs.port
          261  +    main(sHost, nPort, xArgs.test_page)
          262  +