Git Product home page Git Product logo

dartpy's Introduction

Hi 👋, You've reached Tim Whiting's GitHub Profile

About Me

  • 🔭 I’m currently working on: My PhD Research, along with a few fun side projects
  • 🌱 I’m currently learning: Languages, Control Flow Analysis
  • 💬 Ask me about: Koka, Control Flow Analysis, Dart, Flutter
  • 📫 How to reach me: Add an issue on one of my repositories, ideally one of the ones that you are interested in collaborating or knowing more about.

Personal Website

.... TODO: .....

dartpy's People

Contributors

b14cknc0d3 avatar timwhiting avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

dartpy's Issues

Cyrillic encoding

Hello! thanks for "dartpy"!

USING: https://github.com/natasha/natasha

CODE:

import 'dart:ffi';

import 'package:dartpy/dartpy.dart';
import 'package:ffi/ffi.dart';

void main(List args) {

pyLibLocation = 'C:\Python312\python312.dll';

dartpyc.Py_Initialize();

final python = '''

from natasha import AddressExtractor
extractor = AddressExtractor()
addresses = """
Абрамцевская улица, дом 16 Б
ул. Абрамцевская, д.3
ул Абрамцевская 5
Абрамцевская ул., 5/2
""".strip().splitlines()

for address in addresses:
matches = extractor(address)
for match in matches:
print(match.fact)
''';

final pystring = python.toNativeUtf8();
dartpyc.PyRun_SimpleString(pystring.cast());

malloc.free(pystring);
print(dartpyc.Py_FinalizeEx());
}

RESULT:

Address(parts=[Street(name='������������', type='�����'), Building(number='16 �', type='���')])
Address(parts=[Street(name='������������', type='�����'), Building(number='3', type='���')])
Address(parts=[Street(name='������������', type='�����'), Building(number='5', type=None)])
Address(parts=[Street(name='������������', type='�����'), Building(number='5/2', type=None)])

NEED:

Address(parts=[Street(name='Абрамцевская', type='улица'), Building(number='16 Б', type='дом')])
Address(parts=[Street(name='Абрамцевская', type='улица'), Building(number='3', type='дом')])
Address(parts=[Street(name='Абрамцевская', type='улица'), Building(number='5', type=None)])
Address(parts=[Street(name='Абрамцевская', type='улица'), Building(number='5/2', type=None)])

code generation not works, the generated code is not generate.

I tried the demo code on the readme, but when I execute dart run build_runner build, the gen_dartpy_example.g.dart file is not generated.

import 'package:dartpy/dartpy.dart';
import 'package:dartpy/dartpy_annotations.dart';
part 'gen_dartpy_example.g.dart';

@PyFunction(module: 'multiply')
int multiply(int a, int b) => pymultiply(a, b);

@PyFunction(module: 'multiply', name: 'multiply')
double mult_double(double a, double b) => pymultiplydouble(a, b);

@PyFunction(module: 'multiply', name: 'multiply')
num mult_num(num a, num b) => pymultiplynum(a, b);

void main() {
  try {
    print(multiply(6, 4));
    print(mult_double(6.13, 5.2));
    print(mult_num(6, 5.2));
    print(mult_num(6, 2));
  } on DartPyException catch (e) {
    if (pyErrOccurred()) {
      dartpyc.PyErr_Print();
    }
    print(e.message);
  }
}

image

image

logs
D:\code\dart\dartpy_demo1>dart --version
Dart SDK version: 2.17.5 (stable) (Tue Jun 21 11:05:10 2022 +0200) on "windows_x64"

D:\code\dart\dartpy_demo1>
D:\code\dart>dart create dartpy_demo1
Creating dartpy_demo1 using template console...

  .gitignore
  analysis_options.yaml
  CHANGELOG.md
  pubspec.yaml
  README.md
  bin\dartpy_demo1.dart
  lib\dartpy_demo1.dart
  test\dartpy_demo1_test.dart

Running pub get...
  Resolving dependencies...
  Changed 46 dependencies!

Created project dartpy_demo1 in dartpy_demo1! In order to get started, run the following commands:

  cd dartpy_demo1
  dart run


D:\code\dart>cd dartpy_demo1\

D:\code\dart\dartpy_demo1>dart pub add dartpy
Resolving dependencies...
+ dartpy 0.0.1+4
+ ffi 1.2.1 (2.0.1 available)
+ freezed_annotation 0.14.3 (2.0.3 available)
+ json_annotation 4.5.0
Downloading dartpy 0.0.1+4...
Changed 4 dependencies!

