diginoron commited on
Commit
e5eed83
·
verified ·
1 Parent(s): 937f1aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -21
app.py CHANGED
@@ -1,16 +1,17 @@
1
- graidio
2
  import os
3
  import gradio as gr
4
  import pandas as pd
5
  import comtradeapicall
6
  from huggingface_hub import InferenceClient
 
7
 
8
- # کلید COMTRADE (فعلاً برای preview نیازی به آن نداریم)
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
 
15
  def get_importers(hs_code: str, year: str, month: str):
16
  period = f"{year}{int(month):02d}"
@@ -22,14 +23,14 @@ def get_importers(hs_code: str, year: str, month: str):
22
  maxRecords=500, includeDesc=True
23
  )
24
  if df is None or df.empty:
25
- return pd.DataFrame(columns=["کد کشور","نام کشور","ارزش CIF"])
26
  df = df[df['cifvalue'] > 0]
27
  result = (
28
- df.groupby(["reporterCode","reporterDesc"], as_index=False)
29
- .agg({"cifvalue":"sum"})
30
  .sort_values("cifvalue", ascending=False)
31
  )
32
- result.columns = ["کد کشور","نام کشور","ارزش CIF"]
33
  return result
34
 
35
  def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str):
@@ -38,18 +39,31 @@ def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str
38
  table_str = table_data.to_string(index=False)
39
  period = f"{year}/{int(month):02d}"
40
  prompt = (
41
- f"جدول زیر کشورهایی را نشان می‌دهد که کالا با کد HS {hs_code} را در دوره {period} وارد کرده‌اند:\n"
42
  f"{table_str}\n\n"
43
- "لطفاً بر اساس این اطلاعات دو پاراگراف مشاوره تخصصی بنویسید."
44
  )
45
- # فراخوانی text_generation
46
- outputs = client.text_generation(
47
- model="google/gemma-2b",
48
- inputs=prompt,
49
- parameters={"max_new_tokens":256}
50
- )
51
- # خروجی اولین شات
52
- return outputs[0]["generated_text"]
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  current_year = pd.Timestamp.now().year
55
  years = [str(y) for y in range(2000, current_year+1)]
@@ -58,13 +72,13 @@ months = [str(m) for m in range(1, 13)]
58
  with gr.Blocks() as demo:
59
  gr.Markdown("## نمایش کشورهایی که یک کالا را وارد کرده‌اند")
60
  with gr.Row():
61
- inp_hs = gr.Textbox(label="HS Code")
62
- inp_year = gr.Dropdown(choices=years, label="سال", value=str(current_year))
63
  inp_month = gr.Dropdown(choices=months, label="ماه", value=str(pd.Timestamp.now().month))
64
  btn_show = gr.Button("نمایش اطلاعات")
65
  out_table = gr.Dataframe(
66
- headers=["کد کشور","نام کشور","ارزش CIF"],
67
- datatype=["number","text","number"],
68
  interactive=True,
69
  )
70
  btn_show.click(get_importers, [inp_hs, inp_year, inp_month], out_table)
@@ -79,4 +93,4 @@ with gr.Blocks() as demo:
79
  )
80
 
81
  if __name__ == "__main__":
82
- demo.launch()
 
 
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
+ # کلید 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}"
 
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)
30
+ .agg({"cifvalue": "sum"})
31
  .sort_values("cifvalue", ascending=False)
32
  )
33
+ result.columns = ["کد کشور", "نام کشور", "ارزش CIF"]
34
  return result
35
 
36
  def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str):
 
39
  table_str = table_data.to_string(index=False)
40
  period = f"{year}/{int(month):02d}"
41
  prompt = (
42
+ f"The following table shows countries that imported a product with HS code {hs_code} during the period {period}:\n"
43
  f"{table_str}\n\n"
44
+ 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."
45
  )
46
+ print("پرامپت ساخته‌شده:")
47
+ print(prompt)
48
+ try:
49
+ print("در حال فراخوانی مدل mistralai/Mixtral-8x7B-Instruct-v0.1...")
50
+ outputs = client.text_generation(
51
+ prompt=prompt,
52
+ model="mistralai/Mixtral-8x7B-Instruct-v0.1",
53
+ max_new_tokens=1024 # افزایش برای تکمیل جملات
54
+ )
55
+ print("خروجی مدل دریافت شد (به انگلیسی):")
56
+ print(outputs)
57
+
58
+ # ترجمه خروجی به فارسی
59
+ translated_outputs = translator.translate(outputs)
60
+ print("خروجی ترجمه‌شده به فارسی:")
61
+ print(translated_outputs)
62
+ return translated_outputs
63
+ except Exception as e:
64
+ error_msg = f"خطا در تولید مشاوره: {str(e)}"
65
+ print(error_msg)
66
+ return error_msg
67
 
68
  current_year = pd.Timestamp.now().year
69
  years = [str(y) for y in range(2000, current_year+1)]
 
72
  with gr.Blocks() as demo:
73
  gr.Markdown("## نمایش کشورهایی که یک کالا را وارد کرده‌اند")
74
  with gr.Row():
75
+ inp_hs = gr.Textbox(label="HS Code")
76
+ inp_year = gr.Dropdown(choices=years, label="سال", value=str(current_year))
77
  inp_month = gr.Dropdown(choices=months, label="ماه", value=str(pd.Timestamp.now().month))
78
  btn_show = gr.Button("نمایش اطلاعات")
79
  out_table = gr.Dataframe(
80
+ headers=["کد کشور", "نام کشور", "ارزش CIF"],
81
+ datatype=["number", "text", "number"],
82
  interactive=True,
83
  )
84
  btn_show.click(get_importers, [inp_hs, inp_year, inp_month], out_table)
 
93
  )
94
 
95
  if __name__ == "__main__":
96
+ demo.launch()