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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -57
app.py CHANGED
@@ -1,22 +1,27 @@
 
1
  import os
2
- import gradio as gr
3
  import pandas as pd
 
4
  import comtradeapicall
5
  from huggingface_hub import InferenceClient
6
  from deep_translator import GoogleTranslator
 
7
 
 
 
 
 
 
 
8
 
9
- # کلید COMTRADE
10
- subscription_key = os.getenv("COMTRADE_API_KEY", "")
11
- # توکن Hugging Face
12
- hf_token = os.getenv("HF_API_TOKEN")
13
-
14
-
15
- client = InferenceClient(token=hf_token)
16
- translator = GoogleTranslator(source='en', target='fa')
17
-
18
 
19
  def get_importers(hs_code: str, year: str, month: str):
 
 
20
  period = f"{year}{int(month):02d}"
21
  df = comtradeapicall.previewFinalData(
22
  typeCode='C', freqCode='M', clCode='HS', period=period,
@@ -26,74 +31,63 @@ def get_importers(hs_code: str, year: str, month: str):
26
  maxRecords=500, includeDesc=True
27
  )
28
  if df is None or df.empty:
29
- return pd.DataFrame(columns=["کد کشور", "نام کشور", "ارزش CIF"])
30
- df = df[df['cifvalue'] > 0]
31
- result = (
32
- df.groupby(["reporterCode", "reporterDesc"], as_index=False)
33
- .agg({"cifvalue": "sum"})
34
- .sort_values("cifvalue", ascending=False)
35
- )
36
- result.columns = ["کد کشور", "نام کشور", "ارزش CIF"]
37
- return result
38
 
 
 
 
 
 
 
 
 
39
 
 
40
  def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str):
41
  if table_data is None or table_data.empty:
42
- return "ابتدا باید اطلاعات واردات را نمایش دهید."
43
  table_str = table_data.to_string(index=False)
44
  period = f"{year}/{int(month):02d}"
45
  prompt = (
46
- f"The following table shows countries that imported a product with HS code {hs_code} during the period {period}:\n"
47
  f"{table_str}\n\n"
48
- f"Please provide a detailed and comprehensive analysis in two paragraphs. The first paragraph should discuss market opportunities, potential demand, and specific cultural or economic factors influencing the demand for this product in these countries. The second paragraph should offer actionable strategic recommendations for exporters, including detailed trade strategies, risk management techniques, and steps to establish local partnerships."
 
49
  )
50
- print("پرامپت ساخته‌شده:")
51
- print(prompt)
52
  try:
53
- print("در حال فراخوانی مدل mistralai/Mixtral-8x7B-Instruct-v0.1...")
54
  outputs = client.text_generation(
55
  prompt=prompt,
56
  model="mistralai/Mixtral-8x7B-Instruct-v0.1",
57
- max_new_tokens=1024 # افزایش برای تکمیل جملات
58
  )
59
- print("خروجی مدل دریافت شد (به انگلیسی):")
60
- print(outputs)
61
-
62
-
63
- # ترجمه خروجی به فارسی
64
- translated_outputs = translator.translate(outputs)
65
- print("خروجی ترجمه‌شده به فارسی:")
66
- print(translated_outputs)
67
- return translated_outputs
68
  except Exception as e:
69
- error_msg = f"خطا در تولید مشاوره: {str(e)}"
70
- print(error_msg)
71
- return error_msg
72
-
73
-
74
- current_year = pd.Timestamp.now().year
75
- years = [str(y) for y in range(2000, current_year+1)]
76
- months = [str(m) for m in range(1, 13)]
77
-
78
 
79
  with gr.Blocks() as demo:
80
- gr.Markdown("##تولید شده توسط DIGINORON نمایش کشورهایی که یک کالا را وارد کرده‌اند")
 
81
  with gr.Row():
82
- inp_hs = gr.Textbox(label="HS Code")
83
- inp_year = gr.Dropdown(choices=years, label="سال", value=str(current_year))
84
- inp_month = gr.Dropdown(choices=months, label="ماه", value=str(pd.Timestamp.now().month))
85
- btn_show = gr.Button("نمایش اطلاعات")
 
 
86
  out_table = gr.Dataframe(
87
- headers=["کد کشور", "نام کشور", "ارزش CIF"],
88
- datatype=["number", "text", "number"],
89
- interactive=True,
90
  )
91
- btn_show.click(get_importers, [inp_hs, inp_year, inp_month], out_table)
92
-
93
 
94
- btn_advice = gr.Button("ارائه مشاوره تخصصی")
95
- out_advice = gr.Textbox(label="مشاوره تخصصی", lines=6)
 
 
 
96
 
 
 
97
 
98
  btn_advice.click(
99
  provide_advice,
@@ -101,6 +95,5 @@ with gr.Blocks() as demo:
101
  outputs=out_advice
102
  )
103
 
104
-
105
  if __name__ == "__main__":
106
  demo.launch()
 
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"
14
+ )
15
+ hs_df = pd.read_csv(HS_CSV_URL, dtype=str)
16
 
17
+ def get_product_name(hs_code: str) -> str:
18
+ code4 = str(hs_code).zfill(4)
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,
 
31
  maxRecords=500, includeDesc=True
32
  )
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 = (
52
+ f"The following table shows countries that imported a product with HS code {hs_code} during {period}:\n"
53
  f"{table_str}\n\n"
54
+ "Please provide a detailed and comprehensive analysis of market trends, risks, "
55
+ "and opportunities for a new exporter entering this market."
56
  )
 
 
57
  try:
 
58
  outputs = client.text_generation(
59
  prompt=prompt,
60
  model="mistralai/Mixtral-8x7B-Instruct-v0.1",
61
+ max_new_tokens=1024
62
  )
63
+ return translator.translate(outputs)
 
 
 
 
 
 
 
 
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,
 
95
  outputs=out_advice
96
  )
97
 
 
98
  if __name__ == "__main__":
99
  demo.launch()