sending post using instagrapi - python

Hi i am trying to send a post into Instagram using instagrapi module
and I'm using photo_upload to do that but that not working
here is my code :
from instagrapi import Client
print("im gonna log in")
cl = Client()
cl.login("UserName", "Password")
cl.photo_upload("picture.png", "hello this is a test from instagrapi")
but i get this error :
Traceback (most recent call last): File "E:\HadiH2o\Documents\_MyProjects\Python\Test\Test.py", line 10, in <module> File "C:\Users\HadiH2o\AppData\Local\Programs\Python\Python39\lib\site-packages\instagrapi\mixins\photo.py", line 205, in photo_upload
upload_id, width, height = self.photo_rupload(path, upload_id) File "C:\Users\HadiH2o\AppData\Local\Programs\Python\Python39\lib\site-packages\instagrapi\mixins\photo.py", line 170, in photo_rupload
raise PhotoNotUpload(response.text, response=response, **last_json) instagrapi.exceptions.PhotoNotUpload: {"debug_info":{"retriable":false,"type":"ProcessingFailedError","message":"Request processing failed"}}
help please!

I found the answer to the question
To send a post to Instagram, the photo format must be JPG and the photo size must be less than 1080 x 1080.
this is the code :
from pathlib import Path
from PIL import Image
from instagrapi import Client
image = Image.open("picture.jpg")
image = image.convert("RGB")
new_image = image.resize((1080, 1080))
new_image.save("new_picture.jpg")
cl = Client()
cl.login("UserName", "Password")
phot_path = "new_picture.jpg"
phot_path = Path(phot_path)
cl.photo_upload(phot_path , "hello this is a test from instagrapi")

Related

Azure Detect With Stream Invalid Request

