Jump to content

Search the Community

Showing results for tags 'p4d'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Delphi Questions and Answers
    • Algorithms, Data Structures and Class Design
    • VCL
    • FMX
    • RTL and Delphi Object Pascal
    • Databases
    • Network, Cloud and Web
    • Windows API
    • Cross-platform
    • Delphi IDE and APIs
    • General Help
    • Delphi Third-Party
  • C++Builder Questions and Answers
    • General Help
  • General Discussions
    • Embarcadero Lounge
    • Tips / Blogs / Tutorials / Videos
    • Job Opportunities / Coder for Hire
    • I made this
  • Software Development
    • Project Planning and -Management
    • Software Testing and Quality Assurance
  • Community
    • Community Management

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Delphi-Version

Found 11 results

  1. Greetings, I have several pieces of Python code that checks one condition in a loop, if it is met, it outputs Print, if not waits 5 seconds and checks again, and so on endlessly. How do I stop the script using delphi? Can I somehow send ctrl+c or something like that there. The answer from Demo33 did not fit v - 3.12.dll
  2. I found some nice Python code on WWW.SBERT.NET that perfectly suited my need to find the best matching images in two file sets. The file sets are related to each other: they origin the same celluloids, but were created with different quality of scanning equipment. In addition, cropping and tilting may have taken place, and in different ways. I modified the example code to create a file with information on the best fitting high-quality-version of the low-Q image, as well as the three top score values. Here is the code that runs perfectly in Python, version 3.10. I am using PyScripter: great! You can easily test it with your own files, though it may require a series of Python modules to be installed before it runs. from sentence_transformers import SentenceTransformer, util from PIL import Image model = SentenceTransformer("clip-ViT-B-32") f = open("E:/Fotos/testmap/ListMatchingFotos.txt", "a") lijst = ["E:/Fotos/File_nr1.JPG","E:/Fotos/File_nr2.JPG"] # this is the list of low quality images. image_names = ["M:/Fotos/negatieven 001.jpg","M:/Fotos/negatieven 002.jpg","M:/Fotos/negatieven 003.jpg","M:/Fotos/negatieven 004.jpg","M:/Fotos/negatieven 005.jpg","M:/Fotos/negatieven 006.jpg","M:/Fotos/negatieven 007.jpg","M:/Fotos/negatieven 008.jpg"] image_names += lijst encoded_image = model.encode([Image.open(filepath) for filepath in image_names], batch_size=128, convert_to_tensor=True, show_progress_bar=False) processed_images = util.paraphrase_mining_embeddings(encoded_image) threshold = 0.99 near_duplicates = [image for image in processed_images if image[0] < threshold] L = len(near_duplicates) for j in range(len(lijst)): # narrow the list of pairs to consider only the files in the "Lijst" searchresults = [] for i in range(0,L): score, image_id1, image_id2 = near_duplicates[i] idf = image_names.index(lijst[j]) if (( (image_names[image_id1] == image_names[idf] ) and (image_id2 != idf) ) and (not (image_names[image_id2] in lijst))) or (( (image_names[image_id2] == image_names[idf] ) and (image_id1 != idf) ) and (not (image_names[image_id1] in lijst))): searchresults.append( near_duplicates[i] ) ls = len(searchresults) score1 = 0 score2 = 0 score, image_id1, image_id2 = searchresults[0] if ls > 1: score1, image_id11, image_id21 = searchresults[1] if ls > 2: score2, image_id12, image_id22 = searchresults[2] if image_id1 != idf: image_id2 = image_id1 if score < 85/100: f.write( image_names[idf] + " " + image_names[image_id2] + " Score1: {:.3f}%".format(score * 100) + " Score2: {:.3f}%".format(score1 * 100) + " Score3: {:.3f}%".format(score2 * 100) + str(" NO MATCH OR VERY POOR \n")) else: f.write( image_names[idf] + " " + image_names[image_id2] + " Score1: {:.3f}%".format(score * 100) + " Score2: {:.3f}%".format(score1 * 100) + " Score3: {:.3f}%\n".format(score2 * 100)) f.close() However, the very same code doesn't run in Python4Delphi, although it uses the same PythonEngine.dll and path and libraries. I got the error message "Project .... raised exception class EPyAttributeError with message 'AttributeError: 'NoneType' object has no attribute 'flush'". The error is generated in the very first line "from sentence_transformers import...", on both modules, either combined or in separate lines. Here is my delphi version of the code above. Function TPyForm.Picture_Matching_using_Python(Foto_bestanden : String; VAR Zoeklijst :TArray<string>; TekstBestand :String; TargetScore : integer) : Boolean; VAR Mem :TStringList; Lijst, BeterLijst: String; Fotos : Tarray<String>; begin If Foto_bestanden = '' then exit; Fotos := Foto_bestanden.Split([',']); Lijst := '['; BeterLijst := '['; for Var Bestand : String in Fotos DO Lijst := Lijst + '"' + B2F(Bestand) + '"' + ','; Lijst := copy(Lijst,1,length(Lijst)-1)+ ']'; for Var Bestand : String in Zoeklijst DO BeterLijst := BeterLijst + '"' + B2F(Bestand) + '"' + ','; BeterLijst := copy(BeterLijst,1,length(BeterLijst)-1)+']'; TRY Mem := TStringList.Create; With Mem DO begin Add('import os'); Add('from PIL import Image'); Add(' from sentence_transformers import SentenceTransformer, util'); Add('model = SentenceTransformer("clip-ViT-B-32") '); Add('f = open("' + B2F(TekstBestand) + '", "a")'); Add('lijst = '+ Lijst ); Add('image_names = '+ BeterLijst ); Add('image_names += lijst'); Add('encoded_image = model.encode([Image.open(filepath) for filepath in image_names], batch_size=128, convert_to_tensor=True, show_progress_bar=False)'); Add('processed_images = util.paraphrase_mining_embeddings(encoded_image)'); Add('threshold = 99/100'); Add('near_duplicates = [image for image in processed_images if image[0] < threshold] '); Add('l = len(near_duplicates) '); Add('for j in range(len(lijst)): '); Add(' searchresults = [] '); Add(' for i in range(0,l): '); Add(' score, image_id1, image_id2 = near_duplicates[i] '); Add(' idf = image_names.index(lijst[j]) '); Add(' if (( (image_names[image_id1] == image_names[idf] ) and (image_id2 != idf) ) and (not (image_names[image_id2] in lijst))) or ' + ' (( (image_names[image_id2] == image_names[idf] ) and (image_id1 != idf) ) and (not (image_names[image_id1] in lijst))): '); Add(' searchresults.append( near_duplicates[i] ) '); Add(' ls = len(searchresults) '); Add(' score1 = 0' ); Add(' score2 = 0' ); Add(' score, image_id1, image_id2 = searchresults[0]'); Add(' if ls > 1: score1, image_id11, image_id21 = searchresults[1] '); Add(' if ls > 2: score2, image_id12, image_id22 = searchresults[2] '); Add(' if image_id1 != idf: image_id2 = image_id1'); Add(' if score < ' + TargetScore.tostring + '/100: '); Add(' f.write( image_names[idf] + " " + image_names[image_id2] + " Score1: {:.3f}%".format(score * 100) + " Score2: {:.3f}%".format(score1 * 100) + " Score3: {:.3f}%".format(score2 * 100) + str(" GEEN OF TWIJFELACHTIGE MATCH \n"))'); Add(' else:'); Add(' f.write( image_names[idf] + " " + image_names[image_id2] + " Score1: {:.3f}%".format(score * 100) + " Score2: {:.3f}%".format(score1 * 100) + " Score3: {:.3f}%\n".format(score2 * 100))' ); Add('f.close() '); end; TRY Result := True; PythonEngine1.ExecString( ansiString( Mem.text ) ); Except Result := False; END; FINALLY Mem.Free; END; end; I have no idea how to proceed, and do hope that anyone does. I would very much appreciate any help. Jan
  3. Hi, 1. Is there a discord discussion group link that i can join ? ( i found one , https://discord.com/channels/989230637342933042/990834240608415834 , this is a correct forum related to this topic ?) 2. i have this simple python code, in the attached file , main.py - i wish to use a simple memo, 2 buttons (one for start_bot another for stop_bot) and when python4delphi component will read and execute script from main.py and add message receive from Telegram bot into the memo1. i have defined the following in delphi beside the main.py, 1. a pythonEngine and a pythonGUIInputOut component and set the relevant properties, i.e. IO to memo1. etc. 2. i have in my start_button try to executeStrings( memo1.lines) , but no result display my problem is i am unable to get the updates from the python , telegram bot , message receive into the Delphi(10.3)'s Form memo1. and i not even sure whether the bot is running. I have tested to run the python code. (in python 3.9) environment, it ran as expectedly. i am thinking to use the wrapDelphi to wrap the memo1 to the main.py by importing the memo1 component into the python script to add messages or clearing the memo1.lines , can any one help me by giving some advise , what do think i need to do or is wrapping the delphi memo1 component and change my python function i.e. echo() , handle_json() to change the content of the wrapped delphi's memo1.lines in the python code ? Thanks. main.py
  4. My Delphi programs with the P4D-component PyEmbeddedResEnvironment310 run like a charm, as long as I keep them on my own machine (W11 + Delphi 11.3 Enterprise). On the target machines (W10), everything looks good: the embedded "3.10" environment is exactly the same, and contains all the required python libraries. Besides, I have the registry key "Computer\HKEY_CURRENT_USER\Software\Embarcadero\BDS\22.0\Environment Variables" adjusted through the batch file: "reg_env.bat", from P4D github. In there, "PYTHONENVIRONMENTDIR" reads "C:\Program Files\MyProgram", where the folder "3.10" stands aside the program executable (I also tried "C:\Program Files\MyProgram\3.10" by the way). Note that the programs work as normal, except for that the Python scripts don't work. No errors occur. Just no effects. What is it what I do wrong? Many thanks ahead. Jan
  5. shineworld

    First Python + DelphiVCL Program

    Good, after a long time stressing this forum, especially the Python4Delphi channel, with lots of rookie requests, I got to a good point with the development of my first Python program. Until a few months ago I had always ignored Python and its possibilities as Delphi has always been a tool with which I create all my works and I have never thought of anything else. When Python4Delphi and DelphiVCL showed up I wondered if I could do something interesting with both and I must admit that although Python was completely new land to me, the fact of sticking with Delphi anyway took away any doubt. .. I had to try. Basically, the program is pure Python (after being compiled with Cython), an embedded version, with the addition of DelphiVCL (I've never used FMX so it's better to start from the VCL that I know very well) and some Python modules made in Delphi where I put the more delicate parts and in use real threads and not "crippled" threads by the GIL. I anticipate, it is nothing transcendental, but as a first Python project, I am satisfied with it. Description of video In this short video, we can see the execution of an external program written in Python for the holding of print markers necessary to calculate the zero machining, the rotation of the piece on the work table, and all the scaling needed to compensate for the error of model printing between CAD and plotter printer. The Python program interacts directly with the CNC that moves the XYZ axes for the final cut through an API Client (cnc_api_client_core in PyPi) to the CNC control software API Server, retrieving information and sending direct commands to the CNC System. Image capture is done using a proprietary IP Camera equipped with LED lighting. The Python program is executed through an embedded version of the language prepared with all the necessary tools and allows two UI, vertical and horizontal, to adapt to all types of monitors. NOTE: The below CNC Control Software is 100% made with Delphi πŸ™‚ Many Thanks to forum people for the support!
  6. I gonna run python script in separate thread. My PythonEngine has IO field assigned with TPythonGUIInputOutput component What is the correct way to synchronize output (e.g. print("Hello World!") to Delphi's TMemo component? As far as I know VCL is not thread safe... Thank you.
  7. Hi all. To complete my first Python + DelphiVCL program I need to expose to Python an extra Image Viewer Control. I don't want to create a custom delphivcl.pyd which is a good thing remains original and installable with pip install delphivcl, so I've tried to add the component in a custom package. Well, seems simple to do but does not work fine... The control to expose is TImgView32 which inherits from: TImgView32->TCustomImgView32->TCustomImage32->TCustomPaintBox32->TCustomControl so it is close to TLabel and looking at DelphiVCL code I've made same steps: library cnc_vision_ext; uses osPyCncVisionExt in 'sources\osPyCncVisionExt.pas'; exports PyInit_cnc_vision_ext; {$E pyd} begin end. unit osPyCncVisionExt; interface uses PythonEngine; function PyInit_cnc_vision_ext: PPyObject; cdecl; implementation uses System.Classes, System.SysUtils, System.Variants, Winapi.Windows, Vcl.ExtCtrls, VarPyth, WrapDelphi, WrapVclExtCtrls, WrapVclControls, WrapDelphiClasses, GR32_Image; type TPyDelphiImgView32 = class(TPyDelphiControl) private function GetDelphiObject: TImgView32; procedure SetDelphiObject(const Value: TImgView32); public class function DelphiObjectClass: TClass; override; property DelphiObject: TImgView32 read GetDelphiObject write SetDelphiObject; end; TPyExtensionManager = class private FEngine: TPythonEngine; FModule: TPythonModule; FWrapper: TPyDelphiWrapper; public procedure WrapperInitializationEvent(Sender: TObject); end; var ExtensionManager: TPyExtensionManager; { module import functions } function PyInit_cnc_vision_ext: PPyObject; begin Result := nil; try ExtensionManager.FEngine := TPythonEngine.Create(nil); ExtensionManager.FEngine.AutoFinalize := False; ExtensionManager.FEngine.UseLastKnownVersion := True; ExtensionManager.FEngine.LoadDllInExtensionModule(); ExtensionManager.FModule := TPythonModule.Create(nil); ExtensionManager.FModule.Engine := ExtensionManager.FEngine; ExtensionManager.FModule.ModuleName := 'cnc_vision_ext'; ExtensionManager.FWrapper := TPyDelphiWrapper.Create(nil); ExtensionManager.FWrapper.Engine := ExtensionManager.FEngine; ExtensionManager.FWrapper.Module := ExtensionManager.FModule; ExtensionManager.FModule.Initialize; ExtensionManager.FWrapper.OnInitialization := ExtensionManager.WrapperInitializationEvent; ExtensionManager.FWrapper.Initialize; Result := ExtensionManager.FModule.Module; except end; end; { TPyDelphiImgView32 } class function TPyDelphiImgView32.DelphiObjectClass: TClass; begin Result := TImgView32; end; function TPyDelphiImgView32.GetDelphiObject: TImgView32; begin Result := TImgView32(inherited DelphiObject); end; procedure TPyDelphiImgView32.SetDelphiObject(const Value: TImgView32); begin inherited DelphiObject := Value; end; { TPyExtensionManager } procedure TPyExtensionManager.WrapperInitializationEvent(Sender: TObject); begin FWrapper.RegisterDelphiWrapper(TPyDelphiImgView32); end; initialization ExtensionManager := TPyExtensionManager.Create; finalization ExtensionManager.Free; end. Well, compilation OK and import on Python OK, but when I try to create the object assigning the parent I got that: from delphivcl import * from cnc_vision_ext import * class TestForm(Form): def __init__(self, owner): # print type of self ('__main__.TestForm') print(type(self)) # create a vcl label and assign parent: WORKS self.label = Label(self) self.label.Parent = self self.label.Left = 10 self.label.Top = 10 self.label.Caption = 'Hello World' # create a ext image and assign parent: ERROR self.image = ImgView32(self) # <-- AttributeError: Owner receives only Delphi objects self.image.Parent = self self.image.Left = 10 self.image.Top = 30 self.image.Width = 200 self.image.Height = 100 def main(): Application.Initialize() Application.Title = 'test' MainForm = TestForm(Application) MainForm.Show() FreeConsole() Application.Run() if __name__ == '__main__': main() ΓΉ If I check with a Python console the types seem very close: D:\x\develop\qem\cnc_vision_1>python Python 3.9.12 (tags/v3.9.12:b28265d, Mar 23 2022, 23:52:46) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from delphivcl import * >>> from cnc_vision_ext import * >>> frm = Form(None) >>> lbl = Label(frm) >>> lbl.Parent = frm >>> type(lbl) <class 'Label'> >>> lbl.__doc__ 'Wrapper for Delphi TLabel\n' >>> lbl.ClassName 'TLabel' >>> img = ImgView32(frm) # does not work with frm as like as lbl Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Owner receives only Delphi objects >>> img = ImgView32(None) # try with none to check object type >>> type(img) <class 'ImgView32'> >>> img.__doc__ 'Wrapper for Delphi TImgView32\n' >>> img.ClassName 'TImgView32' Thank you in advance for any suggestion πŸ™‚
  8. Hi all. What I love of Delphi is memory management and overall the integration of FastMM and related memory leak management. All my projects are Memory Leak Free (just thanks to reports of FastMM which permits me to create a better code). Now I'm migrating some programs to Python using DelphiVCL and I'm falling into odd memory leaks. In a Python (3.9.12) application that uses DelphiVCL (0.1.40) I've noticed a continuous memory leak in some simple operations with VCL objects like Checkbox. I've attached a very simple Python program that uses a Timer to constantly update the Enabled state of a Checkbox. In the sample, I've also added a const to enable a tracemalloc and confirm the continue grow of memory used by <Checkbox>.Enabled = True # enable/disable tracemalloc to exclude the memory impact of tracemalloc TRACEMALLOC_ENABLED = False By default, TRACEMALLOC_ENABLED is set to False to remove any impact of tracemalloc framework. If enabled, the first mouse down on the form capture the BASE snapshot of memory. Any following mouse down, report on console the comparison of current snapshot with the first. Initially, tracemalloc internals is in the top ten results, but after some time Checkbox1.Enabled = True gain the top. If I disable the interesting lines, commenting on them, any memory leak disappears: def __on_timer(self, sender): """ self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True self.CheckBox1.Enabled = True """ I've placed many CheckBox1.Enabled to exasperate the case-test but usually, I do this for a lot of controls in update events. This is the memory usage captured with Process Explorer on running Python process with TRACEMALLOC_ENABLED = False: test.zip
  9. shineworld

    Add #13#10 to a string

    It is embarrassing but I was not able to set a multiline text in a Button Caption. Usually in Delphi is only necessary to: MyButton.Caption = 'first line' + #13#10 + 'second line' What to get same behaviour in Python + DelphiVCL ?
  10. Albion

    Testing with python

    Good day everyone! I have a question. Perhaps someone has already experienced this. I have a ready-made program on Delphi. And I need to initialize and execute all the functions of this program using a Python script. Is it possible to accomplish this task only with the help of TPytnon components? Without adding memos and other things as shown in the demo programs. Just run the script and get the result. Maybe someone can help with this question. I would be very grateful for any help. Thanks for attention.
  11. Good afternoon, I wanted to know if it is possible to get some information about Python4Delphi, except for two webinars, maybe there are some books, video tutorials, analyzes of all this. I really liked the ability to use Python in Delphi, but as I'm still new to this business, it's quite difficult for me to figure it out without instructions / tutorials / books. If you have the opportunity to share something that may be useful in the study of this topic, I will be incredibly grateful to you.
Γ—