Nymbo commited on
Commit
d4e29c7
·
verified ·
1 Parent(s): 31d1d7e
Files changed (1) hide show
  1. app.py +123 -142
app.py CHANGED
@@ -6,195 +6,176 @@ from google_img_source_search import ReverseImageSearcher
6
  from PIL import Image
7
  import os
8
  import uuid
9
- import subprocess
10
- import html
11
- import imgbbpy # Adding imgbb to upload images for accessible URLs
 
 
 
 
 
12
 
13
- # Initialize imgbb client with your API key (you need to provide your key)
14
- imgbb_client = imgbbpy.SyncClient("YOUR_IMGBB_API_KEY")
15
-
16
- # Function to download video from a given URL using yt-dlp
17
  def dl(inp):
18
  out = None
 
19
  try:
20
- # Generate a unique ID for each download to avoid conflicts
21
- uid = uuid.uuid4()
22
- # Replace characters in URL to create a valid filename
23
- inp_out = inp.replace("https://", "").replace("/", "_").replace(".", "_").replace("=", "_").replace("?", "_")
24
-
25
- # Construct yt-dlp command to download the video
26
- command = [
27
- 'yt-dlp', inp, '--trim-filenames', '160',
28
- '-o', f"{uid}/{inp_out}.mp4", '-S', 'res,mp4', '--recode', 'mp4'
29
- ]
30
-
31
- # Special handling for Twitter URLs
32
  if "twitter" in inp:
33
- command.insert(2, '--extractor-arg')
34
- command.insert(3, 'twitter:api=syndication')
35
-
36
- # Run the yt-dlp command to download the video
37
- subprocess.run(command, check=True)
38
  out = f"{uid}/{inp_out}.mp4"
39
- print(out)
40
- except subprocess.CalledProcessError as e:
41
- print(f"yt-dlp failed: {e}")
42
- return out, gr.HTML(""), "", ""
43
-
44
- # Function to process the video, extracting frames and performing reverse image search
45
- def process_vid(file, cur_frame, every_n):
46
- uid = uuid.uuid4() # Unique identifier for each run to avoid conflicts
47
- capture = cv2.VideoCapture(file) # Open the video file
48
- frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) # Get total number of frames in the video
49
- rev_img_searcher = ReverseImageSearcher() # Initialize the reverse image searcher
50
- html_out = ""
 
 
51
  count = int(every_n)
52
-
53
- # Determine the starting frame based on user input
54
- start_frame = int(cur_frame) if cur_frame else 0
55
-
56
  try:
57
- # Iterate over frames from the starting frame to the end
58
- for i in range(start_frame, frame_count):
59
- if count >= int(every_n):
60
  count = 1
61
- capture.set(cv2.CAP_PROP_POS_FRAMES, i) # Set the position to the specific frame
62
- ret, frame_f = capture.read() # Read the frame
63
-
64
- if not ret:
65
- continue # If frame could not be read, continue to the next one
66
-
67
- # Save the current frame as an image file
68
- frame_path = f"{uid}-vid_tmp{i}.png"
69
- cv2.imwrite(frame_path, frame_f)
70
-
71
- # Upload the frame to imgbb to get a publicly accessible URL
72
- response = imgbb_client.upload(file=frame_path)
73
- out_url = response.url # Get the public URL from imgbb response
74
-
75
- # Perform reverse image search on the extracted frame
76
  res = rev_img_searcher.search(out_url)
77
- out_cnt = 0
78
-
79
- # If results are found, generate HTML output
80
  if len(res) > 0:
 
81
  for search_item in res:
82
- out_cnt += 1
83
- html_out += f"""
 
 
 
 
 
 
 
84
  <div>
85
- Title: {html.escape(search_item.page_title)}<br>
86
- Site: <a href='{html.escape(search_item.page_url)}' target='_blank' rel='noopener noreferrer'>{html.escape(search_item.page_url)}</a><br>
87
- Img: <a href='{html.escape(search_item.image_url)}' target='_blank' rel='noopener noreferrer'>{html.escape(search_item.image_url)}</a><br>
88
- <img class='my_im' src='{html.escape(search_item.image_url)}'><br>
89
  </div>"""
90
- return gr.HTML(f'<h1>Total Found: {out_cnt}</h1><br>{html_out}'), f"Found frame: {i}", i + int(every_n)
91
- count += 1
 
 
 
 
92
  except Exception as e:
93
- return gr.HTML(f'{e}'), "", ""
94
- return gr.HTML('No frame matches found.'), "", ""
95
 
96
- # Function to process an image file and convert it for reverse image search
97
- def process_im(file, url):
98
- # Check if the URL starts with the expected prefix
99
  if not url.startswith("https://omnibus"):
