kadsai commited on
Commit
31a511c
·
verified ·
1 Parent(s): 4f0fd82

update print

Browse files
Files changed (1) hide show
  1. app.py +10 -19
app.py CHANGED
@@ -1,15 +1,14 @@
 
1
  import os
2
  import gradio as gr
3
  import logging
4
  import sqlite3
5
  from datetime import datetime
6
  from openai import OpenAI
7
-
8
  from langchain_openai import ChatOpenAI, OpenAIEmbeddings
9
  from langchain_chroma import Chroma
10
  from langchain.schema import HumanMessage, SystemMessage
11
  from tiktoken import encoding_for_model
12
-
13
  from fastapi import FastAPI, HTTPException
14
  from fastapi.middleware.cors import CORSMiddleware
15
  from pydantic import BaseModel
@@ -99,9 +98,9 @@ def respond(message, history, system_message, domain, model_name, max_tokens, te
99
  # Recherche avec score dans Chroma
100
  results_with_scores = collection.similarity_search_by_vector_with_relevance_scores(query_embedding, k=3)
101
 
102
- seuil = 0.75 # seuil de similarité à ajuster
103
  for doc, score in results_with_scores:
104
- print(f"SCORE: {score:.2f} - DOC: {doc.page_content[:80]}") # affiche le début du contenu
105
 
106
  # Filtrage des résultats selon le seuil
107
  filtered_results = [doc for doc, score in results_with_scores if score >= seuil]
@@ -139,13 +138,13 @@ def respond(message, history, system_message, domain, model_name, max_tokens, te
139
  except Exception as e:
140
  return [{"role": "assistant", "content": f"❌ Erreur : {e}"}]
141
 
142
- # -- Extraction OCR
143
-
144
  def image_to_base64(image):
145
  buffered = BytesIO()
146
  image.save(buffered, format="PNG") # ou "JPEG" si besoin
147
  return base64.b64encode(buffered.getvalue()).decode("utf-8")
148
 
 
149
  def extract_identity_card_info(image):
150
  try:
151
  base64_img = image_to_base64(image)
@@ -170,8 +169,7 @@ def extract_identity_card_info(image):
170
  except Exception as e:
171
  return f"Erreur lors de l'extraction : {e}"
172
 
173
- # Vehicle function
174
-
175
  def extract_vehicle_info(image):
176
  try:
177
  base64_img = image_to_base64(image)
@@ -196,8 +194,7 @@ def extract_vehicle_info(image):
196
  except Exception as e:
197
  return f"Erreur lors de l'extraction : {e}"
198
 
199
- # Plainte fucntion
200
-
201
  def classify_complaint(text):
202
  system_prompt = (
203
  "Tu es un assistant qui classe les plaintes des utilisateurs dans les catégories suivantes : "
@@ -248,7 +245,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color:
248
  label="🎛️ Choisissez un mode", value="chatbotAssistance"
249
  )
250
 
251
- # Bloc 1 - Chatbot
252
  with gr.Column(visible=True) as chatbot_mode_block:
253
  with gr.Row():
254
  domain = gr.Dropdown(
@@ -271,7 +268,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color:
271
  message_input = gr.Textbox(label="✉️ Votre message", placeholder="Tapez votre question ici...")
272
  send_button = gr.Button("🚀 Envoyer", variant="primary")
273
 
274
- # Bloc 2 - ID Extraction
275
  with gr.Column(visible=False) as id_extraction_block:
276
  gr.Markdown("🪪 **Extraction d'informations d'identité à partir d'image**")
277
  id_image_input = gr.File(label="Uploader image de pièce d'identité", file_types=["image"], file_count="multiple")
@@ -281,9 +278,6 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color:
281
  def extract_id_fn(files):
282
  if not files:
283
  return "❌ Aucun fichier reçu."
284
-
285
- # Si c'est un upload Gradio en mode fichier, files est une liste de chemins locaux
286
- # On prend la première image (carte d'identité)
287
  file_path = files[0]
288
 
289
  # Ouvrir l'image avec PIL
@@ -294,7 +288,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color:
294
 
295
  id_button.click(fn=extract_id_fn, inputs=[id_image_input], outputs=[id_output])
296
 
297
- # Bloc 3 - Car Detection
298
  with gr.Column(visible=False) as car_detection_block:
299
  gr.Markdown("🚗 **Analyse de véhicules à partir d'image**")
300
  car_image_input = gr.File(label="Uploader image de voiture", file_types=["image"], file_count="multiple")
@@ -304,9 +298,6 @@ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color:
304
  def car_detect_fn(files):
305
  if not files:
306
  return "❌ Aucun fichier reçu."
307
-
308
- # Si c'est un upload Gradio en mode fichier, files est une liste de chemins locaux
309
- # On prend la première image (carte d'identité)
310
  file_path = files[0]
311
 
312
  # Ouvrir l'image avec PIL
 
1
+ # -- Import Sectio
2
  import os
3
  import gradio as gr
4
  import logging
5
  import sqlite3
6
  from datetime import datetime
7
  from openai import OpenAI
 
8
  from langchain_openai import ChatOpenAI, OpenAIEmbeddings
9
  from langchain_chroma import Chroma
10
  from langchain.schema import HumanMessage, SystemMessage
11
  from tiktoken import encoding_for_model
 
12
  from fastapi import FastAPI, HTTPException
13
  from fastapi.middleware.cors import CORSMiddleware
14
  from pydantic import BaseModel
 
98
  # Recherche avec score dans Chroma
99
  results_with_scores = collection.similarity_search_by_vector_with_relevance_scores(query_embedding, k=3)
100
 
101
+ seuil = 0.75 # seuil de similarité pour le RAG
102
  for doc, score in results_with_scores:
103
+ print(f"SCORE: {score:.2f} - DOC: {doc.page_content[:80]}")
104
 
105
  # Filtrage des résultats selon le seuil
106
  filtered_results = [doc for doc, score in results_with_scores if score >= seuil]
 
138
  except Exception as e:
139
  return [{"role": "assistant", "content": f"❌ Erreur : {e}"}]
140
 
141
+ # -- Section Extraction
 
142
  def image_to_base64(image):
143
  buffered = BytesIO()
144
  image.save(buffered, format="PNG") # ou "JPEG" si besoin
145
  return base64.b64encode(buffered.getvalue()).decode("utf-8")
146
 
147
+ # -- Function d'extraction des infos ID
148
  def extract_identity_card_info(image):
149
  try:
150
  base64_img = image_to_base64(image)
 
169
  except Exception as e:
170
  return f"Erreur lors de l'extraction : {e}"
171
 
172
+ # Function d'extraction des vehicule
 
173
  def extract_vehicle_info(image):
174
  try:
175
  base64_img = image_to_base64(image)
 
194
  except Exception as e:
195
  return f"Erreur lors de l'extraction : {e}"
196
 
197
+ # fucntion de classification des plaintes
 
198
  def classify_complaint(text):
199
  system_prompt = (
200
  "Tu es un assistant qui classe les plaintes des utilisateurs dans les catégories suivantes : "
 
245
  label="🎛️ Choisissez un mode", value="chatbotAssistance"
246
  )
247
 
248
+ # -- Bloc 1 - Chatbot
249
  with gr.Column(visible=True) as chatbot_mode_block:
250
  with gr.Row():
251
  domain = gr.Dropdown(
 
268
  message_input = gr.Textbox(label="✉️ Votre message", placeholder="Tapez votre question ici...")
269
  send_button = gr.Button("🚀 Envoyer", variant="primary")
270
 
271
+ # -- Bloc 2 - ID Extraction
272
  with gr.Column(visible=False) as id_extraction_block:
273
  gr.Markdown("🪪 **Extraction d'informations d'identité à partir d'image**")
274
  id_image_input = gr.File(label="Uploader image de pièce d'identité", file_types=["image"], file_count="multiple")
 
278
  def extract_id_fn(files):
279
  if not files:
280
  return "❌ Aucun fichier reçu."
 
 
 
281
  file_path = files[0]
282
 
283
  # Ouvrir l'image avec PIL
 
288
 
289
  id_button.click(fn=extract_id_fn, inputs=[id_image_input], outputs=[id_output])
290
 
291
+ # -- Bloc 3 - Car Detection
292
  with gr.Column(visible=False) as car_detection_block:
293
  gr.Markdown("🚗 **Analyse de véhicules à partir d'image**")
294
  car_image_input = gr.File(label="Uploader image de voiture", file_types=["image"], file_count="multiple")
 
298
  def car_detect_fn(files):
299
  if not files:
300
  return "❌ Aucun fichier reçu."
 
 
 
301
  file_path = files[0]
302
 
303
  # Ouvrir l'image avec PIL