diginoron commited on
Commit
b4abe98
·
verified ·
1 Parent(s): b8e31be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -22
app.py CHANGED
@@ -5,14 +5,17 @@ import comtradeapicall
5
  from huggingface_hub import InferenceClient
6
  from deep_translator import GoogleTranslator
7
 
 
8
  # کلید COMTRADE
9
  subscription_key = os.getenv("COMTRADE_API_KEY", "")
10
  # توکن Hugging Face
11
  hf_token = os.getenv("HF_API_TOKEN")
12
 
 
13
  client = InferenceClient(token=hf_token)
14
  translator = GoogleTranslator(source='en', target='fa')
15
 
 
16
  def get_importers(hs_code: str, year: str, month: str):
17
  period = f"{year}{int(month):02d}"
18
  df = comtradeapicall.previewFinalData(
@@ -23,7 +26,7 @@ def get_importers(hs_code: str, year: str, month: str):
23
  maxRecords=500, includeDesc=True
24
  )
25
  if df is None or df.empty:
26
- return pd.DataFrame(columns=["کد کشور", "نام کشور", "ارزش CIF"]), "برنج"
27
  df = df[df['cifvalue'] > 0]
28
  result = (
29
  df.groupby(["reporterCode", "reporterDesc"], as_index=False)
@@ -31,34 +34,32 @@ def get_importers(hs_code: str, year: str, month: str):
31
  .sort_values("cifvalue", ascending=False)
32
  )
33
  result.columns = ["کد کشور", "نام کشور", "ارزش CIF"]
34
-
35
- product_name = df['cmdDesc'].iloc[0] if 'cmdDesc' in df.columns else "برنج"
36
- return result, product_name
37
 
38
- def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str, product_name: str):
 
39
  if table_data is None or table_data.empty:
40
  return "ابتدا باید اطلاعات واردات را نمایش دهید."
41
  table_str = table_data.to_string(index=False)
42
  period = f"{year}/{int(month):02d}"
43
  prompt = (
44
- f"The following table shows countries that imported the product '{product_name}' with HS code {hs_code} during the period {period}:\n"
45
  f"{table_str}\n\n"
46
  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."
47
  )
48
  print("پرامپت ساخته‌شده:")
49
  print(prompt)
50
  try:
51
- print("در حال فراخوانی مدل google/gemma-2b-it با متد conversational...")
52
- # استفاده از متد conversational
53
- conversation = client.conversational(
54
- text=prompt,
55
- model="google/gemma-2b-it",
56
- max_new_tokens=1024
57
  )
58
- outputs = conversation['generated_text'] if 'generated_text' in conversation else conversation
59
  print("خروجی مدل دریافت شد (به انگلیسی):")
60
  print(outputs)
61
 
 
62
  # ترجمه خروجی به فارسی
63
  translated_outputs = translator.translate(outputs)
64
  print("خروجی ترجمه‌شده به فارسی:")
@@ -69,14 +70,16 @@ def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str
69
  print(error_msg)
70
  return error_msg
71
 
 
72
  current_year = pd.Timestamp.now().year
73
  years = [str(y) for y in range(2000, current_year+1)]
74
  months = [str(m) for m in range(1, 13)]
75
 
 
76
  with gr.Blocks() as demo:
77
  gr.Markdown("## نمایش کشورهایی که یک کالا را وارد کرده‌اند")
78
  with gr.Row():
79
- inp_hs = gr.Textbox(label="HS Code", value="1006")
80
  inp_year = gr.Dropdown(choices=years, label="سال", value=str(current_year))
81
  inp_month = gr.Dropdown(choices=months, label="ماه", value=str(pd.Timestamp.now().month))
82
  btn_show = gr.Button("نمایش اطلاعات")
@@ -85,20 +88,19 @@ with gr.Blocks() as demo:
85
  datatype=["number", "text", "number"],
86
  interactive=True,
87
  )
88
- btn_show.click(
89
- fn=get_importers,
90
- inputs=[inp_hs, inp_year, inp_month],
91
- outputs=[out_table, gr.State()]
92
- )
93
 
94
  btn_advice = gr.Button("ارائه مشاوره تخصصی")
95
  out_advice = gr.Textbox(label="مشاوره تخصصی", lines=6)
96
 
 
97
  btn_advice.click(
98
- fn=provide_advice,
99
- inputs=[out_table, inp_hs, inp_year, inp_month, gr.State()],
100
  outputs=out_advice
101
  )
102
 
 
103
  if __name__ == "__main__":
104
- demo.launch()
 
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(
 
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)
 
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("خروجی ترجمه‌شده به فارسی:")
 
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("## نمایش کشورهایی که یک کالا را وارد کرده‌اند")
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("نمایش اطلاعات")
 
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,
100
+ inputs=[out_table, inp_hs, inp_year, inp_month],
101
  outputs=out_advice
102
  )
103
 
104
+
105
  if __name__ == "__main__":
106
+ demo.launch()