コード例 #1
0
ファイル: image_analysis.py プロジェクト: danielxu05/parser
def main():
    filelist = list()
    for filename in os.listdir("pictures"):
        try:
            im = Image.open("pictures/" + filename)
            imifd = get_exif_data(im)
            print(filename)
            print(imifd['DateTimeDigitized'])
            gpsdata = ""
            city = ""
            try:
                gpsdata = get_lat_lon(imifd)
                print gpsdata
                city = reverse_geocode.get(gpsdata)
                print(city)
            except (KeyError):
                print('No GPS data avaiable')
            print("--------------->>>>>>>>>>>>>>>>>>>>>")
            temp = picture_info(filename, imifd['DateTimeDigitized'], gpsdata,
                                city)
            filelist.append(temp)
        except:
            (IOError)
    filelist.sort(key=attrgetter('time'))
    for x in filelist:
        temp = x.name + "  " + " " + x.time + " " + " " + str(
            x.city) + " " + str(x.gps)
        print(temp)
        write_into_file("result.txt", 'a', temp + '\n')
コード例 #2
0
    def post(self, request, format=None):
        """
        Prova per python
        """

        user_id = Token.objects.get(key=request.auth.key).user_id
        user = User.objects.get(id=user_id)
        print(request.data['sensors'])
        token = get_random_string(length=32)

        coordinates = (request.data["lat"], request.data["long"])
        posibleLocalitzacio = reverse_geocode.get(coordinates)
        localitzacio = Location.objects.filter(
            pais=posibleLocalitzacio["country"],
            localitat=posibleLocalitzacio["city"]).first()

        if localitzacio:
            client = Client.objects.create(usuari=user,
                                           identificador=request.data["name"],
                                           token=token,
                                           actiu=True,
                                           movil=False,
                                           localitzacio=localitzacio,
                                           quarentena=True)

            for sensor in request.data["sensors"]:
                sensor = Sensor.objects.create(
                    identificador=sensor['name'],
                    tipusSensor=SensorType.objects.get(id=sensor['type']),
                    client=client)

            return Response(client.id)

        else:

            localitzacioCrear = Location.objects.create(
                pais=posibleLocalitzacio["country"],
                localitat=posibleLocalitzacio["city"],
                latitud=request.data["lat"],
                longitud=request.data["long"],
                altitud=0)

            client = Client.objects.create(usuari=user,
                                           identificador=request.data["name"],
                                           token=token,
                                           actiu=True,
                                           movil=False,
                                           localitzacio=localitzacioCrear,
                                           quarentena=True)

            for sensor in request.data["sensors"]:
                sensor = Sensor.objects.create(
                    identificador=sensor['name'],
                    tipusSensor=SensorType.objects.get(id=sensor['type']),
                    client=client)

            return Response(client.id)
コード例 #3
0
ファイル: db_handler.py プロジェクト: utsha1510/messiah
 def _rev_geocode(lat, long):
     """
     reverse codes a pair of latitude and longitude into city and country
     :param lat: latitude of the place
     :param long: longitude of the place
     :return: city, country
     """
     coordinate = (lat, long)
     loc_data = reverse_geocode.get(coordinate)
     return loc_data['city'], loc_data['country']
