shukdevdatta123 commited on
Commit
6f32a8f
·
verified ·
1 Parent(s): d84cefc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -377
app.py CHANGED
@@ -1,388 +1,42 @@
1
- import gradio as gr
2
- import openai
3
- import fitz # PyMuPDF for PDF processing
4
- import base64
5
- import io
6
 
7
- # Variable to store API key
8
- api_key = ""
9
 
10
- # Function to update API key
11
- def set_api_key(key):
12
- global api_key
13
- api_key = key
14
- return "API Key Set Successfully!"
15
 
16
- # Function to interact with OpenAI API
17
- def query_openai(messages, temperature, top_p, max_output_tokens):
18
- if not api_key:
19
- return "Please enter your OpenAI API key first."
 
20
 
21
- try:
22
- openai.api_key = api_key # Set API key dynamically
23
 
24
- # Ensure numeric values for OpenAI parameters
25
- temperature = float(temperature) if temperature else 1.0
26
- top_p = float(top_p) if top_p else 1.0
27
- max_output_tokens = int(max_output_tokens) if max_output_tokens else 2048
28
 
29
- response = openai.ChatCompletion.create(
30
- model="gpt-4.1",
31
- messages=messages,
32
- temperature=temperature,
33
- top_p=top_p,
34
- max_tokens=max_output_tokens
35
- )
36
- return response["choices"][0]["message"]["content"]
37
- except Exception as e:
38
- return f"Error: {str(e)}"
39
 
40
- # Function to process image URL input
41
- def image_url_chat(image_url, text_query, temperature, top_p, max_output_tokens):
42
- if not image_url or not text_query:
43
- return "Please provide an image URL and a query."
44
 
45
- messages = [
46
- {"role": "user", "content": [
47
- {"type": "image_url", "image_url": {"url": image_url}},
48
- {"type": "text", "text": text_query}
49
- ]},
50
- ]
51
- return query_openai(messages, temperature, top_p, max_output_tokens)
52
 
53
- # Function to process text input
54
- def text_chat(text_query, temperature, top_p, max_output_tokens):
55
- if not text_query:
56
- return "Please enter a query."
 
57
 
