tommy24 commited on
Commit
fe56189
·
1 Parent(s): 25ec7bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +230 -52
app.py CHANGED
@@ -315,15 +315,183 @@
315
  # iface.launch()
316
 
317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  import gradio as gr
319
  import numpy as np
320
  import cv2 as cv
321
  import requests
322
- import io
323
- from PIL import Image
324
  import os
325
  import tensorflow as tf
326
- import random
327
 
328
  host = os.environ.get("host")
329
  code = os.environ.get("code")
@@ -333,7 +501,6 @@ state = os.environ.get("state")
333
  system = os.environ.get("system")
334
  auth = os.environ.get("auth")
335
  auth2 = os.environ.get("auth2")
336
- data = None
337
 
338
  np.set_printoptions(suppress=True)
339
 
@@ -344,9 +511,15 @@ model = tf.keras.models.load_model('keras_model.h5')
344
  with open("labels.txt", "r") as file:
345
  labels = file.read().splitlines()
346
 
347
- messages = [
348
- {"role": "system", "content": system}
349
- ]
 
 
 
 
 
 
350
 
351
  def classify(platform, UserInput, Images, Textbox2, Textbox3):
352
  if Textbox3 == code:
@@ -359,6 +532,7 @@ def classify(platform, UserInput, Images, Textbox2, Textbox3):
359
  if platform == "wh":
360
  get_image = requests.get(Images, headers=headers)
361
  if get_image.status_code == 200:
 
362
  random_id = random.randint(1000, 9999)
363
  file_extension = ".png"
364
  filename = f"image_{random_id}{file_extension}"
@@ -368,70 +542,74 @@ def classify(platform, UserInput, Images, Textbox2, Textbox3):
368
 
369
  full_path = os.path.join(os.getcwd(), filename)
370
  print(f"Saved image as: {full_path}")
 
 
 
 
371
  elif platform == "web":
372
  print("WEB")
373
  # Handle web case if needed
374
  else:
375
  pass
376
 
377
- image = cv.imread(full_path)
378
- image = cv.resize(image, (224, 224))
379
- image_array = np.asarray(image)
380
- image_data = cv.resize(imageData, (224, 224))
381
- normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
382
- data[0] = normalized_image_array
 
383
 
384
- prediction = model.predict(data)
385
 
386
- max_label_index = None
387
- max_prediction_value = -1
388
 
389
- print('Prediction')
390
 
391
- Textbox2 = Textbox2.replace("[", "").replace("]", "").replace("'", "")
392
- Textbox2 = Textbox2.split(",")
393
- Textbox2_edited = [x.strip() for x in Textbox2]
394
- Textbox2_edited = list(Textbox2_edited)
395
- Textbox2_edited.append(UserInput)
396
- messages.append({"role": "user", "content": UserInput})
397
 
398
- for i, label in enumerate(labels):
399
- prediction_value = float(prediction[0][i])
400
- rounded_value = round(prediction_value, 2)
401
- print(f'{label}: {rounded_value}')
402
 
403
- if prediction_value > max_prediction_value:
404
- max_label_index = i
405
- max_prediction_value = prediction_value
406
 
407
- if max_label_index is not None:
408
- max_label = labels[max_label_index].split(' ', 1)[1]
409
- max_rounded_prediction = round(max_prediction_value, 2)
410
- print(f'Maximum Prediction: {max_label} with a value of {max_rounded_prediction}')
411
 
412
- if max_rounded_prediction > 0.5:
413
- print("\nWays to dispose of this waste: " + max_label)
414
- messages.append({"role": "user", "content": content + " " + max_label})
415
 
416
- headers = {
417
- "Content-Type": "application/json",
418
- "Authorization": f"Bearer {auth}"
419
- }
420
 
421
- response = requests.post(host, headers=headers, json={
422
- "messages": messages,
423
- "model": model_llm
424
- }).json()
425
 
426
- reply = response["choices"][0]["message"]["content"]
427
- messages.append({"role": "assistant", "content": reply})
428
 