コード例 #4
0
ファイル: GeoMetExtractor.py プロジェクト: obbada126/csci572
def main(argv=None):
    if argv is None:
        argv = sys.argv

    try:
        try:
            opts, args = getopt.getopt(argv[1:], 'vf:', ['verbose', 'file='])
        except getopt.error, msg:
            raise Error(msg)

        if len(opts) == 0:
            raise Error(_helpMessage)
        _filePath = None

        for option, value in opts:
            if option in ('-f', '--file'):
                _filePath = value
            elif option in ('-v', '--verbose'):
                global _verbose
                _verbose = True

        if not checkFilePath(_filePath):
            raise Error("JSON file doesn't exist")

        inputFile = open(_filePath)
        jsonObject = json.load(inputFile)
        dirty = False
        if 'longitude' in jsonObject and 'lattitude' in jsonObject:
            lat = float(jsonObject['lattitude'])
            long = float(jsonObject['longitude'])
            verboseLog((lat, long))
            if lat != 0 and long != 0:
                dirty = True
                geoInfo = reverse_geocode.get((lat, long))
                jsonObject['countryCode'] = geoInfo['country_code']
                jsonObject['city'] = geoInfo['city']
                jsonObject['country'] = geoInfo['country']
                verboseLog(jsonObject)
        inputFile.close()

        if dirty:
            outputFile = open(_filePath, "wb")
            jsonString = json.dumps(jsonObject, ensure_ascii=False, encoding='iso-8859-1')
            outputFile.write(jsonString.encode('utf8'))
            outputFile.close()
コード例 #5
0
    def show_location(self):
        lat = self.data['latitude']
        long = self.data['longitude']

        try:
            latt = self.dms_to_dd(lat[0], lat[1], lat[2])
            longg = self.dms_to_dd(long[0], long[1], long[2])

            factor = 10.0**2
            latt = math.trunc(latt * factor) / factor
            longg = math.trunc(longg * factor) / factor

            # print(latt, longg)
            coordinates = (latt, longg)
            location = reverse_geocode.get(coordinates)
        except Exception as e:
            print("Can't determine location")
            print(e)
            return
        else:
            print("This forest is near " + location['city'] + " in " +
                  location['country'])
コード例 #6
0
def get_country_info_coords(coords):
    """
    Get country information for input lat/lon coordinates

    Parameters
    ----------
    coords : list or tuple
        list of coord tuples (lat, lon) or single coord tuple

    Raises
    ------
    ModuleNotFoundError
        if library reverse_geocode is not installed
    ValueError
        if input format is incorrect

    Returns
    -------
    list
        list of dictionaries containing country information for each input
        coordinate
    """
    try:
        import reverse_geocode as rg
    except ModuleNotFoundError:
        raise ModuleNotFoundError('Cannot retrieve country information for '
                                  'lat / lon coordinates. Please install '
                                  'library reverse_geocode')
    if isinstance(coords, np.ndarray):
        coords = list(coords)
    if not isinstance(coords, (list, tuple)):
        raise ValueError(
            'Invalid input for coords, need list or tuple or array')

    if isnumeric(coords[0]) and len(coords) == 2:  #only one coordinate
        return [rg.get(coords)]

    return rg.search(coords)
コード例 #7
0
def get_exif(file_name):

    f = open(file_name, 'rb')

    tagjson = {'SourceFile': file_name}

    tags = exifread.process_file(f, details=True)
    f.close()

    lat, lon = get_exif_location(tags)
    for dt_tag in tags:
        dt_value = '%s' % tags[dt_tag]
        tagjson[dt_tag.replace(" ", ":")] = dt_value  # tag group separator

    tagjson['EXIF:GpsLat'] = lat
    tagjson['EXIF:GpsLon'] = lon

    if lat and lon:
        location = reverse_geocode.get([lat, lon])
        tagjson['Location:country_code'] = location["country_code"]
        tagjson['Location:city'] = location["city"]
        tagjson['Location:country'] = location["country"]

    return tagjson
コード例 #8
0
ファイル: geo.py プロジェクト: alemela/wiki-needs-pictures
import csv
import reverse_geocode