100
  return url
101
  else:
102
- # Save the image to a temporary file
103
- uid = uuid.uuid4()
104
  read_file = Image.open(file)
105
  read_file.save(f"{uid}-tmp.png")
106
  action_input = f"{uid}-tmp.png"
107
  out = os.path.abspath(action_input)
108
-
109
- # Upload the image to imgbb to get a publicly accessible URL
110
- response = imgbb_client.upload(file=out)
111
- out_url = response.url # Get the public URL from imgbb response
112
- return out_url
113
 
114
- # Function to perform reverse image search on a given image
115
  def rev_im(image):
116
- uid = uuid.uuid4() # Generate a unique ID for each run
117
- html_out = """""" # Initialize HTML output
118
-
119
- # Read the image using OpenCV and save it to a temporary file
120
- image = cv2.imread(image)
121
- tmp_image_path = f"{uid}-im_tmp.png"
122
- cv2.imwrite(tmp_image_path, image)
123
-
124
- # Upload the image to imgbb to get a publicly accessible URL
125
- response = imgbb_client.upload(file=tmp_image_path)
126
- out_url = response.url # Get the public URL from imgbb response
127
-
128
- # Perform reverse image search
129
  rev_img_searcher = ReverseImageSearcher()
130
  res = rev_img_searcher.search(out_url)
131
  count = 0
132
-
133
- # If results are found, generate HTML output
134
  for search_item in res:
135
- count += 1
136
- html_out += f"""
 
 
 
 
 
 
137
  <div>
138
- Title: {html.escape(search_item.page_title)}<br>
139
- Site: <a href='{html.escape(search_item.page_url)}' target='_blank' rel='noopener noreferrer'>{html.escape(search_item.page_url)}</a><br>
140
- Img: <a href='{html.escape(search_item.image_url)}' target='_blank' rel='noopener noreferrer'>{html.escape(search_item.image_url)}</a><br>
141
- <img class='my_im' src='{html.escape(search_item.image_url)}'><br>
142
  </div>"""
143
 
144
- return gr.HTML(f'<h1>Total Found: {count}</h1><br>{html_out}')
 
 
 
 
145
 
146
- # Define the Gradio interface for the application
147
  with gr.Blocks() as app:
148
  with gr.Row():
149
  gr.Column()
150
  with gr.Column():
151
- # Radio button to choose between Image or Video input
152
- source_tog = gr.Radio(choices=["Image", "Video"], value="Image")
153
 
154
- # Box to handle image-related input
155
  with gr.Box(visible=True) as im_box:
156
- inp_url = gr.Textbox(label="Image URL")
157
- load_im_btn = gr.Button("Load Image")
158
- inp_im = gr.Image(label="Search Image", type='filepath')
159
- go_btn_im = gr.Button("Start Image Search")
160
-
161
- # Box to handle video-related input
162
  with gr.Box(visible=False) as vid_box:
163
- vid_url = gr.Textbox(label="Video URL")
164
- vid_url_btn = gr.Button("Load URL")
165
- inp_vid = gr.Video(label="Search Video")
166
  with gr.Row():
167
- every_n = gr.Number(label="Every /nth frame", value=10) # Input to select frame extraction frequency
168
- stat_box = gr.Textbox(label="Status")
169
  with gr.Row():
170
- go_btn_vid = gr.Button("Start Video Search")
171
- next_btn = gr.Button("Next Frame Search")
172
-
173
- gr.Column()
 
174
  with gr.Row():
175
- html_out = gr.HTML("""
176
- """)
177
  with gr.Row(visible=False):
178
- hid_box = gr.Textbox()
179
-
180
- # Function to shuffle between image and video input boxes based on user selection
181
  def shuf(tog):
182
  if tog == "Image":
183
- return gr.update(visible=True), gr.update(visible=False)
184
  if tog == "Video":
185
- return gr.update(visible=False), gr.update(visible=True)
186
-
187
- # Function to load image from the URL
188
  def load_image(url):
189
  return url
190
-
191
- # Gradio button interactions and linking functions
192
- im_load = load_im_btn.click(load_image, inp_url, inp_im)
193
- next_btn.click(process_vid, [inp_vid, hid_box, every_n], [html_out, stat_box, hid_box])
194
- vid_load = vid_url_btn.click(dl, vid_url, [inp_vid, html_out, stat_box, hid_box])
195
- vid_proc = go_btn_vid.click(process_vid, [inp_vid, hid_box, every_n], [html_out, stat_box, hid_box])
196
- im_proc = go_btn_im.click(rev_im, inp_im, [html_out])
197
- source_tog.change(shuf, [source_tog], [im_box, vid_box], cancels=[vid_proc, im_proc, im_load, vid_load])
198
-
199
- # Launch the Gradio app with concurrency settings
200
  app.queue(concurrency_count=20).launch()
 
