File size: 5,461 Bytes
80ef441
 
 
 
 
39bcd35
80ef441
b984707
6f5b134
80ef441
a1b0ed6
80ef441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1b0ed6
 
80ef441
 
 
 
 
 
 
 
 
6f5b134
b984707
 
 
 
 
6f5b134
b984707
 
 
 
6f5b134
b984707
 
6f5b134
b984707
80ef441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1b0ed6
80ef441
39bcd35
a1b0ed6
 
 
 
 
 
 
80ef441
39bcd35
a1b0ed6
80ef441
 
 
2be08ff
 
1ee54b7
80ef441
 
 
 
 
 
 
b984707
80ef441
a1b0ed6
b984707
80ef441
6f5b134
 
 
 
 
80ef441
b984707
6f5b134
 
 
b984707
 
6f5b134
80ef441
 
 
 
 
 
 
 
 
 
a1b0ed6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# app.py
import os
import pandas as pd
import gradio as gr
import comtradeapicall
from openai import OpenAI
from deep_translator import GoogleTranslator
import matplotlib.pyplot as plt
import spaces

# --- بارگذاری داده‌های HS Code ---
HS_CSV_URL = (
    "https://raw.githubusercontent.com/"
    "datasets/harmonized-system/master/data/harmonized-system.csv"
)
hs_df = pd.read_csv(HS_CSV_URL, dtype=str)

def get_product_name(hs_code: str) -> str:
    code4 = str(hs_code).zfill(4)
    row = hs_df[hs_df["hscode"] == code4]
    return row.iloc[0]["description"] if not row.empty else "–"

def get_importers(hs_code: str, year: str, month: str):
    product_name = get_product_name(hs_code)
    period = f"{year}{int(month):02d}"
    df = comtradeapicall.previewFinalData(
        typeCode='C', freqCode='M', clCode='HS', period=period,
        reporterCode=None, cmdCode=hs_code, flowCode='M',
        partnerCode=None, partner2Code=None,
        customsCode=None, motCode=None,
        maxRecords=500, includeDesc=True
    )
    if df is None or df.empty:
        return product_name, pd.DataFrame()

    std_map = {
        'کد کشور': 'ptCode',
        'نام کشور': 'ptTitle',
        'ارزش CIF': 'TradeValue'
    }
    code_col = std_map['کد کشور'] if 'ptCode' in df.columns else next((c for c in df.columns if 'code' in c.lower()), None)
    title_col = std_map['نام کشور'] if 'ptTitle' in df.columns else next((c for c in df.columns if 'title' in c.lower()), None)
    value_col = std_map['ارزش CIF'] if 'TradeValue' in df.columns else next((c for c in df.columns if 'value' in c.lower()), None)

    if not (code_col and title_col and value_col):
        return product_name, df

    df_sorted = df.sort_values(value_col, ascending=False).head(10)
    out = df_sorted[[code_col, title_col, value_col]]
    out.columns = ['کد کشور', 'نام کشور', 'ارزش CIF']
    return product_name, out

# --- تابع ترسیم نمودار ۵ کشور برتر ---
def plot_top5_chart(table_data: pd.DataFrame):
    if table_data is None or table_data.empty:
        return None

    df_sorted = table_data.sort_values("ارزش CIF", ascending=False).head(5)
    fig, ax = plt.subplots(figsize=(6, 4))
    ax.bar(df_sorted["نام کشور"], df_sorted["ارزش CIF"], color="skyblue")
    ax.set_ylabel("ارزش CIF (USD)")
    ax.set_title("۵ کشور اول واردکننده")
    ax.tick_params(axis='x', rotation=45)
    plt.tight_layout()
    return fig

# --- مشاوره با GPT + ترجمه فارسی ---
openai_client = OpenAI(api_key=os.getenv("OPENAI"))
translator = GoogleTranslator(source='en', target='fa')

@spaces.GPU
def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str):
    if table_data is None or table_data.empty:
        return "ابتدا نمایش داده‌های واردات را انجام دهید."

    df_limited = table_data.head(10)
    table_str = df_limited.to_string(index=False)
    period = f"{year}/{int(month):02d}"
    prompt = (
        f"The following table shows the top {len(df_limited)} countries by CIF value importing HS code {hs_code} during {period}:\n"
        f"{table_str}\n\n"
        "Please provide a detailed and comprehensive analysis of market trends, risks, "
        "and opportunities for a new exporter entering this market."
    )

    try:
        response = openai_client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are an expert in international trade and export consulting."},
                {"role": "user", "content": prompt}
            ],
            max_tokens=1000,
            temperature=0.7
        )
        english_response = response.choices[0].message.content
        return translator.translate(english_response)
    except Exception as e:
        return f"خطا در تولید مشاوره: {e}"

# --- رابط کاربری Gradio ---
with gr.Blocks() as demo:
    gr.Markdown("## DIGINORON.COM ابزار هوش مصنوعی برای مشاوره صادرات کالا به کشورهای هدف")

    with gr.Row():
        inp_hs = gr.Textbox(label="کد HS", placeholder="مثلاً 1006")
        inp_year = gr.Textbox(label="سال", placeholder="مثلاً 2023")
        inp_month = gr.Textbox(label="ماه", placeholder="مثلاً 1 تا 12")

    btn_show = gr.Button("نمایش داده‌های واردات")

    out_name = gr.Markdown(label="**نام محصول**")
    out_table = gr.Dataframe(datatype="pandas", interactive=True)
    out_chart = gr.Plot(label="نمودار ۵ کشور اول واردکننده")

    # دکمه اول: دو خروجی با هم
    def combined_output(hs_code, year, month):
        name, table = get_importers(hs_code, year, month)
        chart = plot_top5_chart(table)
        return name, table, chart

    btn_show.click(
        fn=combined_output,
        inputs=[inp_hs, inp_year, inp_month],
        outputs=[out_name, out_table, out_chart]
    )

    # دکمه دوم: مشاوره تخصصی
    btn_advice = gr.Button("ارائه مشاوره تخصصی")
    out_advice = gr.Textbox(label="مشاوره تخصصی", lines=8)

    btn_advice.click(
        fn=provide_advice,
        inputs=[out_table, inp_hs, inp_year, inp_month],
        outputs=out_advice
    )

if __name__ == "__main__":
    demo.launch()