429
- output.append({"Mode": "Image", "type": max_label, "prediction_value": max_rounded_prediction, "content": reply})
430
- elif max_rounded_prediction < 0.5:
431
- output.append({"Mode": "Image", "type": "Not predictable", "prediction_value": max_rounded_prediction, "content": "Seems like the prediction rate is too low due to that won't be able to predict the type of material. Try again with a cropped image or different one"})
432
 
433
  return output
434
-
435
  else:
436
  output = []
437
 
@@ -449,7 +627,7 @@ def classify(platform, UserInput, Images, Textbox2, Textbox3):
449
  messages.append({"role": "user", "content": UserInput})
450
 
451
  headers = {
452
- "Content-Type": "application/json",
453
  "Authorization": f"Bearer {auth}"
454
  }
455
 
 
315
  # iface.launch()
316
 
317
 
318
+ # import gradio as gr
319
+ # import numpy as np
320
+ # import cv2 as cv
321
+ # import requests
322
+ # import io
323
+ # from PIL import Image
324
+ # import os
325
+ # import tensorflow as tf
326
+ # import random
327
+
328
+ # host = os.environ.get("host")
329
+ # code = os.environ.get("code")
330
+ # model_llm = os.environ.get("model")
331
+ # content = os.environ.get("content")
332
+ # state = os.environ.get("state")
333
+ # system = os.environ.get("system")
334
+ # auth = os.environ.get("auth")
335
+ # auth2 = os.environ.get("auth2")
336
+ # data = None
337
+
338
+ # np.set_printoptions(suppress=True)
339
+
340
+ # # Load the model outside of the function
341
+ # model = tf.keras.models.load_model('keras_model.h5')
342
+
343
+ # # Load labels from a file
344
+ # with open("labels.txt", "r") as file:
345
+ # labels = file.read().splitlines()
346
+
347
+ # messages = [
348
+ # {"role": "system", "content": system}
349
+ # ]
350
+
351
+ # def classify(platform, UserInput, Images, Textbox2, Textbox3):
352
+ # if Textbox3 == code:
353
+ # imageData = None
354
+ # if Images is not None:
355
+ # output = []
356
+ # headers = {
357
+ # "Authorization": f"Bearer {auth2}"
358
+ # }
359
+ # if platform == "wh":
360
+ # get_image = requests.get(Images, headers=headers)
361
+ # if get_image.status_code == 200:
362
+ # random_id = random.randint(1000, 9999)
363
+ # file_extension = ".png"
364
+ # filename = f"image_{random_id}{file_extension}"
365
+ # with open(filename, "wb") as file:
366
+ # file.write(get_image.content)
367
+ # print(f"Saved image as: {filename}")
368
+
369
+ # full_path = os.path.join(os.getcwd(), filename)
370
+ # print(f"Saved image as: {full_path}")
371
+ # elif platform == "web":
372
+ # print("WEB")
373
+ # # Handle web case if needed
374
+ # else:
375
+ # pass
376
+
377
+ # image = cv.imread(full_path)
378
+ # image = cv.resize(image, (224, 224))
379
+ # image_array = np.asarray(image)
380
+ # image_data = cv.resize(imageData, (224, 224))
381
+ # normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
382
+ # data[0] = normalized_image_array
383
+
384
+ # prediction = model.predict(data)
385
+
386
+ # max_label_index = None
387
+ # max_prediction_value = -1
388
+
389
+ # print('Prediction')
390
+
391
+ # Textbox2 = Textbox2.replace("[", "").replace("]", "").replace("'", "")
392
+ # Textbox2 = Textbox2.split(",")
393
+ # Textbox2_edited = [x.strip() for x in Textbox2]
394
+ # Textbox2_edited = list(Textbox2_edited)
395
+ # Textbox2_edited.append(UserInput)
396
+ # messages.append({"role": "user", "content": UserInput})
397
+
398
+ # for i, label in enumerate(labels):
399
+ # prediction_value = float(prediction[0][i])
400
+ # rounded_value = round(prediction_value, 2)
401
+ # print(f'{label}: {rounded_value}')
402
+
403
+ # if prediction_value > max_prediction_value:
404
+ # max_label_index = i
405
+ # max_prediction_value = prediction_value
406
+
407
+ # if max_label_index is not None:
408
+ # max_label = labels[max_label_index].split(' ', 1)[1]
409
+ # max_rounded_prediction = round(max_prediction_value, 2)
410
+ # print(f'Maximum Prediction: {max_label} with a value of {max_rounded_prediction}')
411
+
412
+ # if max_rounded_prediction > 0.5:
413
+ # print("\nWays to dispose of this waste: " + max_label)
414
+ # messages.append({"role": "user", "content": content + " " + max_label})
415
+
416
+ # headers = {
417
+ # "Content-Type": "application/json",
418
+ # "Authorization": f"Bearer {auth}"
419
+ # }
420
+
421
+ # response = requests.post(host, headers=headers, json={
422
+ # "messages": messages,
423
+ # "model": model_llm
424
+ # }).json()
425
+
426
+ # reply = response["choices"][0]["message"]["content"]
427
+ # messages.append({"role": "assistant", "content": reply})
428
+
429
+ # output.append({"Mode": "Image", "type": max_label, "prediction_value": max_rounded_prediction, "content": reply})
430
+ # elif max_rounded_prediction < 0.5:
431
+ # output.append({"Mode": "Image", "type": "Not predictable", "prediction_value": max_rounded_prediction, "content": "Seems like the prediction rate is too low due to that won't be able to predict the type of material. Try again with a cropped image or different one"})
432
+
433
+ # return output
434
+
435
+ # else:
436
+ # output = []
437
+
438
+ # Textbox2 = Textbox2.replace("[", "").replace("]", "").replace("'", "")
439
+ # Textbox2 = Textbox2.split(",")
440
+ # Textbox2_edited = [x.strip() for x in Textbox2]
441
+ # Textbox2_edited = list(Textbox2_edited)
442
+ # Textbox2_edited.append(UserInput)
443
+
444
+ # for i in Textbox2_edited:
445
+ # messages.append({"role": "user", "content": i})
446
+
447
+ # print("messages after appending:", messages)
448
+
449
+ # messages.append({"role": "user", "content": UserInput})
450
+
451
+ # headers = {
452
+ # "Content-Type": "application/json",
453
+ # "Authorization": f"Bearer {auth}"
454
+ # }
455
+
456
+ # response = requests.post(host, headers=headers, json={
457
+ # "messages": messages,
458
+ # "model": model_llm
459
+ # }).json()
460
+
461
+ # reply = response["choices"][0]["message"]["content"]
462
+ # messages.append({"role": "assistant", "content": reply})
463
+
464
+ # output.append({"Mode": "Chat", "content": reply})
465
+
466
+ # return output
467
+ # else:
468
+ # return "Unauthorized"
469
+
470
+ # user_inputs = [
471
+ # gr.Textbox(label="Platform", type="text"),
472
+ # gr.Textbox(label="User Input", type="text"),
473
+ # gr.Textbox(label="Image", type="text"),
474
+ # gr.Textbox(label="Textbox2", type="text"),
475
+ # gr.Textbox(label="Textbox3", type="password")
476
+ # ]
477
+
478
+ # iface = gr.Interface(
479
+ # fn=classify,
480
+ # inputs=user_inputs,
481
+ # outputs=gr.outputs.JSON(),
482
+ # title="Classifier",
483
+ # )
484
+ # iface.launch()
485
+
486
+
487
  import gradio as gr