6
  from PIL import Image
7
  import os
8
  import uuid
9
+ uid=uuid.uuid4()
10
+ size_js="""
11
+ function imgSize(){
12
+ var myImg = document.getElementsByClassName("my_im");
13
+ var realWidth = myImg.naturalWidth;
14
+ var realHeight = myImg.naturalHeight;
15
+ alert("Original width=" + realWidth + ", " + "Original height=" + realHeight);
16
+ }"""
17
 
 
 
 
 
18
  def dl(inp):
19
  out = None
20
+ out_file=[]
21
  try:
22
+ inp_out=inp.replace("https://","")
23
+ inp_out=inp_out.replace("/","_").replace(".","_").replace("=","_").replace("?","_")
 
 
 
 
 
 
 
 
 
 
24
  if "twitter" in inp:
25
+ os.system(f'yt-dlp "{inp}" --extractor-arg "twitter:api=syndication" --trim-filenames 160 -o "{uid}/{inp_out}.mp4" -S res,mp4 --recode mp4')
26
+ else:
27
+ os.system(f'yt-dlp "{inp}" --trim-filenames 160 -o "{uid}/{inp_out}.mp4" -S res,mp4 --recode mp4')
28
+
29
+ #os.system(f'yt-dlp "{inp}" --trim-filenames 160 -o "{inp_out}.mp4" -S res,mp4 --recode mp4')
30
  out = f"{uid}/{inp_out}.mp4"
31
+ #out_ap = os.path.abspath(out_f)
32
+ #out = f'https://omnibus-reverse-image.hf.space/file={out_ap}'
33
+ print (out)
34
+ except Exception as e:
35
+ print (e)
36
+ #out = f'{e}'
37
+ return out,gr.HTML(""),"",""
38
+
39
+ def process_vid(file,cur_frame,every_n):
40
+ new_video_in = str(file)
41
+ capture = cv2.VideoCapture(new_video_in)
42
+ frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
43
+ rev_img_searcher = ReverseImageSearcher()
44
+ html_out=""
45
  count = int(every_n)
46
+ if cur_frame == "" or cur_frame==None:
47
+ start_frame = 0
48
+ elif cur_frame != "" and cur_frame!=None:
49
+ start_frame = int(cur_frame)
50
  try:
51
+ for i in range(start_frame, frame_count-1):
52
+ if count == int(every_n):
 
53
  count = 1
54
+ print(i)
55
+ capture.set(cv2.CAP_PROP_POS_FRAMES, i)
56
+ ret, frame_f = capture.read(i)
57
+ cv2.imwrite(f"{uid}-vid_tmp{i}.png", frame_f)
58
+ out = os.path.abspath(f"{uid}-vid_tmp{i}.png")
59
+ out_url = f'https://omnibus-reverse-image.hf.space/file={out}'
60
+ print(out)
 
 
 
 
 
 
 
 
61
  res = rev_img_searcher.search(out_url)
62
+ #print (res)
63
+ out_cnt =0
 
64
  if len(res) > 0:
65
+ #count = 0
66
  for search_item in res:
67
+ print (f'counting {count}')
68
+ out_cnt+=1
69
+ out_dict={
70
+ 'Title': f'{search_item.page_title}',
71
+ 'Site': f'{search_item.page_url}',
72
+ 'Img': f'{search_item.image_url}',
73
+ }
74
+ print (dir(search_item))
75
+ html_out = f"""{html_out}
76
  <div>
77
+ Title: {search_item.page_title}<br>
78
+ Site: <a href='{search_item.page_url}' target='_blank' rel='noopener noreferrer'>{search_item.page_url}</a><br>
79
+ Img: <a href='{search_item.image_url}' target='_blank' rel='noopener noreferrer'>{search_item.image_url}</a><br>
80
+ <img class='my_im' src='{search_item.image_url}'><br>
81
  </div>"""
82
+ return (gr.HTML(f'<h1>Total Found: {out_cnt}</h1><br>{html_out}'), f"Found frame: {i}", i+int(every_n))
83
+ else:
84
+ pass
85
+ count +=1
86
+ print (i+1)
87
+ #return (None,f"Searching Frame: {i}", "")
88
  except Exception as e:
89
+ return (gr.HTML(f'{e}'),"","")
90
+ return (gr.HTML('No frame matches found.'),"","")
91
 
