MMOON commited on
Commit
61e1dfd
·
verified ·
1 Parent(s): 79a435c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -48
app.py CHANGED
@@ -41,34 +41,31 @@ class PesticideDataFetcher:
41
  try:
42
  response = self.session.get(url, timeout=10)
43
  response.raise_for_status()
44
- return response.json()
 
 
45
  except requests.RequestException as e:
46
  logger.error(f"Échec de la requête {url}: {e}")
47
  return {"error": str(e)}
48
 
49
  def preload_substance_names(self):
50
  url = f"{self.BASE_URL}/active_substances?format=json&api-version=v2.0"
51
- with ThreadPoolExecutor(max_workers=5) as executor:
52
- while url:
53
- data = self.fetch_data(url)
54
- if "error" in data:
55
- logger.error(f"Erreur lors du préchargement: {data.get('error', 'Aucune info')}")
56
- break
57
- tasks = []
58
- for item in data.get("value", []):
59
- tasks.append(executor.submit(self._cache_substance, item))
60
- url = data.get("nextLink")
61
- logger.info(f"Cache prérempli avec {len(self._substance_cache)} substances")
62
-
63
- def _cache_substance(self, item: Dict[str, Any]):
64
- substance_id = item.get("substanceId")
65
- if substance_id:
66
- self._substance_cache[substance_id] = SubstanceDetails(
67
- name=item.get("substanceName", "Nom non trouvé"),
68
- status=item.get("substanceStatus"),
69
- approval_date=item.get("approvalDate"),
70
- expiry_date=item.get("expiryDate")
71
- )
72
 
73
  def get_product_list(self) -> List[Dict[str, Any]]:
74
  if self._product_cache:
@@ -77,10 +74,10 @@ class PesticideDataFetcher:
77
  while url:
78
  data = self.fetch_data(url)
79
  if "error" in data:
80
- logger.error(f"Erreur produits: {data.get('error', 'Aucune info')}")
81
  break
82
  for product in data.get("value", []):
83
- product_id = product.get("productId")
84
  if product_id:
85
  self._product_cache[product_id] = product
86
  url = data.get("nextLink")
@@ -91,23 +88,20 @@ class PesticideDataFetcher:
91
  url = f"{self.BASE_URL}/pesticide_residues_mrls?format=json&product_id={product_id}&api-version=v2.0"
92
  response = self.fetch_data(url)
93
  if "error" in response:
94
- logger.error(f"Erreur MRLs pour le produit {product_id}: {response.get('error', 'Aucune info')}")
95
  return []
96
  return response.get("value", [])
97
 
98
- def get_substance_name(self, substance_id: int) -> str:
99
- substance = self._substance_cache.get(substance_id)
100
- return substance.name if substance else f"Substance {substance_id}"
101
-
102
  class PesticideApp:
103
  def __init__(self):
104
  self.fetcher = PesticideDataFetcher()
105
  self.product_list = {
106
- p.get('productName', 'Aucun nom'): p.get('productId', 0)
107
  for p in self.fetcher.get_product_list()
108
  }
 
109
  self.substances = [
110
- sd.name for sd in self._substance_cache.values()
111
  ]
112
 
113
  def format_date(self, date_str: str) -> str:
@@ -118,7 +112,7 @@ class PesticideApp:
118
  return datetime.strptime(date_str, fmt).strftime("%d/%m/%Y")
119
  except ValueError:
120
  continue
121
- return "Format de date inconnu"
122
 
123
  def get_product_details(self, product_name: str) -> pd.DataFrame:
124
  product_id = self.product_list.get(product_name)
@@ -126,20 +120,16 @@ class PesticideApp:
126
  return pd.DataFrame([{"Erreur": "Produit non trouvé"}])
127
 
128
  mrls = self.fetcher.get_mrls(product_id)
129
- if not mrls:
130
- return pd.DataFrame([{"Erreur": "Aucune donnée MRL trouvée"}])
131
-
132
  data = []
133
  for mrl in mrls:
134
- substance_id = mrl.get("pesticideResidueId", 0)
135
- substance_name = self.fetcher.get_substance_name(substance_id)
136
- substance = self.fetcher._substance_cache.get(substance_id)
137
 
138
  data.append({
139
  "Substance": substance_name,
140
  "Valeur LMR": mrl.get("mrlValue", "N/C"),
141
- "Date d'effet": self.format_date(mrl.get("entryIntoForceDate")),
142
- "Statut": getattr(substance, "status", "N/C")
143
  })
144
  return pd.DataFrame(data)
145
 
@@ -148,10 +138,10 @@ class PesticideApp:
148
  return pd.DataFrame(matches, columns=["Substance"]) if matches else pd.DataFrame([{"Message": "Aucun résultat"}])
149
 
150
  def create_ui(self) -> gr.Blocks:
151
- with gr.Blocks(theme=gr.themes.Default()) as ui:
152
  gr.HTML("""
153
  <div style="text-align: center; padding: 20px; background: #006633; color: white;">
154
- <h1>Base de Données des Pesticides UE</h1>
155
  </div>
156
  """)
157
 
@@ -164,7 +154,6 @@ class PesticideApp:
164
  output = gr.Dataframe(
165
  headers=["Substance", "Valeur LMR", "Date d'effet", "Statut"],
166
  max_height=500,
167
- overflow_scroll=True,
168
  interactive=False
169
  )
