leilaghomashchi commited on
Commit
fd31c08
·
verified ·
1 Parent(s): b14b4a7

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -405
app.py DELETED
@@ -1,405 +0,0 @@
1
- import requests
2
- import json
3
- import gradio as gr
4
- from typing import Dict, Any
5
- import os
6
- from dataclasses import dataclass
7
-
8
- @dataclass
9
- class GroqConfig:
10
- """تنظیمات Groq API"""
11
- api_key: str
12
- base_url: str = "https://api.groq.com/openai/v1"
13
- model: str = "llama-3.1-8b-instant"
14
- max_tokens: int = 1000
15
- temperature: float = 0.1
16
-
17
- class GroqAnonymizer:
18
- """سیستم ناشناس‌سازی با استفاده از Groq"""
19
-
20
- def __init__(self, api_key: str = None):
21
- if api_key is None:
22
- api_key = os.getenv("GROQ_API_KEY")
23
- if not api_key:
24
- raise ValueError("کلید API یافت نشد")
25
-
26
- self.config = GroqConfig(api_key=api_key)
27
- self.system_prompt = self._create_system_prompt()
28
-
29
- def _create_system_prompt(self) -> str:
30
- """ایجاد دستورالعمل سیستمی برای Groq"""
31
- return """Replace these in Persian text:
32
- - Company names with: company-01, company-02, etc.
33
- - Person names with: person-01, person-02, etc.
34
- - Numbers/amounts with: amount-01, amount-02, etc.
35
- - Percentages with: percent-01, percent-02, etc.
36
-
37
- Only return the anonymized text, nothing else."""
38
-
39
- def _make_api_request(self, text: str) -> Dict[str, Any]:
40
- """ارسال درخواست به Groq API"""
41
- headers = {
42
- "Authorization": f"Bearer {self.config.api_key}",
43
- "Content-Type": "application/json"
44
- }
45
-
46
- payload = {
47
- "messages": [
48
- {
49
- "role": "system",
50
- "content": self.system_prompt
51
- },
52
- {
53
- "role": "user",
54
- "content": text
55
- }
56
- ],
57
- "model": self.config.model,
58
- "temperature": self.config.temperature,
59
- "max_tokens": self.config.max_tokens
60
- }
61
-
62
- try:
63
- response = requests.post(
64
- f"{self.config.base_url}/chat/completions",
65
- headers=headers,
66
- json=payload,
67
- timeout=30
68
- )
69
- response.raise_for_status()
70
- return response.json()
71
-
72
- except requests.exceptions.RequestException as e:
73
- raise Exception(f"خطا در ارتباط با Groq API: {str(e)}")
74
-
75
- def anonymize_text(self, text: str) -> Dict[str, Any]:
76
- """ناشناس‌سازی متن با استفاده از Groq"""
77
- if not text.strip():
78
- return {
79
- "success": False,
80
- "error": "متن ورودی خالی است"
81
- }
82
-
83
- try:
84
- response = self._make_api_request(text)
85
-
86
- if "choices" not in response or not response["choices"]:
87
- return {
88
- "success": False,
89
- "error": "پاسخ نامعتبر از API"
90
- }
91
-
92
- content = response["choices"][0]["message"]["content"]
93
-
94
- # پاک کردن markdown اگر وجود دارد
95
- if "```" in content:
96
- lines = content.split('\n')
97
- clean_lines = []
98
- skip = False
99
- for line in lines:
100
- if line.strip().startswith('```'):
101
- skip = not skip
102
- continue
103
- if not skip:
104
- clean_lines.append(line)
105
- content = '\n'.join(clean_lines)
106
-
107
- # حذف خطوط اضافی و فضاهای خالی
108
- content = content.strip()
109
-
110
- return {
111
- "success": True,
112
- "anonymized_text": content,
113
- "entities": [], # در حالت ساده entities نداریم
114
- "statistics": self._count_entities(content),
115
- "usage": response.get("usage", {})
116
- }
117
-
118
- except Exception as e:
119
- return {
120
- "success": False,
121
- "error": f"خطا در پردازش: {str(e)}"
122
- }
123
-
124
- def _count_entities(self, text: str) -> Dict[str, int]:
125
- """شمارش موجودیت‌ها در متن ناشناس‌سازی شده"""
126
- import re
127
-
128
- company_count = len(re.findall(r'company-\d+', text))
129
- person_count = len(re.findall(r'person-\d+', text))
130
- amount_count = len(re.findall(r'amount-\d+', text))
131
- percent_count = len(re.findall(r'percent-\d+', text))
132
- group_count = len(re.findall(r'group-\d+', text))
133
-
134
- return {
135
- "company": company_count,
136
- "person": person_count,
137
- "amount": amount_count,
138
- "percent": percent_count,
139
- "group": group_count
140
- }
141
-
142
- def create_interface():
143
- """ایجاد رابط کاربری"""
144
-
145
- # بررسی وجود کلید API
146
- api_key_available = bool(os.getenv("GROQ_API_KEY"))
147
-
148
- # CSS سفارشی
149
- custom_css = """
150
- .gradio-container {
151
- font-family: 'Tahoma', 'Arial', sans-serif !important;
152
- direction: rtl;
153
- max-width: 1200px;
154
- margin: 0 auto;
155
- }
156
- .result-box {
157
- background-color: #f0f8ff;
158
- border: 1px solid #ddd;
159
- border-radius: 8px;
160
- padding: 15px;
161
- }
162
- .warning-box {
163
- background-color: #fff3cd;
164
- border: 1px solid #ffeaa7;
165
- border-radius: 8px;
166
- padding: 10px;
167
- color: #856404;
168
- }
169
- .success-box {
170
- background-color: #d4edda;
171
- border: 1px solid #c3e6cb;
172
- border-radius: 8px;
173
- padding: 10px;
174
- color: #155724;
175
- }
176
- """
177
-
178
- with gr.Blocks(css=custom_css, title="ناشناس‌سازی متن فارسی", theme=gr.themes.Soft()) as interface:
179
-
180
- # عنوان
181
- gr.Markdown("""
182
- # 🔒 سیستم ناشناس‌سازی متن فارسی
183
- ### قدرت‌گرفته از Groq AI برای تشخیص و حفاظت از اطلاعات حساس
184
- """)
185
-
186
- # نمایش وضعیت API
187
- if api_key_available:
188
- gr.Markdown("""
189
- <div class="success-box">
190
- ✅ <strong>سیستم آماده است</strong> - کلید API تنظیم شده
191
- </div>
192
- """)
193
- api_key_input = gr.Textbox(visible=False, value="")
194
- else:
195
- gr.Markdown("""
196
- <div class="warning-box">
197
- ⚠️ <strong>کلید API تنظیم نشده</strong><br>
198
- لطفاً کلید Groq API خود را در زیر وارد کنید
199
- </div>
200
- """)
201
- api_key_input = gr.Textbox(
202
- label="🔑 کلید Groq API",
203
- placeholder="gsk_...",
204
- type="password",
205
- value="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"
206
- )
207
-
208
- with gr.Row():
209
- with gr.Column(scale=1):
210
- input_text = gr.Textbox(
211
- label="📝 متن ورودی",
212
- placeholder="متن خود را اینجا وارد کنید...",
213
- lines=10,
214
- max_lines=20
215
- )
216
-
217
- with gr.Row():
218
- anonymize_btn = gr.Button(
219
- "🔒 ناشناس‌سازی متن",
220
- variant="primary",
221
- size="lg"
222
- )
223
- clear_btn = gr.Button(
224
- "🗑️ پاک کردن",
225
- variant="secondary"
226
- )
227
-
228
- with gr.Column(scale=1):
229
- output_text = gr.Textbox(
230
- label="🎯 متن ناشناس‌سازی شده",
231
- lines=10,
232
- max_lines=20,
233
- elem_classes=["result-box"]
234
- )
235
-
236
- # دکمه کپی
237
- copy_btn = gr.Button(
238
- "📋 کپی متن",
239
- variant="secondary",
240
- size="sm"
241
- )
242
-
243
- # متن برای کپی
244
- copy_output = gr.Textbox(
245
- label="📋 متن برای کپی (Ctrl+A و Ctrl+C)",
246
- lines=3,
247
- max_lines=10,
248
- visible=False,
249
- interactive=True
250
- )
251
-
252
- with gr.Row():
253
- with gr.Column():
254
- statistics_output = gr.Markdown(label="📊 آمار تشخیص")
255
- with gr.Column():
256
- usage_output = gr.Markdown(label="⚡ اطلاعات پردازش")
257
-
258
- entities_output = gr.Markdown(label="📋 جزئیات تغییرات")
259
-
260
- def process_text(text: str, api_key_manual: str = ""):
261
- """پردازش متن"""
262
- # حل مشکل NoneType
263
- if api_key_manual is None:
264
- api_key_manual = ""
265
-
266
- # تعیین کلید API
267
- final_api_key = ""
268
- if api_key_manual and api_key_manual.strip():
269
- final_api_key = api_key_manual.strip()
270
- elif os.getenv("GROQ_API_KEY"):
271
- final_api_key = os.getenv("GROQ_API_KEY")
272
-
273
- if not final_api_key:
274
- return (
275
- "",
276
- "❌ کلید API وارد نشده است",
277
- "",
278
- ""
279
- )
280
-
281
- if not text or not text.strip():
282
- return (
283
- "",
284
- "❌ لطفاً متن ورودی را وارد کنید",
285
- "",
286
- ""
287
- )
288
-
289
- try:
290
- anonymizer = GroqAnonymizer(api_key=final_api_key)
291
- result = anonymizer.anonymize_text(text)
292
-
293
- if not result["success"]:
294
- return (
295
- "",
296
- f"❌ خطا: {result['error']}",
297
- "",
298
- ""
299
- )
300
-
301
- # آمار
302
- stats = result.get("statistics", {})
303
- stats_md = "📊 **آمار تشخیص:**\n\n"
304
- total = sum(stats.values()) if stats else 0
305
- stats_md += f"🔢 **کل موارد:** {total}\n\n"
306
-
307
- type_names = {
308
- 'company': 'شرکت‌ها',
309
- 'person': 'افراد',
310
- 'group': 'گروه‌ها',
311
- 'amount': 'مبالغ',
312
- 'percent': 'درصدها'
313
- }
314
-
315
- if stats:
316
- for key, value in stats.items():
317
- if value > 0:
318
- name = type_names.get(key, key)
319
- stats_md += f"• {name}: **{value}** مورد\n"
320
-
321
- # اطلاعات پردازش
322
- usage = result.get("usage", {})
323
- usage_md = "⚡ **اطلاعات پردازش:**\n\n"
324
- if usage:
325
- usage_md += f"• مدل: Llama 3.1\n"
326
- usage_md += f"• Token های ورودی: {usage.get('prompt_tokens', 'نامشخص')}\n"
327
- usage_md += f"• Token های خروجی: {usage.get('completion_tokens', 'نامشخص')}\n"
328
- else:
329
- usage_md += "✅ پردازش با موفقیت انجام شد"
330
-
331
- # جزئیات موجودیت‌ها
332
- entities_md = "📋 **جزئیات تغییرات:**\n\n"
333
- entities_md += "ناشناس‌سازی با موفقیت انجام شد"
334
-
335
- return (
336
- result["anonymized_text"],
337
- stats_md,
338
- usage_md,
339
- entities_md
340
- )
341
-
342
- except Exception as e:
343
- return (
344
- "",
345
- f"❌ خطای غیرمنتظره: {str(e)}",
346
- "",
347
- ""
348
- )
349
-
350
- def copy_text(text_to_copy):
351
- """تابع کپی متن"""
352
- if not text_to_copy or not text_to_copy.strip():
353
- return gr.Textbox(visible=False), "⚠️ متنی برای کپی وجود ندارد"
354
-
355
- return gr.Textbox(value=text_to_copy, visible=True), "✅ متن در کادر زیر آماده کپی است"
356
-
357
- def clear_all():
358
- """پاک کردن تمام فیلدها"""
359
- return "", "", "", "", "", gr.Textbox(visible=False)
360
-
361
- # اتصال رویدادها
362
- anonymize_btn.click(
363
- fn=process_text,
364
- inputs=[input_text, api_key_input],
365
- outputs=[output_text, statistics_output, usage_output, entities_output]
366
- )
367
-
368
- copy_btn.click(
369
- fn=copy_text,
370
- inputs=[output_text],
371
- outputs=[copy_output, statistics_output]
372
- )
373
-
374
- clear_btn.click(
375
- fn=clear_all,
376
- outputs=[input_text, output_text, statistics_output, usage_output, entities_output, copy_output]
377
- )
378
-
379
- # مثال‌های نمونه
380
- gr.Examples(
381
- examples=[
382
- ["ایران خودرو در اسفندماه سال 1402 حدود 23 هزار و 296 میلیارد تومان درآمد کسب کرد که در مقایسه با بهمن 4.58 درصد افزایش داشت."],
383
- ["مهدی اخوان بهابادی، مدیرعامل همراه اول، اعلام کرد درآمد عملیاتی شرکت با رشد 37 درصدی به 70 هزار و 677 میلیارد تومان رسیده است."],
384
- ["بانک پاسارگاد با شناسایی سود خالص 155 هزار میلیارد ریالی در رده دوم سودآورترین بانک‌های کشور قرار گرفت."]
385
- ],
386
- inputs=input_text,
387
- label="📚 مثال‌های آزمایشی"
388
- )
389
-
390
- # راهنمای استفاده
391
- gr.Markdown("""
392
- ---
393
- ### 🎯 **ویژگی‌ها:**
394
- - 🏢 تشخیص نام شرکت‌ها و سازمان‌ها
395
- - 👤 تشخیص نام افراد با پیشوندهای مختلف
396
- - 💰 تشخیص مبالغ مالی و اعداد
397
- - 📊 تشخیص درصدها با فرمت‌های مختلف
398
- """)
399
-
400
- return interface
401
-
402
- # اجرای برنامه
403
- if __name__ == "__main__":
404
- interface = create_interface()
405
- interface.launch()