58
- messages = [{"role": "user", "content": [{"type": "text", "text": text_query}]}]
59
- return query_openai(messages, temperature, top_p, max_output_tokens)
60
-
61
- # Function to process uploaded image input
62
- def image_chat(image_file, text_query, temperature, top_p, max_output_tokens):
63
- if image_file is None or not text_query:
64
- return "Please upload an image and provide a query."
65
-
66
- # Encode image as base64
67
- with open(image_file, "rb") as img:
68
- base64_image = base64.b64encode(img.read()).decode("utf-8")
69
-
70
- image_data = f"data:image/jpeg;base64,{base64_image}"
71
-
72
- messages = [
73
- {"role": "user", "content": [
74
- {"type": "image_url", "image_url": {"url": image_data}},
75
- {"type": "text", "text": text_query}
76
- ]},
77
- ]
78
- return query_openai(messages, temperature, top_p, max_output_tokens)
79
-
80
- # Function to process uploaded PDF input
81
- def pdf_chat(pdf_file, text_query, temperature, top_p, max_output_tokens):
82
- if pdf_file is None or not text_query:
83
- return "Please upload a PDF and provide a query."
84
-
85
- try:
86
- # Extract text from all pages of the PDF
87
- doc = fitz.open(pdf_file.name)
88
- text = "\n".join([page.get_text("text") for page in doc]) # Extract text from all pages
89
-
90
- # If no text found, return an error
91
- if not text.strip():
92
- return "No text found in the PDF."
93
-
94
- # Create the query message with the extracted text and the user's query
95
- messages = [
96
- {"role": "user", "content": [
97
- {"type": "text", "text": text}, # The extracted text from the PDF
98
- {"type": "text", "text": text_query}
99
- ]},
100
- ]
101
- return query_openai(messages, temperature, top_p, max_output_tokens)
102
-
103
- except Exception as e:
104
- return f"Error processing the PDF: {str(e)}"
105
-
106
- # Function to transcribe audio to text using OpenAI Whisper API
107
- def transcribe_audio(audio_binary, openai_api_key):
108
- if not openai_api_key:
109
- return "Error: No API key provided."
110
-
111
- openai.api_key = openai_api_key
112
-
113
- try:
114
- # Use the correct transcription API call
115
- audio_file_obj = io.BytesIO(audio_binary)
116
- audio_file_obj.name = 'audio.wav' # Set a name for the file object (as OpenAI expects it)
117
-
118
- # Transcribe the audio to text using OpenAI's whisper model
119
- audio_file_transcription = openai.Audio.transcribe(file=audio_file_obj, model="whisper-1")
120
- return audio_file_transcription.text
121
- except Exception as e:
122
- return f"Error transcribing audio: {str(e)}"
123
-
124
- # Function to handle uploaded audio transcription
125
- def process_uploaded_audio(audio_binary):
126
- if not audio_binary:
127
- return "Please upload an audio file first."
128
-
129
- if not api_key:
130
- return "Please enter your OpenAI API key first."
131
-
132
- try:
133
- transcription = transcribe_audio(audio_binary, api_key)
134
- return transcription
135
- except Exception as e:
136
- return f"Error transcribing audio: {str(e)}"
137
-
138
- # Function to handle recorded audio transcription
139
- def process_recorded_audio(audio_path):
140
- if not audio_path:
141
- return "No audio recorded."
142
-
143
- if not api_key:
144
- return "Please enter your OpenAI API key first."
145
-
146
- try:
147
- with open(audio_path, "rb") as audio_file:
148
- audio_binary = audio_file.read()
149
-
150
- transcription = transcribe_audio(audio_binary, api_key)
151
- return transcription
152
- except Exception as e:
153
- return f"Error transcribing recorded audio: {str(e)}"
154
-
155
- # Function to process the voice chat queries
156
- def process_voice_query(transcription, temperature, top_p, max_output_tokens):
157
- if not transcription or transcription.startswith("Error") or transcription.startswith("Please"):
158
- return "Please ensure audio is transcribed successfully first."
159
-
160
- # Use the transcription as the query
161
- messages = [{"role": "user", "content": [{"type": "text", "text": transcription}]}]
162
-
163
- return query_openai(messages, temperature, top_p, max_output_tokens)
164
-
165
- # Function to clear the chat - FIXED to return the correct types for file inputs
166
- def clear_chat():
167
- # For file components like gr.File and gr.Audio, we should return None
168
- # For text components, return empty string
169
- # For sliders, return default values
170
-
171
- # The order must match exactly with the outputs in clear_button.click()
172
- return (
173
- "", # image_url (textbox)
174
- "", # image_query (textbox)
175
- "", # image_url_output (textbox)
176
- "", # text_query (textbox)
177
- "", # text_output (textbox)
178
- "", # image_text_query (textbox)
179
- "", # image_output (textbox)
180
- None, # pdf_upload (file)
181
- "", # pdf_text_query (textbox)
182
- "", # pdf_output (textbox)
183
- None, # audio_upload (file)
184
- "", # upload_transcription (textbox)
185
- "", # upload_audio_output (textbox)
186
- None, # audio_recorder (audio)
187
- "", # record_transcription (textbox)
188
- "", # record_audio_output (textbox)
189
- 1.0, # temperature (slider)
190
- 1.0, # top_p (slider)
191
- 2048 # max_output_tokens (slider)
192
- )
193
-
194
- # Gradio UI Layout
195
- with gr.Blocks(theme=gr.themes.Ocean()) as demo:
196
- gr.Markdown("## GPT-4.5 Preview Chatbot")
197
-
198
- with gr.Accordion("How to Use This App!", open=False, elem_id="neuroscope-accordion"):
199
- gr.Markdown("""
200
- ### Getting Started:
201
- 1. Enter your OpenAI API key in the field at the top and click "Set API Key"
202
- 2. Adjust the hyperparameters if needed (Temperature, Top-P, Max Output Tokens)
203
-
204
- ### Using the Different Tabs:
205
-
206
- #### Image URL Chat
207
- - Paste an image URL in the field
208
- - Enter your question about the image
209
- - Click "Ask" to get a response
210
-
211
- #### Text Chat
212
- - Simply type your query in the text field
213
- - Click "Ask" to get a response
214
-
215
- #### Image Chat
216
- - Upload an image from your device
217
- - Enter your question about the uploaded image
218
- - Click "Ask" to get a response
219
-
220
- #### PDF Chat
221
- - Upload a PDF document
222
- - Ask questions about the PDF content
223
- - Click "Ask" to get a response
224
-
225
- #### Voice Chat
226
- - **Upload Audio:** Upload an audio file, click "Transcribe Audio", then click "Ask"
227
- - **Record Audio:** Record your voice, click "Transcribe Recording", then click "Ask"
228
-
229
- ### Tips:
230
- - Use the "Clear Chat" button to reset all fields
231
- - For more creative responses, try increasing the Temperature
232
- - For longer responses, increase the Max Output Tokens
233
- """)
234
-
235
- # Accordion for explaining hyperparameters
236
- with gr.Accordion("Hyperparameters", open=False, elem_id="neuroscope-accordion"):
237
- gr.Markdown("""
238
- ### Temperature:
239
- Controls the randomness of the model's output. A lower temperature makes the model more deterministic, while a higher temperature makes it more creative and varied.
240
- ### Top-P (Nucleus Sampling):
241
- Controls the cumulative probability distribution from which the model picks the next word. A lower value makes the model more focused and deterministic, while a higher value increases randomness.
242
- ### Max Output Tokens:
243
- Limits the number of tokens (words or subwords) the model can generate in its response. You can use this to control the length of the response.
244
- """)
245
-
246
- gr.HTML("""
247
- <style>
248
- #api_key_button {
249
- margin-top: 27px; /* Add margin-top to the button */
250
- background: linear-gradient(135deg, #4a00e0 0%, #8e2de2 100%); /* Purple gradient */
251
- }
252
- #api_key_button:hover {
253
- background: linear-gradient(135deg, #5b10f1 0%, #9f3ef3 100%); /* Slightly lighter */
254
- }
255
- #clear_chat_button {
256
- background: linear-gradient(135deg, #e53e3e 0%, #f56565 100%); /* Red gradient */
257
- }
258
- #clear_chat_button:hover {
259
- background: linear-gradient(135deg, #c53030 0%, #e53e3e 100%); /* Slightly darker red gradient on hover */
260
- }
261
- #ask_button {
262
- background: linear-gradient(135deg, #fbd38d 0%, #f6e05e 100%); /* Yellow gradient */
263
- }
264
- #ask_button:hover {
265
- background: linear-gradient(135deg, #ecc94b 0%, #fbd38d 100%); /* Slightly darker yellow gradient on hover */
266
- }
267
- #transcribe_button {
268
- background: linear-gradient(135deg, #68d391 0%, #48bb78 100%); /* Green gradient */
269
- }
270
-
271
- #transcribe_button:hover {
272
- background: linear-gradient(135deg, #38a169 0%, #68d391 100%); /* Slightly darker green gradient on hover */
273
- }
274
- #neuroscope-accordion {
275
- background: linear-gradient(to right, #00ff94, #00b4db);
276
- border-radius: 8px;
277
- }
278
- </style>
279
- """)
280
-
281
- # API Key Input
282
- with gr.Row():
283
- api_key_input = gr.Textbox(label="Enter OpenAI API Key", type="password")
284
- api_key_button = gr.Button("Set API Key", elem_id="api_key_button")
285
- api_key_output = gr.Textbox(label="API Key Status", interactive=False)
286
-
287
- with gr.Row():
288
- temperature = gr.Slider(0, 2, value=1.0, step=0.1, label="Temperature")
289
- top_p = gr.Slider(0, 1, value=1.0, step=0.1, label="Top-P")
290
- max_output_tokens = gr.Slider(0, 16384, value=2048, step=512, label="Max Output Tokens")
291
-
292
- with gr.Tabs():
293
- with gr.Tab("Image URL Chat"):
294
- image_url = gr.Textbox(label="Enter Image URL")
295
- image_query = gr.Textbox(label="Ask about the Image")
296
- image_url_output = gr.Textbox(label="Response", interactive=False)
297
- image_url_button = gr.Button("Ask", elem_id="ask_button")
298
-
299
- with gr.Tab("Text Chat"):
300
- text_query = gr.Textbox(label="Enter your query")
301
- text_output = gr.Textbox(label="Response", interactive=False)
302
- text_button = gr.Button("Ask", elem_id="ask_button")
303
-
304
- with gr.Tab("Image Chat"):
305
- image_upload = gr.File(label="Upload an Image", type="filepath")
306
- image_text_query = gr.Textbox(label="Ask about the uploaded image")
307
- image_output = gr.Textbox(label="Response", interactive=False)
308
- image_button = gr.Button("Ask", elem_id="ask_button")
309
-
310
- with gr.Tab("PDF Chat"):
311
- pdf_upload = gr.File(label="Upload a PDF", type="filepath")
312
- pdf_text_query = gr.Textbox(label="Ask about the uploaded PDF")
313
- pdf_output = gr.Textbox(label="Response", interactive=False)
314
- pdf_button = gr.Button("Ask", elem_id="ask_button")
315
-
316
- with gr.Tab("Voice Chat"):
317
- with gr.Tabs():
318
- with gr.Tab("Upload Audio"):
319
- # Upload audio section
320
- audio_upload = gr.File(label="Upload an Audio File", type="binary")
321
- upload_transcribe_button = gr.Button("Transcribe Audio", elem_id="transcribe_button")
322
- upload_transcription = gr.Textbox(label="Transcription", interactive=False)
323
- upload_audio_output = gr.Textbox(label="Response", interactive=False)
324
- upload_audio_button = gr.Button("Ask", elem_id="ask_button")
325
-
326
- with gr.Tab("Record Audio"):
327
- # Record audio section
328
- audio_recorder = gr.Audio(label="Record your voice", type="filepath")
329
- record_transcribe_button = gr.Button("Transcribe Recording", elem_id="transcribe_button")
330
- record_transcription = gr.Textbox(label="Transcription", interactive=False)
331
- record_audio_output = gr.Textbox(label="Response", interactive=False)
332
- record_audio_button = gr.Button("Ask", elem_id="ask_button")
333
-
334
- # Clear chat button
335
- clear_button = gr.Button("Clear Chat", elem_id="clear_chat_button")
336
-
337
- # Button Click Actions
338
- api_key_button.click(set_api_key, inputs=[api_key_input], outputs=[api_key_output])
339
- image_url_button.click(image_url_chat, [image_url, image_query, temperature, top_p, max_output_tokens], image_url_output)
340
- text_button.click(text_chat, [text_query, temperature, top_p, max_output_tokens], text_output)
341
- image_button.click(image_chat, [image_upload, image_text_query, temperature, top_p, max_output_tokens], image_output)
342
- pdf_button.click(pdf_chat, [pdf_upload, pdf_text_query, temperature, top_p, max_output_tokens], pdf_output)
343
-
344
- # Voice Chat - Upload Audio tab actions
345
- upload_transcribe_button.click(
346
- process_uploaded_audio,
347
- inputs=[audio_upload],
348
- outputs=[upload_transcription]
349
- )
350
-
351
- # FIXED: Properly order the inputs to process_voice_query
352
- upload_audio_button.click(
353
- process_voice_query,
354
- inputs=[upload_transcription, temperature, top_p, max_output_tokens],
355
- outputs=[upload_audio_output]
356
- )
357
-
358
- # Voice Chat - Record Audio tab actions
359
- record_transcribe_button.click(
360
- process_recorded_audio,
361
- inputs=[audio_recorder],
362
- outputs=[record_transcription]
363
- )
364
-
365
- # FIXED: Properly order the inputs to process_voice_query
366
- record_audio_button.click(
367
- process_voice_query,
368
- inputs=[record_transcription, temperature, top_p, max_output_tokens],
369
- outputs=[record_audio_output]
370
- )
371
-
372
- # Clear button resets all necessary fields
373
- clear_button.click(
374
- clear_chat,
375
- outputs=[
376
- image_url, image_query, image_url_output,
377
- text_query, text_output,
378
- image_text_query, image_output,
379
- pdf_upload, pdf_text_query, pdf_output,
380
- audio_upload, upload_transcription, upload_audio_output,
381
- audio_recorder, record_transcription, record_audio_output,
382
- temperature, top_p, max_output_tokens
383
- ]
384
- )
385
-
386
- # Launch Gradio App
387
  if __name__ == "__main__":
