PuristanLabs1 commited on
Commit
a26c52d
·
verified ·
1 Parent(s): d7404e6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -50
app.py CHANGED
@@ -16,14 +16,25 @@ from PIL import Image
16
  import os
17
  import uuid
18
  import logging # Add this line
 
 
19
 
20
  # Set up logging
21
  logging.basicConfig(level=logging.DEBUG)
22
 
 
 
 
 
 
 
 
 
 
23
  #IMAGE_DIR = "./images"
24
  IMAGE_DIR = "/tmp"
25
  os.makedirs(IMAGE_DIR, exist_ok=True)
26
- IMGUR_CLIENT_ID = "429c0410bdece6a"
27
 
28
  GITHUB_API_URL = "https://api.github.com/search/repositories"
29
  ACCESS_TOKEN = os.getenv("github_pat")
@@ -50,7 +61,25 @@ embeddings = topic_data["embeddings"]
50
 
51
  discovered_repos = []
52
 
53
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  def search_similar_topics(input_text):
55
  if not input_text.strip():
56
  return "Enter topics to see suggestions."
@@ -484,65 +513,34 @@ def validate_and_fix_dot_code(dot_code):
484
  return dot_code
485
 
486
  def render_dot_code(dot_code, filename=None):
487
- """
488
- Renders Graphviz DOT code and uploads it to Imgur.
489
-
490
- Args:
491
- dot_code (str): The DOT code to render.
492
- filename (str): Optional name for the output file (used for debugging purposes).
493
-
494
- Returns:
495
- str: Imgur URL of the uploaded image, or error message.
496
- """
497
  if not filename:
498
- filename = f"diagram_{uuid.uuid4().hex}"
499
- # Add /tmp directory to the filename
500
- filename = os.path.join("/tmp", filename)
501
-
502
- print(f"Using IMGUR_CLIENT_ID: {IMGUR_CLIENT_ID}")
503
-
504
  try:
505
  # Render the DOT code to an in-memory PNG
506
  src = Source(dot_code, format="png")
507
- rendered_png = src.pipe()
508
-
509
- # Ensure IMGUR_CLIENT_ID is set
510
- if not IMGUR_CLIENT_ID:
511
- raise ValueError("IMGUR_CLIENT_ID is not set")
512
-
513
- # Upload the rendered PNG to Imgur
514
- headers = {"Authorization": f"Client-ID {IMGUR_CLIENT_ID}"}
515
- #files = {"image": rendered_png}
516
- files = {"image": ("image.png", rendered_png, "image/png")}
517
- logging.debug(f"Sending request to Imgur with headers: {headers}")
518
- response = requests.post("https://api.imgur.com/3/image", headers=headers, files=files)
519
-
520
- logging.debug(f"Imgur response status code: {response.status_code}")
521
- logging.debug(f"Imgur response content: {response.text}")
522
-
523
- if response.status_code == 200:
524
- imgur_url = response.json()["data"]["link"]
525
- logging.info(f"Diagram successfully uploaded to Imgur: {imgur_url}")
526
- print(f"Diagram successfully uploaded to Imgur: {imgur_url}")
527
- return imgur_url
528
- else:
529
- error_message = response.json().get("data", {}).get("error", "Unknown error")
530
- raise Exception(f"Imgur upload failed: {error_message}. Response: {response.text}")
531
 
532
  except Exception as e:
533
- logging.error(f"Error rendering or uploading diagram: {e}", exc_info=True)
534
  return f"Error rendering or uploading diagram: {str(e)}"
535
-
 
536
  import time
537
 
538
  def handle_generate_diagram(code_content, diagram_type, retries=5, wait_time=1):
539
 
540
- imgur_url = render_dot_code(generate_dot_code_from_code(code_content, diagram_type))
541
- if imgur_url.startswith("http"): # Check if the response is a valid URL
542
- return f'<img src="{imgur_url}" alt="Generated Diagram" style="max-width: 100%; height: auto;">'
543
  else:
544
- return f"<p>Error: {imgur_url}</p>" # Return the error message in HTML format
545
-
546
 
547
  # Gradio Interface
548
  with gr.Blocks() as demo:
@@ -692,7 +690,6 @@ with gr.Blocks() as demo:
692
  )
