File size: 3,708 Bytes
d46e047
a0a648c
 
 
 
 
 
d46e047
a0a648c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d46e047
 
 
 
 
a0a648c
d46e047
a0a648c
 
 
 
 
 
 
 
d46e047
 
 
 
a0a648c
 
 
 
 
 
d46e047
a0a648c
 
 
 
 
 
 
 
 
 
 
 
 
 
d46e047
 
a0a648c
d46e047
 
 
 
a0a648c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py
import os
import gradio as gr
import pandas as pd
import comtradeapicall
from huggingface_hub import InferenceClient
from deep_translator import GoogleTranslator
import spaces  # اضافه‌شده برای مدیریت GPU روی ZeroGPU Spaces

# کلید COMTRADE
subscription_key = os.getenv("COMTRADE_API_KEY", "")
# توکن Hugging Face
hf_token = os.getenv("HF_API_TOKEN")

client = InferenceClient(token=hf_token)
translator = GoogleTranslator(source='en', target='fa')

def get_importers(hs_code: str, year: str, month: str):
    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 pd.DataFrame()  # خالی
    # فقط ستون‌های مورد نیاز را نگه‌دار
    df = df[['ptCode', 'ptTitle', 'TradeValue']]
    df.columns = ['کد کشور', 'نام کشور', 'ارزش CIF']
    return df

@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 "ابتدا باید اطلاعات واردات را نمایش دهید."
    table_str = table_data.to_string(index=False)
    period = f"{year}/{int(month):02d}"
    prompt = (
        f"The following table shows countries that imported a product with HS code {hs_code} during the period {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. "
        "Include competitive landscape, pricing benchmarks, logistical considerations, "
        "risk management techniques, and steps to establish local partnerships."
    )
    try:
        print("در حال فراخوانی مدل mistralai/Mixtral-8x7B-Instruct-v0.1...")
        outputs = client.text_generation(
            prompt=prompt,
            model="mistralai/Mixtral-8x7B-Instruct-v0.1",
            max_new_tokens=1024
        )
        print("خروجی مدل دریافت شد (به انگلیسی):")
        print(outputs)

        translated_outputs = translator.translate(outputs)
        print("خروجی ترجمه‌شده به فارسی:")
        print(translated_outputs)
        return translated_outputs
    except Exception as e:
        error_msg = f"خطا در تولید مشاوره: {str(e)}"
        print(error_msg)
        return error_msg

with gr.Blocks() as demo:
    gr.Markdown("## تحلیل واردات بر اساس کد HS و ارائه مشاوره تخصصی")

    with gr.Row():
        inp_hs = gr.Textbox(label="کد HS", placeholder="مثلاً 100610")
        inp_year = gr.Textbox(label="سال", placeholder="مثلاً 2023")
        inp_month = gr.Textbox(label="ماه", placeholder="مثلاً 1 تا 12")
    btn_show = gr.Button("نمایش واردات")
    out_table = gr.Dataframe(
        headers=["کد کشور", "نام کشور", "ارزش CIF"],
        datatype=["number", "text", "number"],
        interactive=True,
    )
    btn_show.click(get_importers, [inp_hs, inp_year, inp_month], out_table)

    btn_advice = gr.Button("ارائه مشاوره تخصصی")
    out_advice = gr.Textbox(label="مشاوره تخصصی", lines=6)
    btn_advice.click(
        provide_advice,
        inputs=[out_table, inp_hs, inp_year, inp_month],
        outputs=out_advice
    )

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