diginoron commited on
Commit
d4f3c6c
·
verified ·
1 Parent(s): 6ac8e0f

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -148
app.py DELETED
@@ -1,148 +0,0 @@
1
- import os
2
- import gradio as gr
3
- import pandas as pd
4
- import comtradeapicall
5
- import spaces
6
- from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
7
- from deep_translator import GoogleTranslator
8
- import torch
9
-
10
- # تنظیم متغیر محیطی برای دیباگ CUDA
11
- os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
12
-
13
- # کلید COMTRADE
14
- subscription_key = os.getenv("COMTRADE_API_KEY", "")
15
- # توکن Hugging Face
16
- hf_token = os.getenv("HF_API_TOKEN")
17
-
18
- # تعریف مترجم
19
- translator = GoogleTranslator(source='en', target='fa')
20
-
21
- # تنظیم کوانت‌سازی برای کاهش مصرف حافظه
22
- quantization_config = BitsAndBytesConfig(load_in_4bit=True)
23
-
24
- # بارگذاری توکنایزر و مدل
25
- try:
26
- tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b-it", token=hf_token)
27
- model = AutoModelForCausalLM.from_pretrained(
28
- "google/gemma-2b-it",
29
- token=hf_token,
30
- quantization_config=quantization_config,
31
- device_map="auto",
32
- torch_dtype=torch.float16
33
- )
34
- except Exception as e:
35
- print(f"خطا در بارگذاری مدل: {str(e)}")
36
- raise e
37
-
38
- # تنظیم صریح pad_token_id
39
- if tokenizer.pad_token_id is None:
40
- tokenizer.pad_token_id = tokenizer.eos_token_id
41
-
42
- # تابع دریافت اطلاعات واردکنندگان
43
- def get_importers(hs_code: str, year: str, month: str):
44
- period = f"{year}{int(month):02d}"
45
- df = comtradeapicall.previewFinalData(
46
- typeCode='C', freqCode='M', clCode='HS', period=period,
47
- reporterCode=None, cmdCode=hs_code, flowCode='M',
48
- partnerCode=None, partner2Code=None,
49
- customsCode=None, motCode=None,
50
- maxRecords=500, includeDesc=True
51
- )
52
- if df is None or df.empty:
53
- return pd.DataFrame(columns=["کد کشور", "نام کشور", "ارزش CIF"])
54
- df = df[df['cifvalue'] > 0]
55
- result = (
56
- df.groupby(["reporterCode", "reporterDesc"], as_index=False)
57
- .agg({"cifvalue": "sum"})
58
- .sort_values("cifvalue", ascending=False)
59
- )
60
- result.columns = ["کد کشور", "نام کشور", "ارزش CIF"]
61
- return result
62
-
63
- # تابع ارائه مشاوره با استفاده از GPU
64
- @spaces.GPU(duration=120)
65
- def provide_advice(table_data: pd.DataFrame, hs_code: str, year: str, month: str):
66
- if table_data is None or table_data.empty:
67
- return "ابتدا باید اطلاعات واردات را نمایش دهید."
68
-
69
- table_str = table_data.to_string(index=False)
70
- period = f"{year}/{int(month):02d}"
71
- # پرامپت بهینه‌شده
72
- prompt = (
73
- f"Table of countries importing HS code {hs_code} in {period}:\n{table_str}\n\n"
74
- f"Analyze market opportunities and cultural/economic factors in one paragraph. "
75
- f"Provide strategic recommendations for exporters in another paragraph."
76
- )
77
- print("پرامپت ساخته‌شده:")
78
- print(prompt)
79
-
80
- try:
81
- # آماده‌سازی ورودی برای مدل
82
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
83
- input_ids = inputs.input_ids.to("cuda")
84
- attention_mask = inputs.attention_mask.to("cuda")
85
-
86
- # تولید خروجی
87
- outputs = model.generate(
88
- input_ids=input_ids,
89
- attention_mask=attention_mask,
90
- max_new_tokens=512,
91
- do_sample=True,
92
- temperature=0.7,
93
- top_p=0.9,
94
- pad_token_id=tokenizer.eos_token_id
95
- )
96
- # دیکد کردن خروجی و حذف پرامپت
97
- generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
98
- # حذف پرامپت از خروجی
99
- if generated_text.startswith(prompt):
100
- generated_text = generated_text[len(prompt):].strip()
101
-
102
- # بررسی اینکه خروجی خالی نباشد
103
- if not generated_text:
104
- return "مدل نتوانست پاسخ مناسبی تولید کند. لطفاً دوباره امتحان کنید."
105
-
106
- print("خروجی مدل دریافت شد (به انگلیسی):")
107
- print(generated_text)
108
-
109
- # ترجمه خروجی به فارسی
110
- translated_outputs = translator.translate(generated_text)
111
- print("خروجی ترجمه‌شده به فارسی:")
112
- print(translated_outputs)
113
- return translated_outputs
114
- except Exception as e:
115
- error_msg = f"خطا در تولید مشاوره: {str(e)}"
116
- print(error_msg)
117
- return error_msg
118
-
119
- # تنظیمات رابط Gradio
120
- current_year = pd.Timestamp.now().year
121
- years = [str(y) for y in range(2000, current_year+1)]
122
- months = [str(m) for m in range(1, 13)]
123
-
124
- with gr.Blocks() as demo:
125
- gr.Markdown("##تولید شده توسط DIGINORON نمایش کشورهایی که یک کالا را وارد کرده‌اند")
126
- with gr.Row():
127
- inp_hs = gr.Textbox(label="HS Code")
128
- inp_year = gr.Dropdown(choices=years, label="سال", value=str(current_year))
129
- inp_month = gr.Dropdown(choices=months, label="ماه", value=str(pd.Timestamp.now().month))
130
- btn_show = gr.Button("نمایش اطلاعات")
131
- out_table = gr.Dataframe(
132
- headers=["کد کشور", "نام کشور", "ارزش CIF"],
133
- datatype=["number", "text", "number"],
134
- interactive=True,
135
- )
136
- btn_show.click(get_importers, [inp_hs, inp_year, inp_month], out_table)
137
-
138
- btn_advice = gr.Button("ارائه مشاوره تخصصی")
139
- out_advice = gr.Textbox(label="مشاوره تخصصی", lines=6)
140
-
141
- btn_advice.click(
142
- provide_advice,
143
- inputs=[out_table, inp_hs, inp_year, inp_month],
144
- outputs=out_advice
145
- )
146
-
147
- if __name__ == "__main__":
148
- demo.launch()