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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -48
app.py CHANGED
@@ -1,17 +1,16 @@
 
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}"
@@ -20,53 +19,37 @@ def get_importers(hs_code: str, year: str, month: str):
20
  reporterCode=None, cmdCode=hs_code, flowCode='M',
21
  partnerCode=None, partner2Code=None,
22
  customsCode=None, motCode=None,
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
-
35
- # استخراج نام محصول از توضیحات (فرض بر این است که cmdDesc نام محصول را دارد)
36
- product_name = df['cmdDesc'].iloc[0] if 'cmdDesc' in df.columns else "برنج"
37
- return result, product_name
38
 
39
- def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str, product_name: str):
40
  if table_data is None or table_data.empty:
41
  return "ابتدا باید اطلاعات واردات را نمایش دهید."
42
  table_str = table_data.to_string(index=False)
43
  period = f"{year}/{int(month):02d}"
44
  prompt = (
45
- f"The following table shows countries that imported the product '{product_name}' with HS code {hs_code} during the period {period}:\n"
46
  f"{table_str}\n\n"
47
- f"لطفاً یک تحلیل کامل ارائه دهید که شامل دو بخش باشد. بخش اول فرصت‌های بازار و تقاضای بالقوه برای این محصول در این کشورها را بررسی کند، با توجه به عوامل فرهنگی، اقتصادی و جمعیتی. بخش دوم توصیه‌های استراتژیک عملی برای صادرکنندگان که این بازارها را هدف قرار داده‌اند، با تمرکز بر استراتژی‌های تجاری، مدیریت ریسک و ایجاد مشارکت‌های محلی، ارائه دهد."
48
  )
49
- print("پرامپت ساخته‌شده:")
50
- print(prompt)
51
- try:
52
- print("در حال فراخوانی مدل mistralai/Mixtral-8x7B-Instruct-v0.1...")
53
- outputs = client.text_generation(
54
- prompt=prompt,
55
- model="mistralai/Mixtral-8x7B-Instruct-v0.1",
56
- max_new_tokens=1024
57
- )
58
- print("خروجی مدل دریافت شد (به انگلیسی):")
59
- print(outputs)
60
-
61
- # ترجمه خروجی به فارسی
62
- translated_outputs = translator.translate(outputs)
63
- print("خروجی ترجمه‌شده به فارسی:")
64
- print(translated_outputs)
65
- return translated_outputs
66
- except Exception as e:
67
- error_msg = f"خطا در تولید مشاوره: {str(e)}"
68
- print(error_msg)
69
- return error_msg
70
 
71
  current_year = pd.Timestamp.now().year
72
  years = [str(y) for y in range(2000, current_year+1)]
@@ -75,29 +58,25 @@ months = [str(m) for m in range(1, 13)]
75
  with gr.Blocks() as demo:
76
  gr.Markdown("## نمایش کشورهایی که یک کالا را وارد کرده‌اند")
77
  with gr.Row():
78
- inp_hs = gr.Textbox(label="HS Code", value="1006") # پیش‌فرض 1006 برای برنج
79
- inp_year = gr.Dropdown(choices=years, label="سال", value=str(current_year))
80
  inp_month = gr.Dropdown(choices=months, label="ماه", value=str(pd.Timestamp.now().month))
81
  btn_show = gr.Button("نمایش اطلاعات")
82
  out_table = gr.Dataframe(
83
- headers=["کد کشور", "نام کشور", "ارزش CIF"],
84
- datatype=["number", "text", "number"],
85
  interactive=True,
86
  )
87
- btn_show.click(
88
- fn=get_importers,
89
- inputs=[inp_hs, inp_year, inp_month],
90
- outputs=[out_table, gr.State()] # gr.State برای انتقال product_name
91
- )
92
 
93
  btn_advice = gr.Button("ارائه مشاوره تخصصی")
94
  out_advice = gr.Textbox(label="مشاوره تخصصی", lines=6)
95
 
96
  btn_advice.click(
97
- fn=provide_advice,
98
- inputs=[out_table, inp_hs, inp_year, inp_month, gr.State()],
99
  outputs=out_advice
100
  )
101
 
102
  if __name__ == "__main__":
103
- demo.launch()
 
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}"
 
19
  reporterCode=None, cmdCode=hs_code, flowCode='M',
20
  partnerCode=None, partner2Code=None,
21
  customsCode=None, motCode=None,
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):
36
  if table_data is None or table_data.empty:
37
  return "ابتدا باید اطلاعات واردات را نمایش دهید."
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
  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)
 
 
 
 
71
 
72
  btn_advice = gr.Button("ارائه مشاوره تخصصی")
73
  out_advice = gr.Textbox(label="مشاوره تخصصی", lines=6)
74
 
75
  btn_advice.click(
76
+ provide_advice,
77
+ inputs=[out_table, inp_hs, inp_year, inp_month],
78
  outputs=out_advice
79
  )
80
 
81
  if __name__ == "__main__":
82
+ demo.launch()