it's my first time with Azure Face Detection API and I'm using this code right here:
import os
import io
import cv2
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
from PIL import Image, ImageDraw, ImageFont
API_KEY = '...'
ENDPOINT = '...'
image = open('realmadrid.jpg', 'rb')
face_client = FaceClient(ENDPOINT, CognitiveServicesCredentials(API_KEY))
response_detected_faces = face_client.face.detect_with_stream(
image=image,
detection_model='detection_03',
recognition_model='recognition_04',
return_face_landmarks=True,
)
if not response_detected_faces:
raise Exception("No face detected!")
print(f"Number of face detected {len(response_detected_faces)}")
The problem is that everytime I run this code it gives me an exception:
/home/thecowmilk/dev/azure_faceapi/venv/bin/python /home/thecowmilk/dev/azure_faceapi/faceapi/starting.py
Traceback (most recent call last):
File "/home/thecowmilk/dev/azure_faceapi/faceapi/starting.py", line 20, in <module>
detected_faces = face_client.face.detect_with_stream(
File "/home/thecowmilk/dev/azure_faceapi/venv/lib/python3.8/site-packages/azure/cognitiveservices/vision/face/operations/_face_operations.py", line 782, in detect_with_stream
raise models.APIErrorException(self._deserialize, response)
azure.cognitiveservices.vision.face.models._models_py3.APIErrorException: (InvalidRequest) Invalid request has been sent.
Process finished with exit code 1
I don't know how to solve this. It looks there's not much info about Azure Face Detection API. I'd appreciate your thoughts <3!
According to Get face landmarks, to get face landmark data, set the detectionModel parameter to DetectionModel.Detection01 and the returnFaceLandmarks parameter to true.
IList<DetectedFace> faces2 = await faceClient.Face.DetectWithUrlAsync(url: imageUrl, returnFaceId: true, returnFaceLandmarks: true, detectionModel: DetectionModel.Detection01);
Instead of detection_03 use detection_01:
response_detected_faces = face_client.face.detect_with_stream(
image=image,
detection_model='detection_01',
recognition_model='recognition_04',
return_face_landmarks=True,
)
You can refer to recent changes/limitations about some features of Face API: Responsible AI investments and safeguards for facial recognition

Approach to get currently playing media's thumbnail on Windows only works once per Python instance

I'm trying to get the thumbnail of the currently playing media on windows, and thanks to this answer (https://stackoverflow.com/a/66037406/15491505) i got quite far, however I'm facing a strange issue where in get_thumbnail() the variable byte_buffer always ends up being 0 in length after the first run... as in the first time I call it I get back the thumbnail perfectly, but all further calls end up failing...
This is what I have so far:
from winrt.windows.media.control import GlobalSystemMediaTransportControlsSessionManager as MediaManager
from winrt.windows.storage.streams import DataReader, Buffer, InputStreamOptions
from io import BytesIO
from PIL import Image
import asyncio
async def get_thumbnail():
sessions = await MediaManager.request_async()
current_session = sessions.get_current_session()
if current_session:
properties = await current_session.try_get_media_properties_async()
media_info = {song_attr: properties.__getattribute__(song_attr) for song_attr in dir(properties) if song_attr[0] != '_'}
if media_info.get('thumbnail'):
thumb_stream_ref = media_info['thumbnail']
thumb_read_buffer = Buffer(5000000)
readable_stream = await thumb_stream_ref.open_read_async()
readable_stream.read_async(thumb_read_buffer, thumb_read_buffer.capacity, InputStreamOptions.READ_AHEAD)
buffer_reader = DataReader.from_buffer(thumb_read_buffer)
byte_buffer = buffer_reader.read_bytes(thumb_read_buffer.length)
binary = BytesIO()
binary.write(bytearray(byte_buffer))
binary.seek(0)
print(len(bytearray(byte_buffer)))
img = Image.open(binary)
return img
thumbnail = asyncio.run(get_thumbnail())
thumbnail.show()
# This will work
thumbnail2 = asyncio.run(get_thumbnail())
thumbnail2.show()
# This will not
Example output:
C:\Users\willy\Desktop>test.py
117672
0
Traceback (most recent call last):
File "C:\Users\willy\Desktop\test.py", line 39, in <module>
thumbnail2 = asyncio.run(get_thumbnail())
File "C:\Python38\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "C:\Users\willy\Desktop\test.py", line 31, in get_thumbnail
img = Image.open(binary)
File "C:\Python38\lib\site-packages\PIL\Image.py", line 2930, in open
raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x00000278D2FB3B30>
Solution
Simply await the result of the readable_stream.read_async(...) call:
...
readable_stream = await thumb_stream_ref.open_read_async()
await readable_stream.read_async(thumb_read_buffer, thumb_read_buffer.capacity, InputStreamOptions.READ_AHEAD)
buffer_reader = DataReader.from_buffer(thumb_read_buffer)
...
The thumbnail should now be successfully displayed each time.
Debugging process
(for anyone interested and for similar bugs in the future)
After break-pointing your code, it appeared that, on the second call of get_thumbnail(), byte_buffer was left empty. This indicated that the thumb_read_buffer was not being populated correctly from the stream.
Interestingly, when single-stepping the code instead, the image displayed both times. This suggested to me that maybe an asynchronous function call wasn't being awaited.
Turns out .read_async() (as the function name suggests) is an asynchronous operation in winrt (see IInputStream.ReadAsync on learn.microsoft.com). Hence, awaiting its execution fixed the problem of the empty thumb_read_buffer.

Getting KeyError: 'Endpoint' error in Python when calling Custom Vision API

from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.vision.customvision import prediction
from PIL import Image
endpoint = "https://southcentralus.api.cognitive.microsoft.com/"
project_id = "projectidhere"
prediction_key = "predictionkeyhere"
predict = CustomVisionPredictionClient(prediction_key, endpoint)
with open("c:/users/paul.barbin/pycharmprojects/hw3/TallowTest1.jpg", mode="rb") as image_data:
tallowresult = predict.detect_image(project_id, "test1", image_data)
Python 3.7, and I'm using Azure Custom Vision 3.1? (>azure.cognitiveservices.vision.customvision) (3.1.0)
Note that I've seen the same question on SO but no real solution. The posted answer on the other question says to use the REST API instead.
I believe the error is in the endpoint (as stated in the error), and I've tried a few variants - with the slash, without, using an environment variable, without, I've tried appending various strings to my endpoint but I keep getting the same message. Any help is appreciated.
Full error here:
Traceback (most recent call last):
File "GetError.py", line 15, in <module>
tallowresult = predict.detect_image(project_id, "test1", image_data)
File "C:\Users\paul.barbin\PycharmProjects\hw3\.venv\lib\site-packages\azure\cognitiveservices\vision\customvision\prediction\operations\_custom_vision_
prediction_client_operations.py", line 354, in detect_image
request = self._client.post(url, query_parameters, header_parameters, form_content=form_data_content)
File "C:\Users\paul.barbin\PycharmProjects\hw3\.venv\lib\site-packages\msrest\service_client.py", line 193, in post
request = self._request('POST', url, params, headers, content, form_content)
File "C:\Users\paul.barbin\PycharmProjects\hw3\.venv\lib\site-packages\msrest\service_client.py", line 108, in _request
request = ClientRequest(method, self.format_url(url))
File "C:\Users\paul.barbin\PycharmProjects\hw3\.venv\lib\site-packages\msrest\service_client.py", line 155, in format_url
base = self.config.base_url.format(**kwargs).rstrip('/')
KeyError: 'Endpoint'
CustomVisionPredictionClient takes two required, positional parameters: endpoint and credentials. Endpoint needs to be passed in before credentials, try swapping the order:
predict = CustomVisionPredictionClient(endpoint, prediction_key)

Getting NameError: name 'video' is not defined in Vapoursynth/Python

Trying to make a gif in vapoursynth, followed tutorials yet keep getting name error. If anyone could help explain what's wrong with it and how to fix it, I would appreciate it.
Failed to initialize script.
Failed to evaluate the script:
Python exception: name 'video' is not defined
Traceback (most recent call last):
File "src\cython\vapoursynth.pyx", line 1927, in
vapoursynth.vpy_evaluateScript
File "src\cython\vapoursynth.pyx", line 1928, in
vapoursynth.vpy_evaluateScript
File "C:/Users/caitl/Pictures/bbh.vpy", line 12, in
core.max_cache_size = 1000 #Use this command to limit the RAM usage. 1000 or 2000 is fine.
NameError: name 'video' is not defined
Code
import os
import vapoursynth as vs
import havsfunc as haf
import mvsfunc as mvs
import descale as descale
import muvsfunc as muvs
import resamplehq as rhq
import CSMOD as cs
import Dither as dither
core = vs.get_core()
video = core.std.Trim(video, a, b)
video = haf.QTGMC(video, Preset="Slower", TFF=True)
video = core.fmtc.resample(video, css="444")
video = descale.Debilinear(video, 629,354)
video = mvs.BM3D(video, sigma=8.84, radius1=1, profile1="fast", matrix="709")
video = hnw.FineSharp(video, sstr=1.13)
video = core.std.CropRel(video, left=72, top=52, right=107, bottom=52)
video = core.fmtc.bitdepth(video, bits=8)
video.set_output()
You didn't define video before the call to Trim which takes it as a parameter.
The example script in the documentation says you need to create a video object, for example, by loading a file:
from vapoursynth import core
video = core.ffms2.Source(source='Rule6.mkv')
This loads a video file Rule6.mkv using the ffms2 plugin, which it assumes is installed correctly.

google.gax.errors.RetryError StatusCode.DEADLINE_EXCEEDED

from this github:
https://github.com/GoogleCloudPlatform/python-docs-samples
i am trying to test Video intelligence API and do label analysis.
import argparse
import sys
import time
import io
import base64
from google.cloud.gapic.videointelligence.v1beta1 import enums
from google.cloud.gapic.videointelligence.v1beta1 import (
video_intelligence_service_client)
# [END imports]
#python labels.py /Users/rockbaek/tildawatch-contents/EpicSkillShot/M7-_VukSueY/SKT\ vs\ KT\ Game\ 3\ _\ Grand\ Finals\ S7\ LCK\ Spring\ 2017\ _\ KT\ Rolster\ vs\ SK\ Telecom\ T1\ G3\ 1080p-M7-_VukSueY.mp4
def analyze_labels_file(path):
""" Detects labels given a file path. """
video_client = (video_intelligence_service_client.
VideoIntelligenceServiceClient())
features = [enums.Feature.LABEL_DETECTION]
with io.open(path, "rb") as movie:
content_base64 = base64.b64encode(movie.read())
operation = video_client.annotate_video(
'', features, input_content=content_base64)
print('\nProcessing video for label annotations:')
while not operation.done():
sys.stdout.write('.')
sys.stdout.flush()
time.sleep(15)
print('\nFinished processing.')
# first result is retrieved because a single video was processed
results = operation.result().annotation_results[0]
for i, label in enumerate(results.label_annotations):
print('Label description: {}'.format(label.description))
print('Locations:')
for l, location in enumerate(label.locations):
positions = 'Entire video'
if (location.segment.start_time_offset != -1 or
location.segment.end_time_offset != -1):
positions = '{} to {}'.format(
location.segment.start_time_offset / 1000000.0,
location.segment.end_time_offset / 1000000.0)
print('\t{}: {}'.format(l, positions))
print('\n')
if __name__ == '__main__':
# [START running_app]
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('path', help='GCS file path for label detection.')
args = parser.parse_args()
analyze_labels_file(args.path)
# [END running_app]
# [END full_tutorial]
and then i run it from terminal
python labels.py MP4_FILE_PATH
After quite a while, it fails with this error code:
Traceback (most recent call last):
File "labels.py", line 123, in <module>
analyze_labels_file(args.path)
File "labels.py", line 52, in analyze_labels_file
'', features, input_content=content_base64)
File "/Library/Python/2.7/site-packages/google/cloud/gapic/videointelligence/v1beta1/video_intelligence_service_client.py", line 237, in annotate_video
self._annotate_video(request, options), self.operations_client,
File "/Library/Python/2.7/site-packages/google/gax/api_callable.py", line 428, in inner
return api_caller(api_call, this_settings, request)
File "/Library/Python/2.7/site-packages/google/gax/api_callable.py", line 416, in base_caller
return api_call(*args)
File "/Library/Python/2.7/site-packages/google/gax/api_callable.py", line 376, in inner
return a_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/google/gax/retry.py", line 144, in inner
raise exc
google.gax.errors.RetryError: GaxError(Retry total timeout exceeded with exception, caused by <_Rendezvous of RPC that terminated with (StatusCode.DEADLINE_EXCEEDED, Deadline Exceeded)>)
Please help why it is not working! :(
For the visitors from future, I faced same error with Cloud Speech API.
I just increased the timeout value while calling operation.result. That solved it. Though this fragment isn't in OP's code, it should be in Google's example code OP mentioned.
operation.result(timeout=90) # increase this numeric value
I tried your code with a small video and it seems to work just fine for me. Maybe you are hitting some form of quota or limits (refer: https://cloud-dot-devsite.googleplex.com/video-intelligence/limits)? I have also run large videos loaded in Google Storage and using Python client library without issue.
Other step to try: send the request to the service via a curl command.

Categories