This repository has been archived by the owner on Apr 12, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInsta2QgisDialog.py
580 lines (464 loc) · 22 KB
/
Insta2QgisDialog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Instagram to Qgis
A QGIS plugin
Search and downloading Instagram images and create a point shapefile with them.
-------------------
begin : 2016-03-13
copyright : (C) 2016 All4Gis.
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
# any later version. *
* *
***************************************************************************/
"""
import os.path
from qgis.core import *
from qgis.gui import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from About import AboutDialog
from gui.generated.ui_Insta2QgisTool import Ui_Insta2QgisToolDialog
try:
import sys
from pydevd import *
except:
pass
try:
from instagram.client import InstagramAPI
except Exception,e:
QMessageBox.information(None, 'Instagram2Qgis',"Fail importing library: "+ str(e) ,QMessageBox.Ok)
pass
try:
import base64
except Exception,e:
QMessageBox.information(None, 'Instagram2Qgis',"Fail importing library: "+ str(e) ,QMessageBox.Ok)
pass
try:
import tempfile
except Exception,e:
QMessageBox.information(None, 'Instagram2Qgis',"Fail importing library: "+ str(e) ,QMessageBox.Ok)
pass
try:
import requests
except Exception,e:
QMessageBox.information(None, 'Instagram2Qgis',"Fail importing library: "+ str(e) ,QMessageBox.Ok)
pass
class Insta2QgisDialog(QDialog, Ui_Insta2QgisToolDialog):
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor."""
QDialog.__init__(self)
self.setupUi(self)
self.iface = iface
self.canvas=self.iface.mapCanvas()
self.settings = QSettings()
self.settings.setValue("instagram2qgis/outpath", "")
width=600
height=450
self.setMinimumSize(QSize(width, height))
self.setMaximumSize(QSize(width, height))
self.HideGroupBox()
self.TypeSearch="hashtags" #Default search
self.GetCredentials()
#Save acces login
def SaveCredentials(self):
self.settings.setValue("instagram2qgis/token",self.lnToken.text())
self.settings.setValue("instagram2qgis/client",self.lnAcces.text())
self.iface.messageBar().pushMessage("Info: ", "Save credentials correctly.",level=QgsMessageBar.INFO, duration=3)
return
#Get values credentials
def GetCredentials(self):
self.lnToken.setText(self.settings.value("instagram2qgis/token"))
self.lnAcces.setText(self.settings.value("instagram2qgis/client"))
return
#Hide groupbox
def HideGroupBox(self):
self.groupBox_user.hide()
self.groupBox_location.hide()
self.groupBox_popular.hide()
self.groupBox_location_id.hide()
return
# About
def about(self):
self.About = AboutDialog(self.iface)
#self.About.setWindowFlags(Qt.WindowSystemMenuHint | Qt.WindowTitleHint)
self.About.exec_()
#Save Output file
def SaveFile(self):
out = QFileDialog.getSaveFileName(self, "Save Output", None,"shapefiles (*.shp);;All Files (*)")
if out:
if QFileInfo(out).suffix()=="":
out += '.shp'
self.output_cmb.setText(out)
self.settings.setValue("instagram2qgis/outpath", out)
return
#Get values of list Tags
def GetListTags(self,list):
values=[]
for i ,val in enumerate(list):
values.append(str(list[i].name))
return str(values).strip('[]')
#Capture coords in map
def captureCoord(self):
self.hide()
self.mapTool = CopyCoords(self.iface,parent=self)
self.iface.mapCanvas().setMapTool(self.mapTool)
return
#Update value progessbar
def update_progressbar(self, val):
self.progressBar.setValue(val)
#Toggle GroupBox
def TypeSearch(self,value):
self.HideGroupBox()
self.groupBox_tags.hide()
self.sp_count.hide()
self.label_4.hide()
sender = self.sender().objectName()
if(value):
if sender == "ch_hashtags":
self.groupBox_tags.show()
self.sp_count.show()
self.label_4.show()
self.TypeSearch="hashtags"
elif sender == "ch_user":
self.lnId.setPlaceholderText("Instagram")
self.label_3.setText("User name")
self.groupBox_user.show()
self.TypeSearch="user"
elif sender == "ch_location":
self.groupBox_location.show()
self.TypeSearch="coords"
elif sender == "ch_popular":
self.groupBox_popular.show()
self.TypeSearch="popular"
elif sender == "ch_user_recent":
self.groupBox_popular.show()
self.TypeSearch="user_recent"
elif sender == "ch_user_media":
self.groupBox_popular.show()
self.TypeSearch="user_media"
elif sender == "ch_location_recent":
self.groupBox_location_id.show()
self.TypeSearch="location_recent"
elif sender == "ch_user_follow":
self.lnId.setPlaceholderText("25025320")
self.label_3.setText("User ID")
self.groupBox_user.show()
self.TypeSearch="user_follow"
return
#Principal process
def InstagramProcces(self):
self.aceptar.setCursor(QCursor(Qt.ForbiddenCursor))
self.update_progressbar(10)
access_token = self.lnToken.text()
client_secret = self.lnAcces.text()
user_id=self.lnId.text()
if not access_token or not client_secret:
QMessageBox.information(self, "Empty values", "Complete mandatory items <access_token> and <client_secret>", QMessageBox.AcceptRole)
return
try:
api = InstagramAPI(access_token=access_token, client_secret=client_secret)
#Search recent media with Tag
if self.TypeSearch=="hashtags":
count=self.sp_count.value()
tag=self.ln_tags.text()
if tag=="":
QMessageBox.information(self, "Empty values", "Tag value is empty", QMessageBox.AcceptRole)
self.aceptar.setCursor(QCursor(Qt.PointingHandCursor))
self.update_progressbar(0)
return
tag_search, next_tag = api.tag_search(tag)
tag_recent_media, next = api.tag_recent_media(count,tag_name=tag_search[0].name)
if len(tag_recent_media)==0:return self.Checklength()
categorized,layer=self.CreateShape()
for tag_media in tag_recent_media:
self.AddFeatures(tag_media,layer,categorized)
#Search recent media with Location
elif self.TypeSearch=="coords":
lat=self.ln_lat.text()
lng=self.ln_lng.text()
distance=self.sp_distance.value()
location_search =api.media_search(lat=str(lat),lng=str(lng), distance=int(distance))
if len(location_search)==0:return self.Checklength()
categorized,layer=self.CreateShape()
for location in location_search:
self.AddFeatures(location,layer,categorized)
#Search recent media with user
elif self.TypeSearch=="user":
if self.lnId.text()=="":
QMessageBox.information(self, "Empty values", "User name value is empty", QMessageBox.AcceptRole)
self.aceptar.setCursor(QCursor(Qt.PointingHandCursor))
self.update_progressbar(0)
return
user_name=self.lnId.text()
user_search = api.user_search(user_name)
if len(user_search)==0:return self.Checklength()
layer=self.CreateShapeMin()
for user in user_search:
self.AddFeaturesMin(user,layer)
#Search user recent
elif self.TypeSearch=="user_recent":
recent_media, next = api.user_recent_media()
if len(recent_media)==0:return self.Checklength()
categorized,layer=self.CreateShape()
for media in recent_media:
self.AddFeatures(media,layer,categorized)
#Search User Media Feed
elif self.TypeSearch=="user_media":
media_feed, next = api.user_media_feed()
if len(media_feed)==0:return self.Checklength()
categorized,layer=self.CreateShape()
for media in media_feed:
self.AddFeatures(media,layer,categorized)
#Search User follow
elif self.TypeSearch=="user_follow":
if self.lnId.text()=="":
QMessageBox.information(self, "Empty values", "User ID value is empty", QMessageBox.AcceptRole)
self.aceptar.setCursor(QCursor(Qt.PointingHandCursor))
self.update_progressbar(0)
return
user_follows, next = api.user_follows(user_id)
if len(user_follows)==0:return self.Checklength()
layer=self.CreateShapeMin()
for user in user_follows:
self.AddFeaturesMin(user,layer)
#Search Location recent
elif self.TypeSearch=="location_recent":
if self.ln_loc_id.text()=="":
QMessageBox.information(self, "Empty values", "Location ID value is empty", QMessageBox.AcceptRole)
self.aceptar.setCursor(QCursor(Qt.PointingHandCursor))
self.update_progressbar(0)
return
location_id=int(self.ln_loc_id.text())
recent_media, next = api.location_recent_media(location_id=location_id)
if len(recent_media)==0:return self.Checklength()
categorized,layer=self.CreateShape()
for media in recent_media:
self.AddFeatures(media,layer,categorized)
#Search recent popular
elif self.TypeSearch=="popular":
media_search = api.media_popular()
if len(media_search)==0:return self.Checklength()
categorized,layer=self.CreateShape()
for media in media_search:
self.AddFeatures(media,layer,categorized)
#Save layer in output path
QgsVectorFileWriter.writeAsVectorFormat(layer,self.settings.value("instagram2qgis/outpath"), "CP1250", None, "ESRI Shapefile")
self.update_progressbar(100)
self.aceptar.setCursor(QCursor(Qt.PointingHandCursor))
self.reject()
except Exception, e:
self.iface.messageBar().pushMessage("Error: ", "fail to load photos: "+str(e),level=QgsMessageBar.CRITICAL, duration=20)
self.aceptar.setCursor(QCursor(Qt.PointingHandCursor))
return
#Message length media
def Checklength(self):
self.iface.messageBar().pushMessage("Error: ", "No photos available,please try again",level=QgsMessageBar.INFO, duration=3)
self.update_progressbar(0)
self.aceptar.setCursor(QCursor(Qt.PointingHandCursor))
return
#Create shape for media min
def CreateShapeMin(self):
self.update_progressbar(20)
layer = QgsVectorLayer('Point?crs=EPSG:4326', 'instagram_point', "memory")
provider = layer.dataProvider()
provider.addAttributes([QgsField("user_id", QVariant.Int)])
provider.addAttributes([QgsField("user_name", QVariant.String)])
provider.addAttributes([QgsField("user_full_name", QVariant.String)])
provider.addAttributes([QgsField("user_profile_picture", QVariant.String)])
layer.updateFields()
self.update_progressbar(30)
self.AddActions(layer)
#Add Layer to canvas
QgsMapLayerRegistry.instance().addMapLayer(layer)
return layer
#Add features to shape
def AddFeaturesMin(self,media,layer):
self.update_progressbar(40)
fet = QgsFeature()
try: user_id = media.id
except: user_id =""
try: user_name = media.username
except: user_name =""
try: user_full_name = media.full_name
except: user_full_name =""
try: user_profile_picture = media.profile_picture
except: user_profile_picture =""
fet.setAttributes([user_id,user_name,user_full_name,user_profile_picture])
pr = layer.dataProvider()
pr.addFeatures([fet])
return
#Create shape
def CreateShape(self):
self.update_progressbar(20)
layer = QgsVectorLayer('Point?crs=EPSG:4326', 'instagram_point', "memory")
provider = layer.dataProvider()
provider.addAttributes([QgsField("id_photo", QVariant.String)])
provider.addAttributes([QgsField("text", QVariant.String)])
provider.addAttributes([QgsField("user_name", QVariant.String)])
provider.addAttributes([QgsField("user_full_name", QVariant.String)])
provider.addAttributes([QgsField("user_id", QVariant.Int)])
provider.addAttributes([QgsField("user_profile_picture", QVariant.String)])
provider.addAttributes([QgsField("comments", QVariant.String)])
provider.addAttributes([QgsField("comments_count", QVariant.Int)])
provider.addAttributes([QgsField("likes_count", QVariant.Int)])
provider.addAttributes([QgsField("created_time", QVariant.Date)])
provider.addAttributes([QgsField("link_profile", QVariant.String)])
provider.addAttributes([QgsField("type", QVariant.String)])
provider.addAttributes([QgsField("latitude", QVariant.Double)])
provider.addAttributes([QgsField("longitude", QVariant.Double)])
provider.addAttributes([QgsField("tags", QVariant.String)])
provider.addAttributes([QgsField("photo", QVariant.String)])
provider.addAttributes([QgsField("video", QVariant.String)])
layer.updateFields()
self.update_progressbar(30)
categorized = []
renderer = QgsCategorizedSymbolRendererV2("id_photo", categorized)
layer.setRendererV2(renderer)
self.AddActions(layer)
#Add Layer to canvas
QgsMapLayerRegistry.instance().addMapLayer(layer)
return categorized,layer
def AddActions(self,layer):
#Add actions layers to open video and photo
actions = layer.actions()
actions.addAction(QgsAction.OpenUrl, 'Open photo in browser', '[% "photo" %]')
actions.addAction(QgsAction.OpenUrl, 'Open video in browser', '[% "video" %]')
actions.addAction(QgsAction.OpenUrl, 'Open link profile in browser', '[% "link_profile" %]')
return
#Add features to shape
def AddFeatures(self,media,layer,categorized):
self.update_progressbar(40)
fet = QgsFeature()
try: id_photo = media.id
except: id_photo =""
try: text = media.caption.text
except: text =""
try: user_name = media.caption.user.username
except: user_name =""
try: user_full_name = media.caption.user.full_name
except: user_full_name =""
try: user_id = media.caption.user.id
except: user_id =""
try: user_profile_picture = media.caption.user.profile_picture
except: user_profile_picture =""
try: comments = str(media.comments).strip('[]')
except: comments =""
try: comments_count = media.comment_count
except: comments_count =""
try: likes_count = media.like_count
except: likes_count =""
try: created_time = media.created_time.now().strftime("%Y-%m-%d %H:%M:%S")
except: created_time =""
try: link_profile = media.link
except: link_profile =""
try: media_type = media.type
except: media_type =""
try: latitude = media.location.point.latitude
except: latitude =""
try: longitude = media.location.point.longitude
except: longitude =""
try: tags = self.GetListTags(media.tags)
except: tags =""
try: photo = media.get_thumbnail_url()
except: photo =""
try: video = media.videos['standard_resolution'].url
except: video =""
if longitude!="":
fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(float(longitude),float(latitude))))
fet.setAttributes([id_photo,text, user_name,user_full_name,user_id,user_profile_picture,comments,comments_count,likes_count, created_time,link_profile,media_type, latitude, longitude, tags, photo,video])
pr = layer.dataProvider()
pr.addFeatures([fet])
self.CreateMarker(categorized,media,photo,layer)
return
#Create marker with instagram photo
def CreateMarker(self,categorized,media,thumb,layer):
self.update_progressbar(50)
startSvgTag = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg><g>"""
endSvgTag = """ </g></svg>"""
data = requests.get(thumb, stream=True).content
base64data = base64.b64encode(data).replace('\n','')
base64String = '<image xlink:href="data:image/png;base64,{0}" width="320" height="240"/>'.format(base64data)
if self.settings.value("instagram2qgis/outpath")=="" :
path =tempfile.gettempdir() + os.sep + media.id + '.jpg.svg'
else:
#Icons
p=QFileInfo(self.settings.value("instagram2qgis/outpath")).path()+ os.sep
svgpath = p + "instagram_svg"
if not os.path.exists(svgpath):
os.makedirs(svgpath)
path = svgpath + os.sep + media.id + '.jpg.svg'
#Style
qmlpath = p +"instagram_qml"
if not os.path.exists(qmlpath):
os.makedirs(qmlpath)
with open(path, 'w') as f:
f.write( startSvgTag + base64String + endSvgTag)
svgStyle = {}
svgStyle['name'] = path
svgStyle['size'] = '30'
sym_image = QgsSvgMarkerSymbolLayerV2.create(svgStyle)
symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
symbol.changeSymbolLayer(0, sym_image)
new_category = QgsRendererCategoryV2(str(media.id), symbol,str(media.id))
categorized.append(new_category)
renderer = QgsCategorizedSymbolRendererV2("id_photo", categorized)
layer.setRendererV2(renderer)
layer.updateExtents()
layer.triggerRepaint()
try:#Save style Layer
layer.saveNamedStyle(qmlpath + os.sep +'instagram_style.qml')
except:
None
self.update_progressbar(75)
return
#Copy coord canvas class
class CopyCoords(QgsMapTool):
def __init__(self, iface,parent=None):
QgsMapTool.__init__(self, iface.mapCanvas())
self.canvas = iface.mapCanvas()
self.iface = iface
self.parent=parent
self.cursor = QCursor(QPixmap(["16 16 3 1",
" c None",
". c #FF0000",
"+ c #FFFFFF",
" ",
" +.+ ",
" ++.++ ",
" +.....+ ",
" +. .+ ",
" +. . .+ ",
" +. . .+ ",
" ++. . .++",
" ... ...+... ...",
" ++. . .++",
" +. . .+ ",
" +. . .+ ",
" ++. .+ ",
" ++.....+ ",
" ++.++ ",
" +.+ "]))
def activate(self):
self.canvas.setCursor(self.cursor)
def canvasReleaseEvent(self, event):
crsSrc = self.canvas.mapRenderer().destinationCrs()
crsWGS = QgsCoordinateReferenceSystem(4326)
x = event.pos().x()
y = event.pos().y()
point = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)
#Convert coords to EPSG:4326
xtrans = QgsCoordinateTransform(crsSrc, crsWGS)
point = xtrans.transform(QgsPoint(point.x(),point.y()))
self.parent.ln_lat.setText(str(point.x()))
self.parent.ln_lng.setText(str(point.y()))
self.iface.mapCanvas().unsetMapTool(self.parent.mapTool)
self.parent.exec_()