diginoron commited on
Commit
cfecbd0
·
verified ·
1 Parent(s): 40da04c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -18
app.py CHANGED
@@ -1,13 +1,17 @@
1
  # app.py
2
  import os
3
- import pandas as pd
 
 
 
4
  import gradio as gr
 
5
  import comtradeapicall
6
  from huggingface_hub import InferenceClient
7
  from deep_translator import GoogleTranslator
8
- import spaces
9
 
10
- # 1) بارگذاری HS DataFrame از گیت‌هاب
11
  HS_CSV_URL = (
12
  "https://raw.githubusercontent.com/"
13
  "datasets/harmonized-system/master/data/harmonized-system.csv"
@@ -19,9 +23,10 @@ def get_product_name(hs_code: str) -> str:
19
  row = hs_df[hs_df["hscode"] == code4]
20
  return row.iloc[0]["description"] if not row.empty else "–"
21
 
 
 
22
  def get_importers(hs_code: str, year: str, month: str):
23
  product_name = get_product_name(hs_code)
24
-
25
  period = f"{year}{int(month):02d}"
26
  df = comtradeapicall.previewFinalData(
27
  typeCode='C', freqCode='M', clCode='HS', period=period,
@@ -33,19 +38,36 @@ def get_importers(hs_code: str, year: str, month: str):
33
  if df is None or df.empty:
34
  return product_name, pd.DataFrame()
35
 
36
- df = df[['ptCode', 'ptTitle', 'TradeValue']]
37
- df.columns = ['کد کشور', 'نام کشور', 'ارزش CIF']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  return product_name, df
39
 
40
- subscription_key = os.getenv("COMTRADE_API_KEY", "")
41
- hf_token = os.getenv("HF_API_TOKEN", "")
42
- client = InferenceClient(token=hf_token)
43
- translator = GoogleTranslator(source='en', target='fa')
 
44
 
45
  @spaces.GPU
46
  def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str):
47
  if table_data is None or table_data.empty:
48
- return "ابتدا نمایش واردات را انجام دهید."
49
  table_str = table_data.to_string(index=False)
50
  period = f"{year}/{int(month):02d}"
51
  prompt = (
@@ -64,33 +86,34 @@ def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str
64
  except Exception as e:
65
  return f"خطا در تولید مشاوره: {e}"
66
 
 
 
67
  with gr.Blocks() as demo:
68
- gr.Markdown("## تحلیل واردات بر اساس کد HS و ارائه مشاوره")
69
 
70
  with gr.Row():
71
  inp_hs = gr.Textbox(label="کد HS", placeholder="مثلاً 1006")
72
  inp_year = gr.Textbox(label="سال", placeholder="مثلاً 2023")
73
  inp_month = gr.Textbox(label="ماه", placeholder="مثلاً 1 تا 12")
74
 
75
- btn_show = gr.Button("نمایش واردات")
76
  out_name = gr.Markdown(label="**نام محصول**")
77
  out_table = gr.Dataframe(
78
- headers=["کد کشور","نام کشور","ارزش CIF"],
79
- datatype=["number","text","number"],
80
  interactive=True
81
  )
82
 
83
  btn_show.click(
84
- get_importers,
85
  inputs=[inp_hs, inp_year, inp_month],
86
  outputs=[out_name, out_table]
87
  )
88
 
89
- btn_advice = gr.Button("ارائه مشاوره")
90
  out_advice = gr.Textbox(label="مشاوره تخصصی", lines=8)
91
 
92
  btn_advice.click(
93
- provide_advice,
94
  inputs=[out_table, inp_hs, inp_year, inp_month],
95
  outputs=out_advice
96
  )
 
1
  # app.py
2
  import os
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import requests
7
  import gradio as gr
8
+ import pandas as pd
9
  import comtradeapicall
10
  from huggingface_hub import InferenceClient
11
  from deep_translator import GoogleTranslator
12
+ import spaces # برای مدیریت GPU کرایه‌ای
13
 
14
+ # --- بارگذاری HS DATA از CSV گیت‌هاب ---
15
  HS_CSV_URL = (
16
  "https://raw.githubusercontent.com/"
17
  "datasets/harmonized-system/master/data/harmonized-system.csv"
 
23
  row = hs_df[hs_df["hscode"] == code4]
24
  return row.iloc[0]["description"] if not row.empty else "–"
25
 
26
+
27
+ # --- تابع دریافت واردات و پردازش ستون‌ها ---
28
  def get_importers(hs_code: str, year: str, month: str):
29
  product_name = get_product_name(hs_code)
 
30
  period = f"{year}{int(month):02d}"
31
  df = comtradeapicall.previewFinalData(
32
  typeCode='C', freqCode='M', clCode='HS', period=period,
 
38
  if df is None or df.empty:
39
  return product_name, pd.DataFrame()
40
 
41
+ # اگر ستون‌های استاندارد موجود باشند، از آن‌ها استفاده کن
42
+ std_cols = ['ptCode', 'ptTitle', 'TradeValue']
43
+ if all(col in df.columns for col in std_cols):
44
+ out = df[std_cols]
45
+ out.columns = ['کد کشور', 'نام کشور', 'ارزش CIF']
46
+ return product_name, out
47
+
48
+ # وگرنه سعی می‌کنیم ستون‌های مناسب را شناسایی کنیم
49
+ code_col = next((c for c in df.columns if 'code' in c.lower() and c != 'cmdCode'), None)
50
+ title_col= next((c for c in df.columns if 'title' in c.lower()), None)
51
+ value_col= next((c for c in df.columns if 'value' in c.lower()), None)
52
+
53
+ if code_col and title_col and value_col:
54
+ out = df[[code_col, title_col, value_col]]
55
+ out.columns = ['کد کشور', 'نام کشور', 'ارزش CIF']
56
+ return product_name, out
57
+
58
+ # اگر نشد، خودِ DataFrame خام را برگردان
59
  return product_name, df
60
 
61
+
62
+ # --- تابع تولید مشاوره تخصصی با GPU کرایه‌ای ---
63
+ hf_token = os.getenv("HF_API_TOKEN")
64
+ client = InferenceClient(token=hf_token)
65
+ translator = GoogleTranslator(source='en', target='fa')
66
 
67
  @spaces.GPU
68
  def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str):
69
  if table_data is None or table_data.empty:
70
+ return "ابتدا نمایش داده‌های واردات را انجام دهید."
71
  table_str = table_data.to_string(index=False)
72
  period = f"{year}/{int(month):02d}"
73
  prompt = (
 
86
  except Exception as e:
87
  return f"خطا در تولید مشاوره: {e}"
88
 
89
+
90
+ # --- رابط کاربری Gradio ---
91
  with gr.Blocks() as demo:
92
+ gr.Markdown("## تحلیل واردات بر اساس کد HS و ارائه مشاوره تخصصی")
93
 
94
  with gr.Row():
95
  inp_hs = gr.Textbox(label="کد HS", placeholder="مثلاً 1006")
96
  inp_year = gr.Textbox(label="سال", placeholder="مثلاً 2023")
97
  inp_month = gr.Textbox(label="ماه", placeholder="مثلاً 1 تا 12")
98
 
99
+ btn_show = gr.Button("نمایش داده‌های واردات")
100
  out_name = gr.Markdown(label="**نام محصول**")
101
  out_table = gr.Dataframe(
102
+ datatype="pandas",
 
103
  interactive=True
104
  )
105
 
106
  btn_show.click(
107
+ fn=get_importers,
108
  inputs=[inp_hs, inp_year, inp_month],
109
  outputs=[out_name, out_table]
110
  )
111
 
112
+ btn_advice = gr.Button("ارائه مشاوره تخصصی")
113
  out_advice = gr.Textbox(label="مشاوره تخصصی", lines=8)
114
 
115
  btn_advice.click(
116
+ fn=provide_advice,
117
  inputs=[out_table, inp_hs, inp_year, inp_month],
118
  outputs=out_advice
119
  )