D:\code\dart\dartpy_demo1>dart pub add -d build_runner
Resolving dependencies...
+ build 2.3.0
+ build_config 1.0.0
+ build_daemon 3.1.0
+ build_resolvers 2.0.9
+ build_runner 2.1.11
+ build_runner_core 7.2.3
+ built_collection 5.1.1
+ built_value 8.3.3
+ checked_yaml 2.0.1
+ code_builder 4.1.0
+ dart_style 2.2.3
  ffi 1.2.1 (2.0.1 available)
+ fixnum 1.0.1
  freezed_annotation 0.14.3 (2.0.3 available)
+ graphs 2.1.0
+ pubspec_parse 1.2.0
+ stream_transform 2.0.0
+ timing 1.0.0
Downloading build_resolvers 2.0.9...
Downloading built_value 8.3.3...
Changed 16 dependencies!

D:\code\dart\dartpy_demo1>cat pubspec.yaml
name: dartpy_demo1
description: A sample command-line application.
version: 1.0.0
# homepage: https://www.example.com

environment:
  sdk: '>=2.17.5 <3.0.0'

# dependencies:
#   path: ^1.8.0

dev_dependencies:
  build_runner: ^2.1.11
  lints: ^2.0.0
  test: ^1.16.0
dependencies: {dartpy: ^0.0.1+4}

D:\code\dart\dartpy_demo1> # Make some modifications on the example code!
D:\code\dart\dartpy_demo1>cat lib\dartpy_demo1.dart
import 'package:dartpy/dartpy.dart';
import 'package:dartpy/dartpy_annotations.dart';
part 'dartpy_demo1.g.dart';

@PyFunction(module: 'multiply')
int multiply(int a, int b) => pymultiply(a, b);

@PyFunction(module: 'multiply', name: 'multiply')
double mult_double(double a, double b) => pymultiplydouble(a, b);

@PyFunction(module: 'multiply', name: 'multiply')
num mult_num(num a, num b) => pymultiplynum(a, b);

D:\code\dart\dartpy_demo1>cat lib\gen_dartpy_example.dart
import 'package:dartpy/dartpy.dart';
import 'package:dartpy/dartpy_annotations.dart';
part 'gen_dartpy_example.g.dart';

@PyFunction(module: 'multiply')
int multiply(int a, int b) => pymultiply(a, b);

@PyFunction(module: 'multiply', name: 'multiply')
double mult_double(double a, double b) => pymultiplydouble(a, b);

@PyFunction(module: 'multiply', name: 'multiply')
num mult_num(num a, num b) => pymultiplynum(a, b);

void main() {
  try {
    print(multiply(6, 4));
    print(mult_double(6.13, 5.2));
    print(mult_num(6, 5.2));
    print(mult_num(6, 2));
  } on DartPyException catch (e) {
    if (pyErrOccurred()) {
      dartpyc.PyErr_Print();
    }
    print(e.message);
  }
}

D:\code\dart\dartpy_demo1>cat bin\dartpy_demo1.dart
import 'package:dartpy/dartpy.dart';
import 'package:dartpy_demo1/dartpy_demo1.dart';

void main() {
  try {
    print(multiply(6, 4));
    print(mult_double(6.13, 5.2));
    print(mult_num(6, 5.2));
    print(mult_num(6, 2));
  } on DartPyException catch (e) {
    if (pyErrOccurred()) {
      dartpyc.PyErr_Print();
    }
    print(e.message);
  }
}

D:\code\dart\dartpy_demo1>dart run build_runner build
[INFO] Generating build script completed, took 324ms
[SEVERE] Nothing can be built, yet a build was requested.
[INFO] Reading cached asset graph completed, took 45ms
[INFO] Checking for updates since last build completed, took 498ms
[INFO] Running build completed, took 4ms
[INFO] Caching finalized dependency graph completed, took 28ms
[INFO] Succeeded after 45ms with 0 outputs (0 actions)

D:\code\dart\dartpy_demo1>dart run
Building package executable...
Failed to build dartpy_demo1:dartpy_demo1:
lib/dartpy_demo1.dart:3:6: Error: Error when reading 'lib/dartpy_demo1.g.dart': The system cannot find the file specified.

part 'dartpy_demo1.g.dart';
     ^