693
  generate_diagram_button = gr.Button("Generate Diagram")
694
  with gr.Row():
695
-
696
  diagram_output = gr.HTML(
697
  label="Generated Diagram",
698
 
 
16
  import os
17
  import uuid
18
  import logging # Add this line
19
+ import boto3
20
+ from botocore.exceptions import NoCredentialsError, PartialCredentialsError
21
 
22
  # Set up logging
23
  logging.basicConfig(level=logging.DEBUG)
24
 
25
+ # Initialize the S3 client
26
+ s3_client = boto3.client('s3')
27
+ BUCKET_NAME = "wt-video-dl" # Replace with your bucket name
28
+
29
+ os.environ['AWS_ACCESS_KEY_ID'] = 'AKIA2YB4Z26VQAUNACVC' # Replace with your AWS access key
30
+ os.environ['AWS_SECRET_ACCESS_KEY'] = 'r3GmeE3WslFlaqOrPKBpz0pddAuXH9SDIpOLRGbv' # Replace with your AWS secret key
31
+ os.environ['AWS_DEFAULT_REGION'] = 'us-east-2' # Replace with your region (e.g., 'us-east-1', 'us-west-2')
32
+
33
+
34
  #IMAGE_DIR = "./images"
35
  IMAGE_DIR = "/tmp"
36
  os.makedirs(IMAGE_DIR, exist_ok=True)
37
+
38
 
39
  GITHUB_API_URL = "https://api.github.com/search/repositories"
40
  ACCESS_TOKEN = os.getenv("github_pat")
 
61
 
62
  discovered_repos = []
63
 
64
+ # Function to upload image to S3
65
+ def upload_image_to_s3(image_data, filename):
66
+ try:
67
+ # Upload the image data to S3
68
+ s3_client.put_object(
69
+ Bucket=BUCKET_NAME,
70
+ Key=filename,
71
+ Body=image_data,
72
+ ContentType='image/png',
73
+ ACL='public-read' # Make the image publicly readable
74
+ )
75
+ # Generate the S3 URL
76
+ s3_url = f"https://{BUCKET_NAME}.s3.amazonaws.com/{filename}"
77
+ return s3_url
78
+ except (NoCredentialsError, PartialCredentialsError) as e:
79
+ return f"Error with AWS credentials: {str(e)}"
80
+ except Exception as e:
81
+ return f"Error uploading image to S3: {str(e)}"
82
+
83
  def search_similar_topics(input_text):
84
  if not input_text.strip():
85
  return "Enter topics to see suggestions."
 
513
  return dot_code
514
 
515
  def render_dot_code(dot_code, filename=None):
516
+
 
 
 
 
 
 
 
 
 
517
  if not filename:
518
+ filename = f"diagram_{uuid.uuid4().hex}.png" # Generate a unique filename
519
+
 
 
 
 
520
  try:
521
  # Render the DOT code to an in-memory PNG
522
  src = Source(dot_code, format="png")
523
+ rendered_png = src.pipe() # In-memory PNG image data
524
+
525
+ # Upload the rendered PNG to S3
526
+ s3_url = upload_image_to_s3(rendered_png, filename)
527
+
528
+ # Return the S3 URL
529
+ return s3_url
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
530
 
531
  except Exception as e:
 
532
  return f"Error rendering or uploading diagram: {str(e)}"
533
+
534
+
535
  import time
536
 
537
  def handle_generate_diagram(code_content, diagram_type, retries=5, wait_time=1):
538
 
539
+ s3_url = render_dot_code(generate_dot_code_from_code(code_content, diagram_type))
540
+ if s3_url.startswith("http"): # Check if the response is a valid URL
541
+ return f'<img src="{s3_url}" alt="Generated Diagram" style="max-width: 100%; height: auto;">'
542
  else:
543
+ return f"<p>Error: {s3_url}</p>" # Return the error message in HTML format
 
544
 
545
  # Gradio Interface
546
  with gr.Blocks() as demo:
 
690
  )
691
  generate_diagram_button = gr.Button("Generate Diagram")
692
  with gr.Row():
 
693
  diagram_output = gr.HTML(
694
  label="Generated Diagram",
695