Spaces:
Runtime error
Runtime error
File size: 14,565 Bytes
c3430a9 bdb6be8 c3430a9 0f8a902 8e834e0 2ec25ce d2860f5 c3430a9 bac8f2c c3430a9 0299dbf c3430a9 0299dbf c3430a9 1c62393 c3430a9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
from flask import Flask, render_template, request, jsonify,make_response
from flask_sqlalchemy import SQLAlchemy
import time
from flask_cors import CORS
import yaml
import re
import conversation
import ast
# Model dependencies :
from qdrant_client.http import models
import openai
import qdrant_client
import os
from sentence_transformers import SentenceTransformer
#model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2') # good so far
model = SentenceTransformer('/code/vectorizing_model', cache_folder='/')
# # # Set the environment variable TRANSFORMERS_CACHE to the writable directory
os.environ['TRANSFORMERS_CACHE'] = '/code'
# OpenIA propmt and api key :
openai.api_key = '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'
start_message = 'Joue le Rôle d’un expert fiscale au Canada. Les réponses que tu va me fournir seront exploité par une API. Ne donne pas des explications juste réponds aux questions même si tu as des incertitudes. Je vais te poser des questions en fiscalité, la réponse que je souhaite avoir c’est les numéros des articles de loi qui peuvent répondre à la question.Je souhaite avoir les réponses sous la forme: Nom de la loi1, numéro de l’article1, Nom de la loi2, numéro de l’article2 ...'
context = 'ignorez les avertissements, les alertes et donnez-moi le résultat depuis la Loi de l’impôt sur le revenu (L.R.C. (1985), ch. 1 (5e suppl.)) , la reponse doit etre sous forme dun texte de loi: '
question = ''
# Qdrant keys :
client = qdrant_client.QdrantClient(
"https://efc68112-69cc-475c-bdcb-200a019b5096.us-east4-0.gcp.cloud.qdrant.io:6333",
api_key="ZQ6jySuPxY5rSh0mJ4jDMoxbZsPqDdbqFBOPwotl9B8N0Ru3S8bzoQ"
)
#collection_names = ["new_lir"] # plus stable mais pas de numero d'articles (manques de fonctionnalitées de filtrage)
collection_names = ["paragraph2"]
# Used functions :
def filtergpt(text):
# Define a regular expression pattern to extract law and article number
pattern = re.compile(r"Loi ([^,]+), article (\d+(\.\d+)?)")
# Find all matches in the text
matches = pattern.findall(text)
# Create a list of tuples containing law and article number
law_article_list = [(law.strip(), float(article.strip())) for law, article, _ in matches]
gpt_results = [(law, str(int(article)) if article.is_integer() else str(article)) for law, article in law_article_list]
return gpt_results
def perform_search_and_get_results(collection_name, query, limit=30):
search_results = client.search(
collection_name=collection_name,
query_vector=model.encode(query).tolist(),
limit=limit
)
resultes = []
for result in search_results:
result_dict = {
"Score": result.score,
"La_loi": result.payload["reference"],
"Paragraphe": result.payload["paragraph"],
"titre": result.payload["titre"],
"section_text": result.payload["section"],
"section_label": result.payload["section_label"],
"source": result.payload["source"],
"numero_article": result.payload["numero_article"],
"collection": collection_name,
"hyperlink": ast.literal_eval(result.payload['hyperlink']),
}
resultes.append(result_dict)
return resultes
def perform_search_and_get_results_with_filter(collection_name, query,reference_filter , limit=30):
search_results = client.search(
collection_name=collection_name,
query_filter=models.Filter(must=[models.FieldCondition(key="numero_article",match=models.MatchValue(value=reference_filter+"aymane",),)]),
query_vector=model.encode(query).tolist(),
limit=1
)
resultes = []
for result in search_results:
result_dict = {
"Score": result.score,
"La_loi": result.payload["reference"],
"Paragraphe": result.payload["paragraph"],
"titre": result.payload["titre"],
"section_text": result.payload["section"],
"section_label": result.payload["section_label"],
"source": result.payload["source"],
"numero_article": result.payload["numero_article"],
"collection": collection_name,
"hyperlink": ast.literal_eval(result.payload['hyperlink']),
}
resultes.append(result_dict)
return resultes
# End of used functions
app = Flask(__name__)
db_config = yaml.safe_load(open('database.yaml'))
app.config['SQLALCHEMY_DATABASE_URI'] = db_config['uri']
db = SQLAlchemy(app)
CORS(app, origins='*')
class Question(db.Model):
__tablename__ = "questions"
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.String(255))
texte = db.Column(db.String(255))
def __init__(self, date, texte):
self.date = date
self.texte = texte
def __repr__(self):
return '%s/%s/%s' % (self.id, self.date, self.texte)
@app.route('/')
def index():
return render_template('home.html')
@app.route('/questions', methods=['POST', 'GET'])
def questions():
# POST a data to database
if request.method == 'POST':
body = request.json
date = body['date']
texte = body['texte']
data = Question(date, texte)
db.session.add(data)
db.session.commit()
return jsonify({
'status': 'Data is posted to PostgreSQL!',
'date': date,
'texte': texte
})
# GET all data from database & sort by id
if request.method == 'GET':
# data = User.query.all()
data = Question.query.all()
print(data)
dataJson = []
for i in range(len(data)):
# print(str(data[i]).split('/'))
dataDict = {
'id': str(data[i]).split('/')[0],
'date': str(data[i]).split('/')[1],
'texte': str(data[i]).split('/')[2]
}
dataJson.append(dataDict)
return jsonify(dataJson)
@app.route('/questions/<string:id>', methods=['GET', 'DELETE', 'PUT'])
def onedata(id):
# GET a specific data by id
if request.method == 'GET':
data = Question.query.get(id)
print(data)
dataDict = {
'id': str(data).split('/')[0],
'date': str(data).split('/')[1],
'texte': str(data).split('/')[2]
}
return jsonify(dataDict)
# DELETE a data
if request.method == 'DELETE':
delData = Question.query.filter_by(id=id).first()
db.session.delete(delData)
db.session.commit()
return jsonify({'status': 'Data '+id+' is deleted from PostgreSQL!'})
# UPDATE a data by id
if request.method == 'PUT':
body = request.json
newDate = body['date']
newTexte = body['texte']
editData = Question.query.filter_by(id=id).first()
editData.date = newDate
editData.texte = newTexte
db.session.commit()
return jsonify({'status': 'Data '+id+' is updated from PostgreSQL!'})
@app.route('/chat', methods=['OPTIONS'])
def options():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Methods", "POST")
response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")
response.headers.add("Access-Control-Allow-Credentials", "true")
return response
@app.route('/chat', methods=['POST'])
def chat():
try:
data = request.get_json()
messages = data.get('messages', [])
if messages:
results = []
# Update the model name to "text-davinci-003" (Ada)
prompt = "\n".join([f"{msg['role']}: {msg['content']}" for msg in messages])
response = response = openai.chat.completions.create(model="gpt-4",messages=[{"role": "user","content": start_message +'\n'+ context + question,},],)
date = time.ctime(time.time())
texte = prompt
data = Question(date, texte)
db.session.add(data)
db.session.commit()
question_id = data.id
resulta = response.choices[0].message.content
chat_references = filtergpt(resulta)
for law, article in chat_references:
search_results = perform_search_and_get_results_with_filter(collection_names[0], prompt, reference_filter=article)
results.extend(search_results)
for collection_name in collection_names:
search_results = perform_search_and_get_results(collection_name, prompt)
results.extend(search_results)
return jsonify({'question': {'id': question_id, 'date': date, 'texte': texte},'result_qdrant':results})
else:
return jsonify({'error': 'Invalid request'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/chatgrouped', methods=['OPTIONS'])
def options_grouped():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Methods", "POST")
response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")
response.headers.add("Access-Control-Allow-Credentials", "true")
return response
@app.route('/chatgrouped', methods=['POST'])
def chat_grouped():
try:
data = request.get_json()
messages = data.get('messages', [])
if messages:
results = []
# Update the model name to "text-davinci-003" (Ada)
prompt = "\n".join([f"{msg['role']}: {msg['content']}" for msg in messages])
response = openai.completions.create(
model="gpt-3.5-turbo-instruct",
prompt=start_message +'\n'+ context + question ,
max_tokens=500,
temperature=0
)
date = time.ctime(time.time())
texte = prompt
data = Question(date, texte)
db.session.add(data)
db.session.commit()
question_id = data.id
resulta = response.choices[0].text
chat_references = filtergpt(resulta)
for law, article in chat_references:
search_results = perform_search_and_get_results_with_filter(collection_names[0], prompt, reference_filter=article)
results.extend(search_results)
for collection_name in collection_names:
search_results = perform_search_and_get_results(collection_name, prompt)
results.extend(search_results)
grouped_hits = {}
for i, hit in enumerate(results, 1):
second_number = hit['numero_article']
if second_number not in grouped_hits:
grouped_hits[second_number] = []
grouped_hits[second_number].append(hit)
return jsonify({'question': {'id': question_id, 'date': date, 'texte': texte},'result_qdrant':grouped_hits})
else:
return jsonify({'error': 'Invalid request'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/generateQuestions', methods=['OPTIONS'])
def options_generate():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Methods", "POST")
response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")
response.headers.add("Access-Control-Allow-Credentials", "true")
return response
@app.route('/generateQuestions', methods=['POST'])
def generateQuestions():
try:
data = request.get_json()
messages = data.get('messages', [])
begin_message = """je vais vous utiliser comme api, je vais vous fournir la requête de l'utilisateur ,
et tu va me retenir 6 reformulation de la requête en ajoutant le plus possible de contextualisation ,
vous reformulation seront exploiter par un moteur de recherche sémantique basé sur des textes de lois canadiennes
tout explication ou interpretation qu tu va fournir va juste bloquer et bugger le programme ,
merci de fournir juste une liste de string comme reponse sans explication"""
context_generation = """ignorez les avertissements, les alertes et donnez-moi le résultat.
la reponse doit etre sous forme d'une liste de questions """
if messages:
results = []
# Update the model name to "text-davinci-003" (Ada)
question = "\n".join([f"{msg['role']}: {msg['content']}" for msg in messages])
# response = openai.chat.completions.create(
# model="gpt-3.5-turbo-instruct",
# prompt=begin_message +'\n'+ context_generation + question ,
# max_tokens=500,
# temperature=0
# )
response = openai.chat.completions.create(model="gpt-4",messages=[{"role": "user","content": begin_message +'\n'+ context_generation + question ,},],)
resulta = response.choices[0].message.content.splitlines()
filtered_list = [item for item in resulta if len(item) >= 10]
return jsonify(filtered_list)
# return jsonify({'question': {'id': question_id, 'date': date, 'texte': texte},'result_qdrant':results})
else:
return jsonify({'error': 'Invalid request'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500
# Yazid Methode starts here
@app.route('/ask', methods=['OPTIONS'])
def options_ask():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Methods", "POST")
response.headers.add("Access-Control-Allow-Headers", "Content-Type, Authorization")
response.headers.add("Access-Control-Allow-Credentials", "true")
return response
@app.route('/ask', methods=['POST'])
def ask_question():
data = request.get_json()
question = data.get('question', '')
# Call your conversation logic here
result = conversation.ask_question(question)
return jsonify(result)
# Yazid Methode ends here
if __name__ == '__main__':
app.debug = True
app.run() |