with open('../data/data.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
    first = 0
    for row in spamreader:
        if (first == 0):
            first = 1
            continue
        lat = float(row[1])
        lon = float(row[2])

        coordinates = (lat, lon)
        location = reverse_geocode.get(coordinates)

        country_file = open('../data/countries/' + location["country_code"], 'a')
        writer = csv.writer(country_file)
        writer.writerow([row[0], row[1], row[2], row[3], row[4], row[5]])
コード例 #9
0
#Function to find current ISS location and number of astronauts in realtime
#Using Open Notify API to get the ISS data

import requests, reverse_geocode

loc_response = requests.get("http://api.open-notify.org/iss-now.json")
coordinates_data = loc_response.json()
coordinates = (coordinates_data['iss_position']['latitude']), (
    coordinates_data['iss_position']['longitude'])
location = reverse_geocode.get(coordinates)

astro_response = requests.get("http://api.open-notify.org/astros.json")
astro_data = astro_response.json()

# 9 people are currently in space.
# print astro_data['number']
print "Current ISS location is " + location['city'] + ", " + location['country']
print "There are " + str(
    astro_data['number']) + " astronauts in ISS right now: "
for i in range(0, astro_data["number"]):
    print "Name: " + astro_data['people'][i][
        'name'] + ", Craft: " + astro_data['people'][i]['craft']
コード例 #10
0
 def get_poi(self, point: GPXPoint) -> POI:
     lookup_result = reverse_geocode.get(
         (point.latitude, point.longitude)
     )
     return POI(city=lookup_result["city"])
コード例 #11
0
ファイル: main.py プロジェクト: Monara/SmartPhotoFrame
def update_image_and_info(dbx, oldImageName):
	
	#Default file and info to display
	imgPath = defaultImage
	uploaderName = "Nėra" #none
	placeStr = "Nenurodyta" #unspecified location
	
	if dbx != None:
		
		try:
			#List files
			listFolder = dbx.files_list_folder(path=uploadImagesFolder)
			listFolderImages = list(filter(lambda x: x.name.endswith(".jpeg") or x.name.endswith(".jpg"), listFolder.entries)) #can also include gif, tiff, tif, bmp, png
			fileCount = len(listFolderImages)
			print(fileCount)
		except:
			listFolderImages = None
			fileCount = 0

		if fileCount > 0 and listFolderImages != None:
			#Sort list: newest uploaded first
			fileArraySorted = sorted(listFolderImages, key=lambda x: x.server_modified, reverse=True)
			
			#Cycle images uploaded in the last month since newest
			newestUploadedDate = fileArraySorted[0].server_modified
			month = timedelta(days=30)
			showImagesFrom = newestUploadedDate - month
			entriesToShow = [x for x in fileArraySorted if x.server_modified > showImagesFrom]
			
			if len(entriesToShow) < imagesToCycle: #if there isn't enough images to cycle, append older images
				entriesToShow += fileArraySorted[len(entriesToShow):imagesToCycle]
			
			nextImageEntry = get_next_image_entry(entriesToShow, oldImageName)
			print(nextImageEntry.server_modified)
			
			if nextImageEntry != None:
				dbxImgMeta = get_dropbox_image(dbx, nextImageEntry)
					
				if dbxImgMeta != None:
					imgPath = nextImageEntry.name #local
					#Get uploader name from metadata
					uploaderID = dbxImgMeta.sharing_info.modified_by
					uploaderName = dbx.users_get_account(uploaderID).name.given_name

					#Get GPS coordinates from metadata
					mediaMeta = dbxImgMeta.media_info
					#media_info: pending or metadata
					if mediaMeta.is_metadata():
						readyImgMeta = mediaMeta.get_metadata()
						if readyImgMeta.location != None:
							gps = (readyImgMeta.location.latitude, readyImgMeta.location.longitude)
							place = reverse_geocode.get(gps) 
							placeStr = place["city"] + ", " + place["country_code"] #dict data type. country or country_code
			
	
	#Resize image
	localImg = Image.open(imgPath)
	(thumbnailWidth, thumbnailHeight) = localImg.size
	#Width doesn't need resizing, unless height is too large
	if thumbnailHeight > defaultScreenHeight:
		difference = thumbnailHeight - defaultScreenHeight #often 168px
		resizeBy = difference / thumbnailHeight
		resizeWidth = int(thumbnailWidth * (1 - resizeBy))
		localImg = localImg.resize((resizeWidth, defaultScreenHeight), Image.ANTIALIAS)
	
	useImage = ImageTk.PhotoImage(localImg) #same folder as program
	displayImage.configure(image=useImage)
	displayImage.image = useImage
	displayUploader.configure(text=" " + uploaderName)		
	displayLocation.configure(text=placeStr)
	
	#Remove old image locally
	if imgPath != defaultImage and imgPath != None: 
		os.remove(imgPath)
		
	#Run again after delay
	root.after(1800000, update_image_and_info, dbx, imgPath) #30 min 1800000
コード例 #12
0
def getNearestLocation(iss):
    """Return the nearest city to the ISS"""

    nearestLocation = reverse_geocode.get(iss["coordinates"])
    return nearestLocation
コード例 #13
0
    def post(self, request, format=None):
        """
        Prova per python
        """

        # coordinates = (request.data["lat"], request.data["long"])
        # return Response(reverse_geocode.get(coordinates))

        if not "hora" in request.data:
            return Response("Es necesari enviar la hora de presa de dades",
                            status=status.HTTP_404_NOT_FOUND)

        if not "token" in request.data:
            return Response("Es necesari enviar un token",
                            status=status.HTTP_404_NOT_FOUND)

        client = Client.objects.filter(token=request.data["token"]).first()

        if not client:
            return Response("El client no es valid",
                            status=status.HTTP_404_NOT_FOUND)

        if not client.movil:

            for key, dada in request.data["data"].items():
                sensorActual = Sensor.objects.filter(
                    client=client, identificador=key).first()
                if sensorActual:
                    Registre.objects.create(hora=request.data["hora"],
                                            valor=str(dada),
                                            sensor=sensorActual)

            return Response("Les dades s'han introduit correctament",
                            status=status.HTTP_200_OK)

        else:
            if not "lat" in request.data or not "long" in request.data:
                return Response("Es necesari enviar la latitud i longitud",
                                status=status.HTTP_404_NOT_FOUND)

            coordinates = (request.data["lat"], request.data["long"])
            posibleLocalitzacio = reverse_geocode.get(coordinates)
            localitzacio = Location.objects.filter(
                pais=posibleLocalitzacio["country"],
                localitat=posibleLocalitzacio["city"]).first()

            if localitzacio:

                for key, dada in request.data["data"].items():
                    sensorActual = Sensor.objects.filter(
                        client=client, identificador=key).first()
                    if sensorActual:
                        #                       RegistreMovil.objects.create(hora=request.data["hora"], valor=dada[key], localitzacio=localitzacio, latitudReal=float(request.data["lat"]), longitudReal=float(request.data["long"]), sensor=sensorActual)
                        RegistreMovil.objects.create(hora=request.data["hora"],
                                                     valor=str(dada),
                                                     localitzacio=localitzacio,
                                                     latitudReal=5.7,
                                                     longitudReal=7.4,
                                                     sensor=sensorActual)

                return Response(
                    "Les dades s'han afegit correctament en una localitzacio existent",
                    status=status.HTTP_200_OK)

            else:

                localitzacioCrear = Location.objects.create(
                    pais=posibleLocalitzacio["country"],
                    localitat=posibleLocalitzacio["city"],
                    latitud=request.data["lat"],
                    longitud=request.data["long"],
                    altitud=0)
                for key, dada in request.data["data"].items():
                    sensorActual = Sensor.objects.filter(
                        client=client, identificador=key).first()
                    if sensorActual:
                        RegistreMovil.objects.create(
                            hora=request.data["hora"],
                            valor=str(dada),
                            localitzacio=localitzacioCrear,
                            latitudReal=request.data["lat"],
                            longitudReal=request.data["long"],
                            sensor=sensorActual)

                return Response(
                    "Les dades s'han afegit correctament en una localitzacio creada",
                    status=status.HTTP_200_OK)