170
  product.change(
@@ -176,12 +165,9 @@ class PesticideApp:
176
  with gr.Tab("Recherche par Substance"):
177
  substance_search = gr.Textbox(
178
  label="Rechercher une substance",
179
- placeholder="Entrez un nom de substance..."
180
- )
181
- substance_results = gr.Dataframe(
182
- max_height=300,
183
- interactive=False
184
  )
 
185
  substance_search.submit(
186
  fn=self.search_substances,
187
  inputs=[substance_search],
 
41
  try:
42
  response = self.session.get(url, timeout=10)
43
  response.raise_for_status()
44
+ data = response.json()
45
+ logger.info(f"Réponse API pour {url}: {data[:200]}")
46
+ return data
47
  except requests.RequestException as e:
48
  logger.error(f"Échec de la requête {url}: {e}")
49
  return {"error": str(e)}
50
 
51
  def preload_substance_names(self):
52
  url = f"{self.BASE_URL}/active_substances?format=json&api-version=v2.0"
53
+ while url:
54
+ data = self.fetch_data(url)
55
+ if "error" in data:
56
+ logger.error(f"Erreur préchargement substances: {data.get('error')}")
57
+ break
58
+ for item in data.get("value", []):
59
+ substance_id = item.get("substanceId") # Utilisation de substanceId (camelCase)
60
+ if substance_id:
61
+ self._substance_cache[substance_id] = SubstanceDetails(
62
+ name=item.get("substanceName", "Nom non trouvé"),
63
+ status=item.get("substanceStatus"),
64
+ approval_date=item.get("approvalDate"),
65
+ expiry_date=item.get("expiryDate")
66
+ )
67
+ url = data.get("nextLink")
68
+ logger.info(f"Cache substances prérempli avec {len(self._substance_cache)} entrées")
 
 
 
 
 
69
 
70
  def get_product_list(self) -> List[Dict[str, Any]]:
71
  if self._product_cache:
 
74
  while url:
75
  data = self.fetch_data(url)
76
  if "error" in data:
77
+ logger.error(f"Erreur récupération produits: {data.get('error')}")
78
  break
79
  for product in data.get("value", []):
80
+ product_id = product.get("productId") # Utilisation de productId (camelCase)
81
  if product_id:
82
  self._product_cache[product_id] = product
83
  url = data.get("nextLink")
 
88
  url = f"{self.BASE_URL}/pesticide_residues_mrls?format=json&product_id={product_id}&api-version=v2.0"
89
  response = self.fetch_data(url)
90
  if "error" in response:
91
+ logger.error(f"Erreur MRLs pour {product_id}: {response.get('error')}")
92
  return []
93
  return response.get("value", [])
94
 
 
 
 
 
95
  class PesticideApp:
96
  def __init__(self):
97
  self.fetcher = PesticideDataFetcher()
98
  self.product_list = {
99
+ p.get('productName', 'Aucun nom'): p.get('productId', 0) # Utilisation de productName (camelCase)
100
  for p in self.fetcher.get_product_list()
101
  }
102
+ # Correction : Accès au cache via self.fetcher
103
  self.substances = [
104
+ sd.name for sd in self.fetcher._substance_cache.values()
105
  ]
106
 
107
  def format_date(self, date_str: str) -> str:
 
112
  return datetime.strptime(date_str, fmt).strftime("%d/%m/%Y")
113
  except ValueError:
114
  continue
115
+ return "Format inconnu"
116
 
117
  def get_product_details(self, product_name: str) -> pd.DataFrame:
118
  product_id = self.product_list.get(product_name)
 
120
  return pd.DataFrame([{"Erreur": "Produit non trouvé"}])
121
 
122
  mrls = self.fetcher.get_mrls(product_id)
 
 
 
123
  data = []
124
  for mrl in mrls:
125
+ substance_id = mrl.get("pesticideResidueId", 0) # Utilisation de pesticideResidueId (camelCase)
126
+ substance_name = self.fetcher._substance_cache.get(substance_id, {}).get("name", "Substance inconnue")
 
127
 
128
  data.append({
129
  "Substance": substance_name,
130
  "Valeur LMR": mrl.get("mrlValue", "N/C"),
131
+ "Date d'effet": self.format_date(mrl.get("entryIntoForceDate")), # entryIntoForceDate (camelCase)
132
+ "Statut": self.fetcher._substance_cache.get(substance_id, {}).get("status", "N/C")
133
  })
134
  return pd.DataFrame(data)
135
 
 
138
  return pd.DataFrame(matches, columns=["Substance"]) if matches else pd.DataFrame([{"Message": "Aucun résultat"}])
139
 
140
  def create_ui(self) -> gr.Blocks:
141
+ with gr.Blocks() as ui:
142
  gr.HTML("""
143
  <div style="text-align: center; padding: 20px; background: #006633; color: white;">
144
+ <h1>Base de Données Pesticides UE</h1>
145
  </div>
146
  """)
147
 
 
154
  output = gr.Dataframe(
155
  headers=["Substance", "Valeur LMR", "Date d'effet", "Statut"],
156
  max_height=500,
 
157
  interactive=False
158
  )
159
  product.change(
 
165
  with gr.Tab("Recherche par Substance"):
166
  substance_search = gr.Textbox(
167
  label="Rechercher une substance",
168
+ placeholder="Entrez un nom..."
 
 
 
 
169
  )
170
+ substance_results = gr.Dataframe(max_height=300)
171
  substance_search.submit(
172
  fn=self.search_substances,
173
  inputs=[substance_search],