The follwowing is a code written in blender python
import bpy
import os
import subprocess
import time
bpy.data.materials["Material"].use_face_texture = True
customer_id = "john33"
image1 = "orangeskin.jpg" # define image 1 from folder
imagepath1 = "C:\\Users\\mrryan\\Desktop\\models\\materialsjpeg\\"
image2 = "elec.jpg"
imagepath2 = "C:\\Users\\mrryan\\Desktop\\models\\materialsjpeg\\"
#Step 1 go to Edit Mode
bpy.ops.object.editmode_toggle()
#step 2 insert image in the Image Editor
bpy.context.area.type = 'IMAGE_EDITOR'
bpy.ops.uv.smart_project()
bpy.ops.image.open(filepath = image1, directory= imagepath1 ,
files=[{"name":image1, "name":image1}])
#Step 3 back to Object Mode TRY AND CHANGE TITLE TO `CUSTOMER_ID AND FILE`
bpy.ops.object.editmode_toggle()
bpy.data.window_managers["WinMan"].sketchfab.title = "orangetube"
#Step 4 save new.blend
filepath = os.path.join(r"C:\Users\mrryan\Desktop", customer_id + "orangytube.blend")
bpy.ops.wm.save_as_mainfile(filepath = filepath)
toggleedit = bpy.ops.object.editmode_toggle()
#here is the problem!!!!
subprocess.call(["bpy.ops.export.sketchfab()"], shell = True)
#new texture
#Step 1 go to Edit Mode
#step 2 insert image in the Image Editor
bpy.context.area.type = 'IMAGE_EDITOR'
bpy.ops.image.open(filepath= image2, directory= imagepath2,
files= [{"name":image2,"name":image2}])
bpy.ops.uv.smart_project()
#Step 3 back to Object Mode
bpy.ops.object.editmode_toggle()
bpy.data.window_managers["WinMan"].sketchfab.title = "elec-tube"
#Step 4 save new.blend
filepath = os.path.join(r"C:\Users\mrryan\Desktop", customer_id + "elec-tube.blend")
bpy.ops.wm.save_as_mainfile(filepath = filepath)
bpy.ops.export.sketchfab()
The idea is, eventually to programmatically change the active object( which is combined but not joined with another object) to have different materials and change the shape, etc. Each individual model combination would be uploaded to sketchfab separately and saved as a blender file.
At this stage my problem is that, while uploading, the script does not wait until the first upload is finished.This generates an error that says to please wait for the current upload to finish. and as a result only one model is uploaded.
subprocess.Popen
has been tried but i could not get it to work.
Perhaps the return values were wrong?
How can you get the script to upload the first model, wait until finished, then continue to make the adjustments and upload the second?
(I work at Sketchfab, but I don't have much experience in Blender scripting).
The issue is that the Sketchfab Blender Exporter uses a thread for the upload, meaning the subprocess will return, with a thread still running in the background.
I would experiment in launching bpy.ops.export.sketchfab() using a new Thread and join(), instead of just subprocess.
The following resources might help:
python multithreading wait till all threads finished
https://docs.python.org/2/library/multiprocessing.html
http://www.blender.org/documentation/blender_python_api_2_62_2/info_gotcha.html#strange-errors-using-threading-module
Let us know how it goes!
Related
I was trying to Play multiple small mp4 files that is in a folder. And i was using this example as my reference:
https://github.com/oaubert/python-vlc/blob/master/generated/3.0/examples/play_buffer.py
But when i ran the py file giving that particular folder it read all of the files but closes after playing the first file. Can Someone Help me with this.
And i know i can just use a for loop to play all the files in a folder but i don't want any stutter between transitioning those files(Or in simple words i want seamless transition between those files). So any help would be appreciated.
i don't want any stutter between transitioning those files
What you are looking for is called "gapless playback". Sadly, this is not currently supported by LibVLC.
Regardless, to play multiple individual files, you need to either feed them one after the other to the mediaplayer (by subscribing to the EndReached event, for example) or use a MediaList object.
You have picked a complicated and arguably inappropriate code example for your scenario.
Try something like this (without ctypes):
import vlc
import glob
import time
base_folder = './'
# vlc State 0: Nowt, 1 Opening, 2 Buffering, 3 Playing, 4 Paused, 5 Stopped, 6 Ended, 7 Error
playing = set([1,2,3,4])
def add_media(inst, media_list, playlist):
for song in playlist:
print('Loading: - {0}'.format(song))
media = inst.media_new(song)
media_list.add_media(media)
playlist = glob.glob(base_folder + "/" + "*.mp3")
playlist = sorted(playlist)
media_player = vlc.MediaListPlayer()
inst = vlc.Instance('--no-xlib --quiet ')
media_list = vlc.MediaList()
add_media(inst, media_list, playlist)
media_player.set_media_list(media_list)
media_player.play()
time.sleep(0.1)
current = ""
idx = 1
player = media_player.get_media_player()
while True:
state = player.get_state()
if state.value == vlc.State.Ended or state == vlc.State.Error:
if idx == len(playlist)+1:
break
title = player.get_media().get_mrl()
if title != current:
print("\nPlaying - {0}\t{1} of {2}".format(str(title), idx, len(playlist)))
current = title
idx += 1
time.sleep(0.1)
print("\nPlaylist Finished")
Here, we use a MediaListPlayer() rather than a media.player_new_from_media() or a media_player_new() because we are playing a set of media, not a single instance.
You can improve on this by controlling it via events using the event_manager() and attaching appropriate events for the player to listen for.
i am working on a telethon script of python which runs if the channel/group receives new message
i am looking at the message id for running my script
i am a beginner of python so with what knowledge i have
i am using this following code.
prev_msgid=0
latest_msgid = message.id
if latest_msgid>prev_msgid:
print('latest message')
prev_msgid = message.id
else:
print('old message')
but when i run this code every time the previous message resets to 0
i need a way for when i run this code multiple times the prev_msgid is automatically changed to the latest message id.
thank you.
like #Quba said you need a way to store data in persistent way
Pickle is the fastest solution for you. It can save python object as a file:
import pickle
from os import path
prev_msgid = 0
# check if saved
if path.exists("prev_msgid"):
# load
with open("prev_msgid", 'rb') as f:
prev_msgid = pickle.load(f)
prev_msgid += 1
# save
with open("prev_msgid", 'wb') as f:
pickle.dump(prev_msgid, f)
print(prev_msgid)
Every time you run the script it will add one to prev_msgid. See that it makes a file that named "prev_msgid"
I'm trying to insert an image into a libreoffice document that is handled/controlled by unotools.
Therefore I start LibreOffice with this command:
soffice --accept='socket,host=localhost,port=8100;urp;StarOffice.Service'
Inside my python code I can connect to LibreOffice:
from unotools import Socket, connect
from unotools.component.writer import Writer
context = connect(Socket('localhost', 8100))
writer = Writer(context)
(This code is taken from this documentation: https://pypi.org/project/unotools/)
By using writer.set_string_to_end() I can add some text to the document. But I also want to insert an image into the document. So far I couldn't find any resource where this was done. The image is inside of my clipboard, so ideally I want to insert the image directly from there. Alternatively I can save the image temporarily and insert the saved file.
Is there any known way how to insert images by using unotools? Any alternative solution would also be great.
I've found a way to insert images by using uno instead of unotools:
import uno
from com.sun.star.awt import Size
from pythonscript import ScriptContext
def connect_to_office():
if not 'XSCRIPTCONTEXT' in globals():
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext(
'com.sun.star.bridge.UnoUrlResolver', localContext )
client = resolver.resolve("uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext" )
global XSCRIPTCONTEXT
XSCRIPTCONTEXT = ScriptContext(client, None, None)
def insert_image(doc):
size = Size()
path = uno.systemPathToFileUrl('/somepath/image.png')
draw_page = self.doc.DrawPage
image = doc.createInstance( 'com.sun.star.drawing.GraphicObjectShape')
image.GraphicURL = path
draw_page.add(image)
size.Width = 7500
size.Height = 5000
image.setSize(size)
image.setPropertyValue('AnchorType', 'AT_FRAME')
connect_to_office()
doc = XSCRIPTCONTEXT.getDocument()
insert_image(doc)
sources:
https://ask.libreoffice.org/en/question/38844/how-do-i-run-python-macro-from-the-command-line/
https://forum.openoffice.org/en/forum/viewtopic.php?f=45&t=80302
I still don't know how to insert an image from my clipboard, I worked around that problem by saving the image first. If someone knows a way to insert the image directly from the clipboard that would still be helpful.
In my project a user can upload an image and once it is saved I can run a post_save signal to modify the image using Pillow. And after modifying the image I need to replace the existing image with the new image. Now the issue is if I run the save method in the post_save signal it will lead to maximum recursion error.So instead of this I am thinking of using update method but it throws an error regarding the characters in the file.
Below is the code:
def menuImageLocation(instance,filename):
return "%s/%s"%(instance,filename)
class restaurantMenuImage(models.Model):
restaurant = models.ForeignKey(restaurantCreateUpdate)
title = models.CharField(max_length=100,null=True,blank=True)
menuImage = models.ImageField(upload_to=menuImageLocation,null=True,blank=True,verbose_name="Menu Image")
def __unicode__(self):
return str(self.restaurant)
#receiver(post_save,sender=restaurantMenuImage)
def modifyMenuImage(sender,instance,**kwargs):
getRestaurant = restaurantCreateUpdate.objects.get(restaurantName=instance.restaurant)
image_path = instance.menuImage.path
filename = os.path.basename(image_path)
image_hold = Image.open(image_path)
image = image_hold.resize((300,300),Image.ANTIALIAS)
temp_loc = "%s/%s/%s/tmp"%(settings.MEDIA_ROOT,"menu",getRestaurant.uniqueID)
if not os.path.exists(temp_loc):
os.makedirs(temp_loc)
temp_file_path = os.path.join(temp_loc,filename)
if os.path.exists(temp_file_path):
temp_path = os.path.join(temp_loc,"%s" %(random.random()))
os.makedirs(temp_path)
temp_file_path = os.path.join(temp_path,filename)
temp_image = open(temp_file_path,"w")
image.save(temp_image,quality=80)
temp_data = open(temp_file_path,"r")
image_file = File(temp_data)
instance.menuImage.save(filename, image_file)
So if I run the last line of the code, this will result into maximum recursion error, and instead of using save method I am trying to use update method the file path but for that I am getting the error that the characters exceed the max_length of the "image_file". Will appreciate any help.
Before you run the last line, add a check if the image path of the instance is not the same as the new image path. Then the code will only run once. Your problem occurs, because the code in your post_save signal is always run when you call save on your model, which creates an endless loop. So you need to be careful when you call save in your post_save signal method.
Something like this should help:
if instance.menuImage != image_file:
instance.menuImage.save(filename, image_file)
We have an AJA Ki Pro recorder at another location and I a need to created an automated system that pulls the recorded files over to my editing studio. So far I have successfully been able to pull recordings using a python script run via an Applescript through Automator. I than can trigger the application from iCal. Basically my script involves setting the "MediaState" parameter on my recorder to "Data" (value=1) so I can pull files, comparing the files on the recorder to my local files (it only downloads what I dont already have locally), and then setting the "MediaState" property back to "Rec" (value=0) so the recorder is ready to go again.
Here are the 2 problems I have been unable to resolve so far. Bear with me, I have about 2 days worth of experience with Python :) It seems that I have somehow created a loop where it constantly says "Looking for new clips" and "No new clips found". Ideally I would like to have the script terminate if no new clips are found. I would also like to set this up so that when it finishes a download through cURL, it automatically sets my "MediaState" back to value=0 and ends the script. Here is my code so far:
# This script polls the unit downloads any new clips it hasn't already downloaded to the current directory
# Arguments: hostname or IP address of Ki Pro unit
import urllib, sys, string, os, posix, time
def is_download_allowed(address):
f = urllib.urlopen("http://"+address+"/config?action=get¶mid=eParamID_MediaState")
response = f.read()
if (response.find('"value":"1"') > -1):
return True
f = urllib.urlopen("http://"+address+"/config?action=set¶mid=eParamID_MediaState&value=1")
def download_clip(clip):
url = "http://" + address + "/media/" + clip
print url
posix.system("curl --output " + clip + " " + url);
def download_clips(response):
values = response.split(":")
i = 0
for word in values:
i += 1
if(word.find('clipname') > -1):
clip = values[i].split(',')[0].translate(string.maketrans("",""), '[]{} \,\"\" ')
if not os.path.exists(clip):
print "Downloading clip: " + clip
download_clip(clip)
else:
f = urllib.urlopen("http://"+address+"/config?action=set¶mid=eParamID_MediaState&value=0")
print "No new clips found"
address = sys.argv[1]
while 1:
if (is_download_allowed(address)):
print "Looking for new clips"
f = urllib.urlopen("http://"+address+"/clips")
response = f.read()
download_clips(response)
If the download_clips function is looping through the clip names, why you need that infinite while 1 loop? I think it is not necessary. Just remove it and dedent the block.