488
  import numpy as np
489
  import cv2 as cv
490
  import requests
491
+ import random
 
492
  import os
493
  import tensorflow as tf
494
+ import base64
495
 
496
  host = os.environ.get("host")
497
  code = os.environ.get("code")
 
501
  system = os.environ.get("system")
502
  auth = os.environ.get("auth")
503
  auth2 = os.environ.get("auth2")
 
504
 
505
  np.set_printoptions(suppress=True)
506
 
 
511
  with open("labels.txt", "r") as file:
512
  labels = file.read().splitlines()
513
 
514
+ messages = [{"role": "system", "content": system}]
515
+
516
+ def save_image_as_base64(image_content, file_extension=".png"):
517
+ # Encode the image content as base64
518
+ image_base64 = base64.b64encode(image_content).decode("utf-8")
519
+
520
+ # Construct the data URL
521
+ data_url = f"data:image/{file_extension};base64,{image_base64}"
522
+ return data_url
523
 
524
  def classify(platform, UserInput, Images, Textbox2, Textbox3):
525
  if Textbox3 == code:
 
532
  if platform == "wh":
533
  get_image = requests.get(Images, headers=headers)
534
  if get_image.status_code == 200:
535
+ # Generate a random ID for the file
536
  random_id = random.randint(1000, 9999)