388
- demo.launch()
 
 
 
 
1
+ from Crypto.Cipher import AES
2
+ from Crypto.Protocol.KDF import PBKDF2
3
+ import os
4
+ import tempfile
5
+ from dotenv import load_dotenv
6
 
7
+ load_dotenv() # Load all environment variables
 
8
 
9
+ def unpad(data):
10
+ return data[:-data[-1]]
 
 
 
11
 
12
+ def decrypt_and_run():
13
+ # Get password from Hugging Face Secrets environment variable
14
+ password = os.getenv("PASSWORD")
15
+ if not password:
16
+ raise ValueError("PASSWORD secret not found in environment variables")
17
 
18
+ password = password.encode()
 
19
 
20
+ with open("code.enc", "rb") as f:
21
+ encrypted = f.read()
 
 
22
 
23
+ salt = encrypted[:16]
24
+ iv = encrypted[16:32]
25
+ ciphertext = encrypted[32:]
 
 
 
 
 
 
 
26
 
27
+ key = PBKDF2(password, salt, dkLen=32, count=1000000)
28
+ cipher = AES.new(key, AES.MODE_CBC, iv)
 
 
29
 
30
+ plaintext = unpad(cipher.decrypt(ciphertext))
 
 
 
 
 
 
31
 
32
+ with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode='wb') as tmp:
33
+ tmp.write(plaintext)
34
+ tmp.flush()
35
+ print(f"[INFO] Running decrypted code from {tmp.name}")
36
+ os.system(f"python {tmp.name}")
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  if __name__ == "__main__":
39
+ decrypt_and_run()
40
+
41
+ # This script decrypts the encrypted code and runs it.
42
+ # Ensure you have the PASSWORD secret set in your Hugging Face Secrets