lib/dartpy_demo1.dart:3:6: Error: Can't use 'lib/dartpy_demo1.g.dart' as a part, because it has no 'part of' declaration.
part 'dartpy_demo1.g.dart';
     ^
lib/dartpy_demo1.dart:6:31: Error: Method not found: 'pymultiply'.
int multiply(int a, int b) => pymultiply(a, b);
                              ^^^^^^^^^^
lib/dartpy_demo1.dart:9:43: Error: Method not found: 'pymultiplydouble'.
double mult_double(double a, double b) => pymultiplydouble(a, b);
                                          ^^^^^^^^^^^^^^^^
lib/dartpy_demo1.dart:12:31: Error: Method not found: 'pymultiplynum'.
num mult_num(num a, num b) => pymultiplynum(a, b);
                              ^^^^^^^^^^^^^
Failed to build dartpy_demo1:dartpy_demo1:
lib/dartpy_demo1.dart:3:6: Error: Error when reading 'lib/dartpy_demo1.g.dart': The system cannot find the file specified.

part 'dartpy_demo1.g.dart';
     ^
lib/dartpy_demo1.dart:3:6: Error: Can't use 'lib/dartpy_demo1.g.dart' as a part, because it has no 'part of' declaration.
part 'dartpy_demo1.g.dart';
     ^
lib/dartpy_demo1.dart:6:31: Error: Method not found: 'pymultiply'.
int multiply(int a, int b) => pymultiply(a, b);
                              ^^^^^^^^^^
lib/dartpy_demo1.dart:9:43: Error: Method not found: 'pymultiplydouble'.
double mult_double(double a, double b) => pymultiplydouble(a, b);
                                          ^^^^^^^^^^^^^^^^
lib/dartpy_demo1.dart:12:31: Error: Method not found: 'pymultiplynum'.
num mult_num(num a, num b) => pymultiplynum(a, b);
                              ^^^^^^^^^^^^^

D:\code\dart\dartpy_demo1>

How to pass arguments to the python script?

Hi, I'm trying to use your API to integrate a piece of python script to my flutter app which is written by Dart.
Is it possible to pass arguments to the python script? If so, what should I do?

I noticed that the second example in your README.md pass arguments to the imported function. However, I failed to fully understand it. If my understanding is correct, multiply is a method in multiply.py. But where should I put the multiply.py to make it successfully imported by your API?

Actually, in my need, I hope that users don't need to explicitly download additional python scripts as long as they have some python packages installed on their workstation. So I'm really curious whether I can pass arguments using the inline way.

Thanks for your help!

iOS Compatability ProcessException

I'm wondering if this library is compatible with iOS. Trying to run on an iPad application and getting the following error:
Exception has occurred. ProcessException (ProcessException: Starting new processes is not supported on iOS Command: python3.10-config --ldflags --embed)

flutter doctor -v
[✓] Flutter (Channel stable, 3.16.8, on macOS 14.3.1 23D60 darwin-arm64, locale en-US)
    • Flutter version 3.16.8 on channel stable at ...Source/SDK/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 67457e669f (7 weeks ago), 2024-01-16 16:22:29 -0800
    • Engine revision 6e2ea58a5c
    • Dart version 3.2.5
    • DevTools version 2.28.5

[✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
    • Android SDK at /Users/synchronmac/Library/Android/sdk
    • Platform android-32, build-tools 32.0.0
    • Java binary at: /usr/bin/java
    • Java version Java(TM) SE Runtime Environment (build 19.0.2+7-44)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15C65
    • CocoaPods version 1.12.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[!] Android Studio (not installed)
    • Android Studio not found; download from https://developer.android.com/studio/index.html
      (or visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions).

[✓] VS Code (version 1.87.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.84.0

[✓] VS Code (version 1.84.0-insider)
    • VS Code at /Applications/Visual Studio Code - Insiders.app/Contents
    • Flutter extension can be installed from:
      🔨 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (4 available)
    • iPhone 13 Pro (mobile) • 00008110-00183589AAD8801E • ios            • iOS 17.3.1 21D61
    • iPad (mobile)  • 00008103-000D597A01C8001E • ios            • iOS 17.3.1 21D61
    • macOS (desktop)        • macos                     • darwin-arm64   • macOS 14.3.1 23D60 darwin-arm64
    • Chrome (web)           • chrome                    • web-javascript • Google Chrome 122.0.6261.94

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.

Memory Allocation Failed with python3.12

I tried your example code and tried to run it, but getting memory allocation error in python3.12

Building package executable... 
Built dartmat:dartmat.
Fatal Python error: memory allocation failed
Python runtime state: core initialized

Current thread 0x00007282f247e6c0 (most recent call first):
  <no Python frame>

Can you kindly help, about what's wrong here?

Path issue in Macos

Hey great package , but am not able to run this project , getting Path issues

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Invalid argument(s): Failed to load dynamic library '/Users/rohitsangwan/Drive/Frameworks/Python.framework/Versions/3.9/lib/libpython3.9.dylib': dlopen(/Users/rohitsangwan/Drive/Frameworks/Python.framework/Versions/3.9/lib/libpython3.9.dylib, 0x0001): tried: '/Users/rohitsangwan/Drive/Frameworks/Python.framework/Versions/3.9/lib/libpython3.9.dylib' (file system sandbox blocked open()), '/usr/local/lib/libpython3.9.dylib' (no such file), '/usr/lib/libpython3.9.dylib' (no such file)

this error

herer is my Code

void main() {
  pyLibLocation =
      '/Users/rohitsangwan/Drive/Frameworks/Python.framework/Versions/3.9/lib/libpython3.9.dylib';

  dartpyc.Py_Initialize();
  const python = '''
  print("Hello, world!")
    
    ''';
  final pystring = python.toNativeUtf8();
  dartpyc.PyRun_SimpleString(pystring.cast<Int8>());
  malloc.free(pystring);
  print(dartpyc.Py_FinalizeEx());

  runApp(
    GetMaterialApp(
      title: "Application",
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
    ),
  );
}

pyerr_fetch

When an error occurs, use pyerr_ Fetch obtains information and then throws an exception through Dart to make the error more clear

Cannot parse string to the python function

In this test code, whenever I am trying to send the python function a string value, it's getting it as a byte.

import 'dart:io';

import 'package:dartpy/dartpy.dart';
import 'package:ffi/ffi.dart';

void main() {
  pyLibLocation = '/usr/lib/x86_64-linux-gnu/libpython3.12.so';
  // initializes the python runtime
  pyStart();
  try {
    final pyModule = pyImport('os');
    final pFunc = pyModule.getFunction('getenv');
    final envName = 'HOME';
    final result = pFunc([envName]);
    print(result);
  } on DartPyException catch (e) {
    print(e);
    // Cleans up memory
    pyCleanup();
    exit(1);
  }
  // Cleans up memory
  pyCleanup();
  exit(0);
}

This is the exception showing up

Building package executable... 
Built dartmat:dartmat.
Traceback (most recent call last):
  File "<frozen os>", line 783, in getenv
  File "<frozen _collections_abc>", line 807, in get
  File "<frozen os>", line 682, in __getitem__
  File "<frozen os>", line 764, in encode
TypeError: str expected, not bytes
Unhandled exception:
UnimplementedError: Python error occurred
#0      pyConvertBackDynamic (package:dartpy/src/helpers/converters/converters.dart:41:7)
#1      CallablePyObjectList.call (package:dartpy/src/helpers/helpers.dart:172:12)
#2      main (file:///home/soumyaxubuntu/Documents/Dart/dartmat/bin/dartmat.dart:17:25)
#3      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#4      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

Now, I tried with casting Char to it but still getting this

Building package executable... 
Built dartmat:dartmat.
Unhandled exception:
UnimplementedError
#0      pyConvertDynamic (package:dartpy/src/helpers/converters/converters.dart:33:3)
#1      CallablePyObjectList.call (package:dartpy/src/helpers/helpers.dart:158:15)
#2      main (file:///home/soumyaxubuntu/Documents/Dart/dartmat/bin/dartmat.dart:18:25)
#3      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#4      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

Implementing Dartpy

Hi Tim!

Wanted to thank your for a super cool project! I was curious how you were about to get this file structure set up and functioning properly.

Screen Shot 2021-06-07 at 9 22 28 PM

I've tried to implement a bunch of solution but keep getting this error. Any way you could point me in the right direction on how you got this working the way you did?

Screen Shot 2021-06-07 at 9 29 17 PM

We were able to pull in the math module and extract pow, and that was amazing!! I feel we are super close!!

oh yeah, and in the screen shot is the path for windows python dynamic import :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.