1+ import tkinter as tk
2+ from tkinter import simpledialog , messagebox , filedialog , scrolledtext
3+ import pywhatkit
4+ import cv2
5+ from cvzone .HandTrackingModule import HandDetector
6+ import geocoder
7+ import boto3
8+ import webbrowser
9+ import requests
10+ import cohere
11+ import io
12+ import base64
13+
14+ # Initialize Boto3 client for EC2 and S3
15+ ec2_client = boto3 .client ('ec2' )
16+ s3_client = boto3 .client ('s3' )
17+
18+ # Initialize Cohere client
19+ COHERE_API_KEY = '2bdecd6iI83GtBV92Y6xx5BeQtUoN3eHegpc1AEv'
20+ cohere_client = cohere .Client (COHERE_API_KEY )
21+
22+ # Initialize SerpAPI key
23+ SERPAPI_API_KEY = '23675a4826deb198848dadd4ae0a3a91850d7c18ee4e3cc49dab571316cf889c'
24+
25+ # Initialize Google Vision API key
26+ VISION_API_KEY = 'AIzaSyB3SJUtcMwq69he1Jycd5mgG7Wp-51lXSg'
27+
28+ def describe_image (image_path ):
29+ try :
30+ # Load the image into memory
31+ with io .open (image_path , 'rb' ) as image_file :
32+ content = image_file .read ()
33+
34+ # Encode image to base64
35+ encoded_image = base64 .b64encode (content ).decode ('utf-8' )
36+
37+ # Prepare the request payload
38+ request_payload = {
39+ "requests" : [
40+ {
41+ "image" : {
42+ "content" : encoded_image
43+ },
44+ "features" : [
45+ {
46+ "type" : "LABEL_DETECTION" ,
47+ "maxResults" : 10 # Adjust the number of results as needed
48+ }
49+ ]
50+ }
51+ ]
52+ }
53+
54+ # Make the request to the Vision API
55+ url = f'https://vision.googleapis.com/v1/images:annotate?key={ VISION_API_KEY } '
56+ response = requests .post (url , json = request_payload )
57+
58+ # Check if the request was successful
59+ if response .status_code != 200 or 'error' in response .json ():
60+ raise Exception (f"Error { response .status_code } : { response .json ().get ('error' , {}).get ('message' , 'Unknown error' )} " )
61+
62+ # Parse the response
63+ label_annotations = response .json ()['responses' ][0 ].get ('labelAnnotations' , [])
64+
65+ # Check if any labels were found
66+ if not label_annotations :
67+ return "No labels detected."
68+
69+ # Collect the labels
70+ labels = [label ['description' ] for label in label_annotations ]
71+ prompt = f"Based on the image labels: { ' ' .join (labels )} \n Generate a summary:"
72+
73+ # Generate text using Cohere
74+ summary = generate_text_with_cohere (prompt )
75+
76+ return summary
77+
78+ except Exception as e :
79+ return str (e )
80+
81+ def select_image ():
82+ # Open file dialog to select an image file
83+ image_path = filedialog .askopenfilename (filetypes = [("Image Files" , ".jpg;.jpeg;*.png" )])
84+ if image_path :
85+ result = describe_image (image_path )
86+ result_text .delete (1.0 , tk .END )
87+ result_text .insert (tk .END , result )
88+
89+ def send_email ():
90+ sender_email = 'ansarimohdasif128@gmail.com' # Update with your email
91+ password = 'kkuj xtph gxmf qetp' # Update with your email password
92+
93+ receiver_email = simpledialog .askstring ("Receiver Email" , "Enter receiver's email:" )
94+ message = simpledialog .askstring ("Message" , "Enter your message:" )
95+ subject = 'DOSS Technical Training Project'
96+
97+ try :
98+ pywhatkit .send_mail (sender_email , password , subject , message , receiver_email )
99+ messagebox .showinfo ("Success" , "Email sent successfully!" )
100+ except Exception as e :
101+ messagebox .showerror ("Error" , f"Failed to send email: { str (e )} " )
102+
103+ def get_location_info ():
104+ coordinate = geocoder .ip ('me' ).latlng
105+ city = geocoder .osm (coordinate , method = 'reverse' ).city
106+ nearby_places = geocoder .osm (coordinate , method = 'reverse' ).json ['address' ]
107+
108+ location_info = f"City: { city } \n Nearby Places: { nearby_places } "
109+ messagebox .showinfo ("Location Info" , location_info )
110+
111+ def capture_hand_gestures ():
112+ model = HandDetector ()
113+ cap = cv2 .VideoCapture (0 )
114+
115+ while True :
116+ status , photo = cap .read ()
117+ hand = model .findHands (photo )
118+ cv2 .imshow ("Hand Gestures" , photo )
119+ if cv2 .waitKey (10 ) == 13 :
120+ break
121+
122+ cv2 .destroyAllWindows ()
123+ cap .release ()
124+
125+ def list_ec2_instances ():
126+ response = ec2_client .describe_instances ()
127+ instance_ids = []
128+ for reservation in response ['Reservations' ]:
129+ for instance in reservation ['Instances' ]:
130+ instance_id = instance ['InstanceId' ]
131+ state = instance ['State' ]['Name' ]
132+ print (f"Instance ID: { instance_id } , State: { state } " )
133+ instance_ids .append (instance_id )
134+ instance_ids_str = '\n ' .join (instance_ids )
135+ messagebox .showinfo ("EC2 Instance IDs" , f"Instance IDs:\n { instance_ids_str } " )
136+
137+ def stop_ec2_instance ():
138+ response = ec2_client .describe_instances (Filters = [{'Name' : 'instance-state-name' , 'Values' : ['running' ]}])
139+ instances = response ['Reservations' ]
140+
141+ if not instances :
142+ messagebox .showinfo ("No Running Instances" , "There are no running instances to stop." )
143+ return
144+
145+ instance_number = simpledialog .askinteger ("Select Instance" , "Enter 1 to stop the instance:" ) - 1
146+
147+ if instance_number is None or instance_number < 0 or instance_number >= len (instances ):
148+ messagebox .showerror ("Invalid Selection" , "Please select a valid instance number." )
149+ return
150+
151+ selected_instance_id = instances [instance_number ]['Instances' ][0 ]['InstanceId' ]
152+ ec2_client .stop_instances (InstanceIds = [selected_instance_id ])
153+ messagebox .showinfo ("Instance Stopped" , f"Stopping instance { selected_instance_id } " )
154+
155+ def launch_instance ():
156+ response = ec2_client .run_instances (
157+ ImageId = 'ami-09298640a92b2d12c' , # Replace with your desired AMI ID
158+ InstanceType = 't2.micro' , # Replace with your desired instance type
159+ MinCount = 1 ,
160+ MaxCount = 1
161+ )
162+ instance_id = response ['Instances' ][0 ]['InstanceId' ]
163+ print (f"New instance launched with ID: { instance_id } " )
164+
165+ def open_url ():
166+ webbrowser .open ("http://3.109.103.64:10001/" )
167+
168+ def upload_to_s3 ():
169+ file_path = filedialog .askopenfilename ()
170+ if file_path :
171+ key = simpledialog .askstring ("Key" , "Enter the key (name) for the file in the bucket:" )
172+ try :
173+ s3_client .upload_file (file_path , "dossttpprojectbucket" , key )
174+ messagebox .showinfo ("Success" , "File uploaded successfully!" )
175+ except Exception as e :
176+ messagebox .showerror ("Error" , f"Failed to upload file: { str (e )} " )
177+
178+ def download_from_s3 ():
179+ key = simpledialog .askstring ("Key" , "Enter the key (name) of the file to download from the bucket:" )
180+ if key :
181+ file_path = filedialog .asksaveasfilename (initialfile = key .split ('/' )[- 1 ])
182+ if file_path :
183+ try :
184+ s3_client .download_file ("dossttpprojectbucket" , key , file_path )
185+ messagebox .showinfo ("Success" , "File downloaded successfully!" )
186+ except Exception as e :
187+ messagebox .showerror ("Error" , f"Failed to download file: { str (e )} " )
188+
189+ def delete_from_s3 ():
190+ key = simpledialog .askstring ("Key" , "Enter the key (name) of the file to delete from the bucket:" )
191+ if key :
192+ try :
193+ s3_client .delete_object (Bucket = "dossttpprojectbucket" , Key = key )
194+ messagebox .showinfo ("Success" , "File deleted successfully!" )
195+ except Exception as e :
196+ messagebox .showerror ("Error" , f"Failed to delete file: { str (e )} " )
197+
198+ def search_serpapi (query ):
199+ params = {
200+ "engine" : "google" ,
201+ "q" : query ,
202+ "api_key" : SERPAPI_API_KEY
203+ }
204+ response = requests .get ("https://serpapi.com/search" , params = params )
205+ return response .json ()
206+
207+ def generate_text_with_cohere (prompt ):
208+ response = cohere_client .generate (
209+ model = 'command-light-nightly' ,
210+ prompt = prompt ,
211+ max_tokens = 50 ,
212+ temperature = 0.75 ,
213+ )
214+ return response .generations [0 ].text .strip ()
215+
216+ def search_and_generate (query ):
217+ search_results = search_serpapi (query )
218+ search_snippets = [result .get ('snippet' , '' ) for result in search_results .get ('organic_results' , [])]
219+ combined_snippets = "\n " .join (search_snippets )
220+ cohere_prompt = f"Based on the following information, write a summary:\n \n { combined_snippets } "
221+ summary = generate_text_with_cohere (cohere_prompt )
222+ return summary
223+
224+ def chatbot ():
225+ chat_window = tk .Toplevel (root )
226+ chat_window .title ("Chatbot" )
227+ chat_window .configure (bg = 'lightblue' )
228+
229+ def get_response ():
230+ query = query_entry .get ()
231+ summary = search_and_generate (query )
232+ response_area .insert (tk .END , f"Q: { query } \n A: { summary } \n \n " )
233+ query_entry .delete (0 , tk .END )
234+
235+ query_label = tk .Label (chat_window , text = "Enter your query:" , bg = 'lightblue' )
236+ query_label .pack (pady = 5 )
237+
238+ query_entry = tk .Entry (chat_window , width = 50 )
239+ query_entry .pack (pady = 5 )
240+
241+ response_area = scrolledtext .ScrolledText (chat_window , wrap = tk .WORD , width = 60 , height = 20 )
242+ response_area .pack (pady = 5 )
243+
244+ submit_button = tk .Button (chat_window , text = "Get Response" , command = get_response , bg = 'blue' , fg = 'white' )
245+ submit_button .pack (pady = 5 )
246+
247+ # Main Window
248+ root = tk .Tk ()
249+ root .title ("Main Window" )
250+ root .configure (bg = 'lightgrey' )
251+
252+ buttons = [
253+ ("Send Email" , send_email ),
254+ ("Get Location Info" , get_location_info ),
255+ ("Capture Hand Gestures" , capture_hand_gestures ),
256+ ("List EC2 Instances" , list_ec2_instances ),
257+ ("Stop EC2 Instance" , stop_ec2_instance ),
258+ ("Launch EC2 Instance" , launch_instance ),
259+ ("Open URL" , open_url ),
260+ ("Upload to S3" , upload_to_s3 ),
261+ ("Download from S3" , download_from_s3 ),
262+ ("Delete from S3" , delete_from_s3 ),
263+ ("Chatbot" , chatbot ),
264+ ("Image Detection" , select_image ) # Add the image detection button
265+ ]
266+
267+ # Create a text widget to display the results of image detection
268+ result_text = tk .Text (root , width = 60 , height = 20 , wrap = tk .WORD )
269+ result_text .pack (pady = 5 )
270+
271+ for btn_text , command in buttons :
272+ btn = tk .Button (root , text = btn_text , command = command , bg = 'blue' , fg = 'white' )
273+ btn .pack (pady = 5 , padx = 10 )
274+
275+ root .mainloop ()
0 commit comments