92
+ def process_im(file,url):
 
 
93
  if not url.startswith("https://omnibus"):
94
  return url
95
  else:
 
 
96
  read_file = Image.open(file)
97
  read_file.save(f"{uid}-tmp.png")
98
  action_input = f"{uid}-tmp.png"
99
  out = os.path.abspath(action_input)
100
+ out_url = f'https://omnibus-reverse-image.hf.space/file={out}'
101
+ return (out_url)
 
 
 
102
 
 
103
  def rev_im(image):
104
+ #image_url = 'https://i.pinimg.com/originals/c4/50/35/c450352ac6ea8645ead206721673e8fb.png'
105
+ out_list = []
106
+ out_im = []
107
+ html_out = """"""
108
+ image=cv2.imread(image)
109
+ cv2.imwrite(f"{uid}-im_tmp.png", image)
110
+ out = os.path.abspath(f"{uid}-im_tmp.png")
111
+ out_url = f'https://omnibus-reverse-image.hf.space/file={out}'
 
 
 
 
 
112
  rev_img_searcher = ReverseImageSearcher()
113
  res = rev_img_searcher.search(out_url)
114
  count = 0
 
 
115
  for search_item in res:
116
+ count+=1
117
+ out_dict={
118
+ 'Title': f'{search_item.page_title}',
119
+ 'Site': f'{search_item.page_url}',
120
+ 'Img': f'{search_item.image_url}',
121
+ }
122
+ print (dir(search_item))
123
+ html_out = f"""{html_out}
124
  <div>
125
+ Title: {search_item.page_title}<br>
126
+ Site: <a href='{search_item.page_url}' target='_blank' rel='noopener noreferrer'>{search_item.page_url}</a><br>
127
+ Img: <a href='{search_item.image_url}' target='_blank' rel='noopener noreferrer'>{search_item.image_url}</a><br>
128
+ <img class='my_im' src='{search_item.image_url}'><br>
129
  </div>"""
130
 
131
+ return (gr.HTML(f'<h1>Total Found: {count}</h1><br>{html_out}'))
132
+
133
+
134
+
135
+
136
 
 
137
  with gr.Blocks() as app:
138
  with gr.Row():
139
  gr.Column()
140
  with gr.Column():
 
 
141
 
142
+ source_tog=gr.Radio(choices=["Image","Video"],value="Image")
143
  with gr.Box(visible=True) as im_box:
144
+ inp_url=gr.Textbox(label="Image URL")
145
+ load_im_btn=gr.Button("Load Image")
146
+ inp_im=gr.Image(label="Search Image",type='filepath')
147
+ go_btn_im=gr.Button()
 
 
148
  with gr.Box(visible=False) as vid_box:
149
+ vid_url=gr.Textbox(label="Video URL")
150
+ vid_url_btn=gr.Button("Load URL")
151
+ inp_vid=gr.Video(label="Search Video")
152
  with gr.Row():
153
+ every_n=gr.Number(label = "Every /nth frame", value = 10)
154
+ stat_box=gr.Textbox(label="Status")
155
  with gr.Row():
156
+ go_btn_vid=gr.Button("Start")
157
+ next_btn=gr.Button("Next")
158
+
159
+ gr.Column()
160
+ #paste_clip = gr.Button("Paste from Clipboard")
161
  with gr.Row():
162
+ html_out = gr.HTML("""""")
 
163
  with gr.Row(visible=False):
164
+ hid_box=gr.Textbox()
 
 
165
  def shuf(tog):
166
  if tog == "Image":
167
+ return gr.update(visible=True),gr.update(visible=False)
168
  if tog == "Video":
169
+ return gr.update(visible=False),gr.update(visible=True)
 
 
170
  def load_image(url):
171
  return url
172
+ im_load = load_im_btn.click(load_image,inp_url,inp_im)
173
+ next_btn.click(process_vid,[inp_vid,hid_box,every_n],[html_out,stat_box,hid_box])
174
+ vid_load = vid_url_btn.click(dl,vid_url,[inp_vid,html_out,stat_box,hid_box])
175
+ #inp_im.change(process_im,[inp_im,inp_url],[inp_url])
176
+ vid_proc = go_btn_vid.click(process_vid,[inp_vid,hid_box,every_n],[html_out,stat_box,hid_box])
177
+ im_proc = go_btn_im.click(rev_im,inp_im,[html_out])
178
+ source_tog.change(shuf,[source_tog],[im_box,vid_box],cancels=[vid_proc,im_proc,im_load,vid_load])
179
+
180
+ #go_btn_url.click(rev_im,inp_url,[html_out])
 
181
  app.queue(concurrency_count=20).launch()