537
  file_extension = ".png"
538
  filename = f"image_{random_id}{file_extension}"
 
542
 
543
  full_path = os.path.join(os.getcwd(), filename)
544
  print(f"Saved image as: {full_path}")
545
+
546
+ # Convert the image content to base64
547
+ image_data_url = save_image_as_base64(get_image.content, file_extension)
548
+ print(f"Data URL of the image: {image_data_url}")
549
  elif platform == "web":
550
  print("WEB")
551
  # Handle web case if needed
552
  else:
553
  pass
554
 
555
+ if imageData is not None:
556
+ image = cv.imread(full_path)
557
+ image = cv.resize(image, (224, 224))
558
+ image_array = np.asarray(image)
559
+ image_data = cv.resize(imageData, (224, 224))
560
+ normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
561
+ data[0] = normalized_image_array
562
 
563
+ prediction = model.predict(data)
564
 
565
+ max_label_index = None
566
+ max_prediction_value = -1
567
 
568
+ print('Prediction')
569
 
570
+ Textbox2 = Textbox2.replace("[", "").replace("]", "").replace("'", "")
571
+ Textbox2 = Textbox2.split(",")
572
+ Textbox2_edited = [x.strip() for x in Textbox2]
573
+ Textbox2_edited = list(Textbox2_edited)
574
+ Textbox2_edited.append(UserInput)
575
+ messages.append({"role": "user", "content": UserInput})
576
 
577
+ for i, label in enumerate(labels):
578
+ prediction_value = float(prediction[0][i])
579
+ rounded_value = round(prediction_value, 2)
580
+ print(f'{label}: {rounded_value}')
581
 
582
+ if prediction_value > max_prediction_value:
583
+ max_label_index = i
584
+ max_prediction_value = prediction_value
585
 
586
+ if max_label_index is not None:
587
+ max_label = labels[max_label_index].split(' ', 1)[1]
588
+ max_rounded_prediction = round(max_prediction_value, 2)
589
+ print(f'Maximum Prediction: {max_label} with a value of {max_rounded_prediction}')
590
 
591
+ if max_rounded_prediction > 0.5:
592
+ print("\nWays to dispose of this waste: " + max_label)
593
+ messages.append({"role": "user", "content": content + " " + max_label})
594
 
595
+ headers = {
596
+ "Content-Type": "application/json",
597
+ "Authorization": f"Bearer {auth}"
598
+ }
599
 
600
+ response = requests.post(host, headers=headers, json={
601
+ "messages": messages,
602
+ "model": model_llm
603
+ }).json()
604
 
605
+ reply = response["choices"][0]["message"]["content"]
606
+ messages.append({"role": "assistant", "content": reply})
607
 
608
+ output.append({"Mode": "Image", "type": max_label, "prediction_value": max_rounded_prediction, "content": reply})
609
+ elif max_rounded_prediction < 0.5:
610
+ output.append({"Mode": "Image", "type": "Not predictable", "prediction_value": max_rounded_prediction, "content": "Seems like the prediction rate is too low due to that won't be able to predict the type of material. Try again with a cropped image or different one"})
611
 
612
  return output
 
613
  else:
614
  output = []
615
 
 
627
  messages.append({"role": "user", "content": UserInput})
628
 
629
  headers = {
630
+ "Content-Type": "application.json",
631
  "Authorization": f"Bearer {auth}"
632
  }
633