Opera10 commited on
Commit
30d71ad
·
verified ·
1 Parent(s): 4b69172

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -180
app.py CHANGED
@@ -1,181 +1,60 @@
1
- <!DOCTYPE html>
2
- <html lang="fa" dir="rtl">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>چت‌بات اختصاصی گِراک (Groq API)</title>
7
- <!-- لود کردن Tailwind CSS برای طراحی زیبا -->
8
- <script src="https://cdn.tailwindcss.com"></script>
9
- <style>
10
- @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;700&display=swap');
11
- body {
12
- font-family: 'Vazirmatn', sans-serif;
13
- }
14
- </style>
15
- </head>
16
- <body class="bg-gray-900 text-gray-100 min-h-screen flex flex-col justify-between">
17
-
18
- <!-- هدر برنامه -->
19
- <header class="bg-gray-800 border-b border-gray-700 p-4 shadow-md">
20
- <div class="max-w-4xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4">
21
- <h1 class="text-xl font-bold text-emerald-400">پنل تست سریع چت گِراک (Groq)</h1>
22
-
23
- <div class="flex flex-wrap items-center gap-2">
24
- <!-- انتخاب مدل -->
25
- <select id="model-select" class="bg-gray-700 text-white border border-gray-600 rounded p-2 text-sm focus:outline-none focus:border-emerald-500">
26
- <option value="llama-3.3-70b-versatile">Llama 3.3 70B (بسیار دقیق و قوی)</option>
27
- <option value="llama-3.1-8b-instant">Llama 3.1 8B (بسیار سریع)</option>
28
- </select>
29
-
30
- <!-- کادر کلید API -->
31
- <input type="password" id="api-key-input" placeholder="کلید API خود را وارد کنید (gsk_...)"
32
- class="bg-gray-700 text-white border border-gray-600 rounded p-2 text-sm w-64 focus:outline-none focus:border-emerald-500">
33
- </div>
34
- </div>
35
- </header>
36
-
37
- <!-- کادر نمایش چت‌ها -->
38
- <main class="flex-1 max-w-4xl w-full mx-auto p-4 overflow-y-auto space-y-4" style="height: calc(100vh - 180px);" id="chat-container">
39
- <!-- پیام خوش‌آمدگویی پیش‌فرض -->
40
- <div class="bg-gray-800 border border-gray-700 rounded-lg p-4 shadow-sm" id="welcome-message">
41
- <p class="text-emerald-400 font-bold mb-2">به پنل گِراک خوش آمدید!</p>
42
- <p class="text-sm text-gray-300 leading-relaxed">
43
- لطفاً کلید API دریافتی خود از کنسول گِراک را در کادر بالای صفحه قرار دهید. مدل دلخواه خود را انتخاب کرده و اولین پیام خود را در کادر پایین بنویسید. این فایل کاملاً آفلاین و ایمن است و اطلاعات شما به هیچ سرور واسطی ارسال نخواهد شد.
44
- </p>
45
- </div>
46
- </main>
47
-
48
- <!-- فوتر و کادر پیام ورودی -->
49
- <footer class="bg-gray-800 border-t border-gray-700 p-4 shadow-md">
50
- <div class="max-w-4xl mx-auto flex gap-2">
51
- <textarea id="user-input" rows="1" placeholder="پیام خود را بنویسید..."
52
- class="flex-1 bg-gray-700 text-white border border-gray-600 rounded-lg p-3 resize-none focus:outline-none focus:border-emerald-500 h-12 overflow-y-auto"></textarea>
53
- <button id="send-btn" class="bg-emerald-500 hover:bg-emerald-600 text-gray-900 font-bold px-6 rounded-lg transition duration-200">
54
- ارسال
55
- </button>
56
- </div>
57
- </footer>
58
-
59
- <script>
60
- const apiKeyInput = document.getElementById('api-key-input');
61
- const modelSelect = document.getElementById('model-select');
62
- const chatContainer = document.getElementById('chat-container');
63
- const userInput = document.getElementById('user-input');
64
- const sendBtn = document.getElementById('send-btn');
65
- const welcomeMessage = document.getElementById('welcome-message');
66
-
67
- // بازیابی خودکار کلید API ذخیره شده از حافظه مرورگر در صورت وجود
68
- const savedApiKey = localStorage.getItem('groq_api_key');
69
- if (savedApiKey) {
70
- apiKeyInput.value = savedApiKey;
71
- }
72
-
73
- // ذخیره خودکار کلید API هنگام تغییر مقدار کادر
74
- apiKeyInput.addEventListener('input', () => {
75
- localStorage.setItem('groq_api_key', apiKeyInput.value.trim());
76
- });
77
-
78
- // تابع ایجاد یک پیام جدید در صفحه
79
- function appendMessage(sender, text, isError = false) {
80
- if (welcomeMessage) {
81
- welcomeMessage.style.display = 'none';
82
- }
83
-
84
- const messageDiv = document.createElement('div');
85
- messageDiv.className = `p-4 rounded-lg shadow-sm leading-relaxed max-w-[85%] ${
86
- sender === 'user'
87
- ? 'bg-emerald-950/40 border border-emerald-800 text-emerald-100 mr-auto'
88
- : isError
89
- ? 'bg-rose-950/50 border border-rose-800 text-rose-200 ml-auto'
90
- : 'bg-gray-800 border border-gray-700 text-gray-100 ml-auto'
91
- }`;
92
-
93
- const senderLabel = document.createElement('div');
94
- senderLabel.className = `text-xs font-bold mb-1 ${sender === 'user' ? 'text-emerald-400' : 'text-gray-400'}`;
95
- senderLabel.innerText = sender === 'user' ? 'شما' : 'گِراک';
96
-
97
- const messageText = document.createElement('p');
98
- messageText.className = 'whitespace-pre-wrap text-sm';
99
- messageText.innerText = text;
100
-
101
- messageDiv.appendChild(senderLabel);
102
- messageDiv.appendChild(messageText);
103
- chatContainer.appendChild(messageDiv);
104
 
105
- // اسکرول خودکار به انتهای صفحه چت
106
- chatContainer.scrollTop = chatContainer.scrollHeight;
107
- }
108
-
109
- // عملکرد دکمه ارسال پیام
110
- async function handleSend() {
111
- const apiKey = apiKeyInput.value.trim();
112
- const messageText = userInput.value.trim();
113
- const model = modelSelect.value;
114
-
115
- if (!apiKey) {
116
- alert('لطفاً ابتدا کلید API خود را در بالای صفحه وارد کنید.');
117
- return;
118
- }
119
- if (!messageText) return;
120
-
121
- // نمایش پیام کاربر در صفحه
122
- appendMessage('user', messageText);
123
- userInput.value = '';
124
-
125
- // نمایش پیام موقت در حال بارگذاری
126
- const loadingId = 'msg-loading-' + Date.now();
127
- const loadingDiv = document.createElement('div');
128
- loadingDiv.id = loadingId;
129
- loadingDiv.className = 'bg-gray-800 border border-gray-700 text-gray-400 p-4 rounded-lg shadow-sm ml-auto max-w-[85%] animate-pulse';
130
- loadingDiv.innerText = 'درحال پاسخ‌دهی...';
131
- chatContainer.appendChild(loadingDiv);
132
- chatContainer.scrollTop = chatContainer.scrollHeight;
133
-
134
- try {
135
- // ارسال درخواست مستقیم به API رسمی گِراک
136
- const response = await fetch("https://api.groq.com/openai/v1/chat/completions", {
137
- method: "POST",
138
- headers: {
139
- "Authorization": `Bearer ${apiKey}`,
140
- "Content-Type": "application/json"
141
- },
142
- body: JSON.stringify({
143
- model: model,
144
- messages: [{ role: "user", content: messageText }],
145
- temperature: 0.7
146
- })
147
- });
148
-
149
- // حذف پیام بارگذاری
150
- document.getElementById(loadingId).remove();
151
-
152
- if (!response.ok) {
153
- const errData = await response.json();
154
- const errMsg = errData?.error?.message || `خطای ارتباط با سرور (${response.status})`;
155
- appendMessage('system', `خطا در دریافت پاسخ: ${errMsg}`, true);
156
- return;
157
- }
158
-
159
- const data = await response.json();
160
- const replyText = data.choices[0].message.content;
161
-
162
- // نمایش پاسخ نهایی هوش مصنوعی
163
- appendMessage('groq', replyText);
164
-
165
- } catch (error) {
166
- document.getElementById(loadingId).remove();
167
- appendMessage('system', `خطا در اتصال به اینترنت یا سرویس گِراک: ${error.message}`, true);
168
- }
169
- }
170
-
171
- // اتصال دکمه ارسال و کلید Enter به تابع ارسال پیام
172
- sendBtn.addEventListener('click', handleSend);
173
- userInput.addEventListener('keydown', (e) => {
174
- if (e.key === 'Enter' && !e.shiftKey) {
175
- e.preventDefault();
176
- handleSend();
177
- }
178
- });
179
- </script>
180
- </body>
181
- </html>
 
1
+ import os
2
+ import gradio as gr
3
+ from groq import Groq
4
+
5
+ # خواندن کلید مخفی شده از تنظیمات هاگینگ فیس
6
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
7
+
8
+ def transcribe_audio(audio_path):
9
+ if not GROQ_API_KEY:
10
+ return "خطا: کلید API یافت نشد. لطفا ابتدا GROQ_API_KEY را در تنظیمات اسپیس تعریف کنید.", []
11
+
12
+ if not audio_path:
13
+ return "لطفاً ابتدا یک فایل صوتی آپلود کنید.", []
14
+
15
+ try:
16
+ # ساخت کلاینت گراک با کلید امن شده
17
+ client = Groq(api_key=GROQ_API_KEY)
18
+
19
+ # خواندن فایل صوتی آپلود شده توسط کاربر
20
+ with open(audio_path, "rb") as file:
21
+ response = client.audio.transcriptions.create(
22
+ file=(audio_path, file.read()),
23
+ model="whisper-large-v3", # مدل ویسپر ۳ توربو
24
+ response_format="verbose_json", # فرمت خروجی حاوی زمان‌بندی
25
+ language="fa" # زبان فارسی
26
+ )
27
+
28
+ # دریافت متن کامل
29
+ full_text = getattr(response, "text", "")
30
+
31
+ # استخراج و مرتب‌سازی زمان‌بندی جملات
32
+ segments = []
33
+ raw_segments = getattr(response, "segments", [])
34
+ for idx, segment in enumerate(raw_segments):
35
+ segments.append({
36
+ "بخش": idx + 1,
37
+ روع انیه)": round(segment.get("start", 0), 2),
38
+ "پایان (ثانیه)": round(segment.get("end", 0), 2),
39
+ "متن جمله": segment.get("text", "").strip()
40
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ return full_text, segments
43
+
44
+ except Exception as e:
45
+ return f"خطا در پردازش صوتی: {str(e)}", []
46
+
47
+ # ساخت محیط وب ساده و تعاملی با Gradio
48
+ demo = gr.Interface(
49
+ fn=transcribe_audio,
50
+ inputs=gr.Audio(type="filepath", label="فایل صوتی خود را اینجا بکشید و رها کنید"),
51
+ outputs=[
52
+ gr.Textbox(label="متن کامل شناسایی شده (Full Text)"),
53
+ gr.JSON(label="زمان‌بندی دقیق جملات (Segments)")
54
+ ],
55
+ title="تست ابزار تبدیل صدا به متن Whisper v3",
56
+ description="فایل صوتی خود را آپلود کنید تا خروجی متنی و زمان‌بندی دقیق کلمات را در محیط هاگینگ فیس مشاهده کنید."
57
+ )
58
+
59
+ if __name__ == "__main__":
60
+ demo.launch()