class AnotherScreen(Screen): def __init__(self, **kw): super().__init__(**kw) self.button = ObjectProperty(None) self.tap_target_view = MDTapTargetView( outer_circle_color=(1, 1, 1), widget=self.ids.button, title_text=" tutorials", draw_shadow=True, title_text_size=50, title_text_color=(255, 255, 0, 1), widget_position="right_top", description_text= " most part of our\n life is always wasted \n due to lack of knowledge", description_text_color=(100, 100, 0, 1), ) def monk(self): if self.tap_target_view.state == "close": self.tap_target_view.start() else: self.tap_target_view.stop() def lonk(self): p = monk() self.add_widget(p) def rongr(self): print("hi")
class DemoApp(MDApp): def build(self): screen = Screen() self.help_str = Builder.load_string(helper_string) screen.add_widget(self.help_str) self.taptarget = MDTapTargetView( widget=self.help_str.get_screen('bye').ids.textview, title_text='text', widget_position='left_bottom', title_text_size='20sp', description_text="GO next", outer_radius='80dp', description_text_color=[1, 0, 0, 0], outer_circle_alpha=0.40, target_radius='40dp') return screen def open_tapview(self): self.taptarget.start() def close_tapview(self): self.taptarget.stop() self.help_str.get_screen('bye').ids.next.disabled = False
class CustomTapTargetViews: def __init__(self, app): self.tap_1 = MDTapTargetView( widget=app.root.ids.MD_tap_target_view_screen.ids.button1, title_text='This is an MDTapTargetView', description_text='This is the description', widget_position='left_bottom', cancelable=True) self.tap_2 = MDTapTargetView( widget=app.root.ids.MD_tap_target_view_screen.ids.button2, title_text='This is an MDTapTargetView', description_text='This is the description', widget_position='right_top', cancelable=True) def toggle_tap_1(self): if self.tap_1.state == 'close': self.tap_1.start() if self.tap_2.state == 'open': self.tap_2.stop() else: self.tap_1.stop() def toggle_tap_2(self): if self.tap_2.state == 'close': self.tap_2.start() if self.tap_1.state == 'open': self.tap_1.stop() else: self.tap_2.stop()
class DemoApp(MDApp): def build(self): screen = Builder.load_string(KV) self.tap_target_view = MDTapTargetView( widget=screen.ids.button, title_text="Lire", description_text="Patientez en écoutant la lecture de ce texte", widget_position="left_bottom", ) return screen def tap_target_start(self): if self.tap_target_view.state == "close": self.tap_target_view.start() else: self.tap_target_view.stop()
class ContentNavigationDrawer(BoxLayout): def __init__(self, **kwargs): super(ContentNavigationDrawer, self).__init__(**kwargs) self.tap_target_view = None def tap_target_start(self): if self.tap_target_view is None: self.tap_target_view = MDTapTargetView( widget=self.ids.commitTipsButton, widget_position="right_bottom", title_text="Tips for You", title_text_size="20sp", description_text= "After selecting a numeric values in\nthe above controls using the\nincrement or decrement " + "buttons,\nclick on the new number to\ncommit to the ventilator", description_text_color=[1, 1, .5, 1]) if self.tap_target_view.state == "close": self.tap_target_view.start() else: self.tap_target_view.stop() def numeric_buttons_callback(self, button_type=None, widget=None): """ This method is called by the increment and decrement buttons in the bottom sheet of the Control Screen :param button_type: str value, its either 'decrement' or 'increment' :param widget: The widget whose text is to be updated :return: None """ value_char = '' if widget.text.isdigit(): value_digit = eval(widget.text) else: values = widget.text.split(':') value_char = values[0] + ':' value_digit = eval(values[-1]) if button_type == 'decrement': value_digit -= 1 else: value_digit += 1 widget.text = value_char + str(value_digit)
class AmazonApp(MDApp): def build(self): screen = Screen() self.theme_cls.theme_style = "Light" self.helper_string = Builder.load_string(code_helper) screen.add_widget(self.helper_string) self.skip_target_view = MDTapTargetView( widget=self.helper_string.get_screen( 'firstwelcome').ids.welcome_skip, title_text="Next", widget_position="left_bottom", title_text_size="20sp", description_text="GO next", outer_radius='80dp', description_text_color=[1, 0, 0, 0], outer_circle_alpha=0.40, target_radius='40dp') self.android_target_view = MDTapTargetView( widget=self.helper_string.get_screen( 'androidinfo').ids.android_info, title_text="Hey!!", widget_position="center", title_text_size="20sp", title_position="right_top", description_text="I am your assistant\nClick on me", outer_radius='180dp', description_text_color=[0, 0, 0, 1], outer_circle_alpha=0.5, target_radius='50dp') self.skip_target_view.start() self.android_target_view.start() #self.dob initialize self.dob_entered = True return screen def theme_switcher(self): if self.theme_cls.theme_style == "Dark": self.theme_cls.theme_style = "Light" else: self.theme_cls.theme_style = "Dark" def tap_target_stop(self): self.skip_target_view.stop() def android_info_targerview_stop(self): self.android_target_view.stop() def help_chip(self, instance, value): help_cancel_btn_first = MDIconButton( icon='checkbox-marked-circle-outline', on_release=self.help_close_dialog_btn) self.help_dialog = MDDialog( title='Help', text= 'Little android is your assistant\nClick the android for more Info', size_hint=(0.7, 0.1), buttons=[help_cancel_btn_first]) self.help_dialog.open() def help_close_dialog_btn(self, obj): self.help_dialog.dismiss() def username_checker(self): username_check_false = True self.username_text_data = self.helper_string.get_screen( 'usernamescreen').ids.username_text.text # print(self.username_text_data) try: int(self.username_text_data) except: username_check_false = False if username_check_false or self.username_text_data.split() == []: cancel_btn_username_dialogue = MDFlatButton( text='Retry', on_release=self.close_username_dialog) self.username_dialoge = MDDialog( title='Invalid Username', text='Please Enter a valid Username', size_hint=(0.7, 0.2), buttons=[cancel_btn_username_dialogue]) self.username_dialoge.open() else: screen_usernamescreen = self.helper_string.get_screen( 'usernamescreen') screen_usernamescreen.ids.username_enter.disabled = False screen_usernamescreen.ids.username_check_extra_button.icon = 'account-check-outline' screen_usernamescreen.ids.username_check_btn.text_color = [ 1, 1, 1, 0 ] screen_usernamescreen.ids.username_check_btn.md_bg_color = [ 1, 1, 1, 0 ] screen_usernamescreen.ids.username_check_extra_button.text_color = self.theme_cls.primary_color screen_usernamescreen.ids.username_check_extra_button.pos_hint = { 'center_x': 0.5, 'center_y': 0.62 } screen_usernamescreen.ids.username_check_extra_button.user_font_size = '60sp' def close_username_dialog(self, obj): self.username_dialoge.dismiss() # DOB Picker #self.dob for Date of birth def show_date_picker(self): date_dialog = MDDatePicker( callback=self.get_date, year=1999, month=1, day=1, ) date_dialog.open() def get_date(self, date): self.dob = date dob_input_screen_selector = self.helper_string.get_screen('dobinput') #here i put the next button disbaled as False so user can enter in that window dob_input_screen_selector.ids.dob_enter.disabled = False dob_input_screen_selector.ids.account_shield.icon = 'shield-account' dob_input_screen_selector.ids.dob.text = str(self.dob) dob_input_screen_selector.ids.secure.text_color = [0, 1, 0, 0.7] self.store.put('userInfo', name=self.username_text_data, dob=str(self.dob)) self.username_changer() def navigation_draw(self): self.helper_string.get_screen('about').manager.current = "about" def username_changer(self): self.helper_string.get_screen('main').ids.title.title = self.store.get( 'userInfo')['name'] def price(self): link = self.helper_string.get_screen('main').ids.Link.text if link.split() != []: self.price_finder(URL=link) else: self.helper_string.get_screen('main').manager.current = "main" def price_finder(self, URL): try: r = requests.get(URL, headers={"User-Agent": "Defined"}) soup = BeautifulSoup(r.content, "html.parser") try: if 'amazon' in URL: try: price_one = soup.find(id="priceblock_dealprice") price = price_one except: print("in ourprice") price_two = soup.find(id="priceblock_ourprice") price = price_two elif 'flipkart' in URL: try: price = soup.find(class_='_1vC4OE _3qQ9m1') except: self.helper_string.get_screen( 'main').manager.current = "main" except: self.helper_string.get_screen('main').manager.current = "main" if price == None: self.helper_string.get_screen('main').manager.current = "main" else: current_price = price.get_text() self.helper_string.get_screen( 'result').ids.realPrice.text = current_price except: self.helper_string.get_screen('main').manager.current = "main" def setting_username_checker(self): username_check_false = True self.new_username = self.helper_string.get_screen( 'setting').ids.new_username.text try: int(self.new_username) except: username_check_false = False if username_check_false or self.new_username.split() == []: cancel_btn_username_dialogue = MDFlatButton( text='Retry', on_release=self.close_username_dialog) self.username_dialoge = MDDialog( title='Invalid Username', text='Please Enter a valid Username', size_hint=(0.7, 0.2), buttons=[cancel_btn_username_dialogue]) self.username_dialoge.open() else: self.username_text_data = self.new_username self.store.put('userInfo', name=self.username_text_data) self.username_changer() self.helper_string.get_screen('main').manager.current = "main" def change_edit_username(self): self.helper_string.get_screen( 'setting').ids.new_username.text = self.store.get( 'userInfo')['name'] def on_start(self): self.store = JsonStore("userProfile.json") try: if self.store.get('userInfo')['name'] != "": self.username_changer() self.helper_string.get_screen('main').manager.current = "main" except KeyError: self.helper_string.get_screen( 'firstwelcome').manager.current = 'firstwelcome'
class AmazonApp(MDApp): def build(self): screen = Screen() self.theme_cls.theme_style = "Light" self.helper_string = Builder.load_string(code_helper) screen.add_widget(self.helper_string) self.skip_target_view = MDTapTargetView( widget=self.helper_string.get_screen( 'firstwelcome').ids.welcome_skip, title_text="Next", widget_position="left_bottom", title_text_size="20sp", description_text="GO next", outer_radius='80dp', description_text_color=[1, 0, 0, 0], outer_circle_alpha=0.40, target_radius='40dp') self.android_target_view = MDTapTargetView( widget=self.helper_string.get_screen( 'androidinfo').ids.android_info, title_text="Hey!!", widget_position="center", title_text_size="20sp", title_position="right_top", description_text="I am your assistant\nClick on me", outer_radius='180dp', description_text_color=[0, 0, 0, 1], outer_circle_alpha=0.5, target_radius='50dp') self.skip_target_view.start() self.android_target_view.start() #self.dob initialize self.dob_entered = True return screen def theme_switcher(self): if self.theme_cls.theme_style == "Dark": self.theme_cls.theme_style = "Light" else: self.theme_cls.theme_style = "Dark" def tap_target_stop(self): self.skip_target_view.stop() def android_info_targerview_stop(self): self.android_target_view.stop() def help_chip(self, instance, value): help_cancel_btn_first = MDIconButton( icon='checkbox-marked-circle-outline', on_release=self.help_close_dialog_btn) self.help_dialog = MDDialog( title='Help', text= 'Little android is your assistant\nClick the android for more Info', size_hint=(0.7, 0.1), buttons=[help_cancel_btn_first]) self.help_dialog.open() def help_close_dialog_btn(self, obj): self.help_dialog.dismiss() def username_checker(self): username_check_false = True username_text_data = self.helper_string.get_screen( 'usernamescreen').ids.username_text.text # print(username_text_data) try: int(username_text_data) except: username_check_false = False if username_check_false or username_text_data.split() == []: cancel_btn_username_dialogue = MDFlatButton( text='Retry', on_release=self.close_username_dialog) self.username_dialoge = MDDialog( title='Invalid Username', text='Please Enter a valid Username', size_hint=(0.7, 0.2), buttons=[cancel_btn_username_dialogue]) self.username_dialoge.open() else: screen_usernamescreen = self.helper_string.get_screen( 'usernamescreen') screen_usernamescreen.ids.username_enter.disabled = False screen_usernamescreen.ids.username_check_extra_button.icon = 'account-check-outline' screen_usernamescreen.ids.username_check_btn.text_color = [ 1, 1, 1, 0 ] screen_usernamescreen.ids.username_check_btn.md_bg_color = [ 1, 1, 1, 0 ] screen_usernamescreen.ids.username_check_extra_button.text_color = self.theme_cls.primary_color screen_usernamescreen.ids.username_check_extra_button.pos_hint = { 'center_x': 0.5, 'center_y': 0.62 } screen_usernamescreen.ids.username_check_extra_button.user_font_size = '60sp' def close_username_dialog(self, obj): self.username_dialoge.dismiss() # DOB Picker #self.dob for Date of birth def show_date_picker(self): date_dialog = MDDatePicker( callback=self.get_date, year=1999, month=1, day=1, ) date_dialog.open() def get_date(self, date): self.dob = date dob_input_screen_selector = self.helper_string.get_screen('dobinput') #here i put the next button disbaled as False so user can enter in that window dob_input_screen_selector.ids.dob_enter.disabled = False dob_input_screen_selector.ids.account_shield.icon = 'shield-account' dob_input_screen_selector.ids.dob.text = str(self.dob) dob_input_screen_selector.ids.secure.text_color = [0, 1, 0, 0.7]
class MyApp(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) Window.bind(on_keyboard=self.events) self.manager_open = False self.file_manager = MDFileManager( exit_manager=self.exit_manager, select_path=self.select_path, preview=True, ) icons = list(md_icons.keys())[0:30] data = { 'language-python': 'Python', 'language-php': 'PHP', 'language-cpp': 'C++', } def build(self): self.theme_cls.theme_style = "Dark" # "Light" self.theme_cls.primary_palette = "Green" # "Purple", "Red" self.theme_cls.primary_hue = "A700" # "500" self.theme_cls.accent_palette = 'Lime' speed_dial = MDFloatingActionButtonSpeedDial() speed_dial.hint_animation= True speed_dial.right_pad = True speed_dial.data = self.data speed_dial.root_button_anim = True screen= Builder.load_string(kv) screen.add_widget(speed_dial) self.tap_target_view = MDTapTargetView( widget=screen.ids.button, title_text="Add Trip", description_text="Let people know where are you heading", widget_position="left_bottom", ) return screen def on_start(self): for name_tab in self.icons: self.root.ids.tabs.add_widget(Tab(text=name_tab)) def on_tab_switch( self, instance_tabs, instance_tab, instance_tab_label, tab_text ): '''Called when switching tabs. :type instance_tabs: <kivymd.uix.tab.MDTabs object>; :param instance_tab: <__main__.Tab object>; :param instance_tab_label: <kivymd.uix.tab.MDTabsLabel object>; :param tab_text: text or name icon of tab; ''' count_icon = [k for k, v in md_icons.items() if v == tab_text] instance_tab.ids.icon.icon = count_icon[0] def tap_target_start(self): if self.tap_target_view.state == "close": self.tap_target_view.start() else: self.tap_target_view.stop() def set_list(self): async def set_list(): names_icons_list = list(md_icons.keys())[self.x:self.y] for name_icon in names_icons_list: await asynckivy.sleep(0) self.screen.ids.box.add_widget( ItemForList(icon=name_icon, text=name_icon)) asynckivy.start(set_list()) def refresh_callback(self, *args): '''A method that updates the state of your application while the spinner remains on the screen.''' def refresh_callback(interval): self.screen.ids.box.clear_widgets() if self.x == 0: self.x, self.y = 15, 30 else: self.x, self.y = 0, 15 self.set_list() self.screen.ids.refresh_layout.refresh_done() self.tick = 0 Clock.schedule_once(refresh_callback, 1) def file_manager_open(self): self.file_manager.show('/') # output manager to the screen self.manager_open = True def select_path(self, path): '''It will be called when you click on the file name or the catalog selection button. :type path: str; :param path: path to the selected directory or file; ''' self.exit_manager() toast(path) def exit_manager(self, *args): '''Called when the user reaches the root of the directory tree.''' self.manager_open = False self.file_manager.close() def events(self, instance, keyboard, keycode, text, modifiers): '''Called when buttons are pressed on the mobile device.''' if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True
class WelcomeScreen(Screen): def __init__(self, **kwargs): Builder.load_file('kvs/WelcomeScreen.kv') super(WelcomeScreen, self).__init__(**kwargs) # timeout variables self.timeout_event = None self.timeout_time = 30 # Seconds # connect tap-target-view self.tap_target_view = MDTapTargetView( widget=self.ids.info, title_text="Version Information", description_text=f"Build {App.get_running_app().build_version}\n", widget_position="right_bottom" ) def on_pre_enter(self, *args): self.ids.label.text = App.get_running_app().active_user # # performed upon each screen entry # def on_enter(self, *args): # Set timer of duration @timeout_time self.timeout_event = Clock.schedule_once(self.on_timeout, self.timeout_time) # # callback function on timeout # def on_timeout(self, dt): self.on_cancel() # # when the screen is touched, we restart the timer # def on_touch_up(self, touch): self.timeout_event.cancel() self.on_enter() # # Called when the stop button is pressed # def on_cancel(self): self.manager.transition = SlideTransition(direction='right') # Switch back to the default screen to welcome a new user self.manager.current = Screens.DEFAULT_SCREEN.value # # Called when buy is pressed # def on_buy(self): self.manager.transition = SlideTransition(direction='left') self.manager.get_screen(Screens.PRODUCT_SCREEN.value).user_name = self.ids.label.text self.manager.current = Screens.PRODUCT_SCREEN.value def on_touch_move(self, touch): if touch.dx > 0: self.on_cancel() elif touch.dx < 0: self.on_buy() # # Opens the little information screen at the right bottom # def tap_target_start(self): if self.tap_target_view.state == "close": self.tap_target_view.start() else: self.tap_target_view.stop() def on_leave(self, *args): self.timeout_event.cancel() # If tap target view is open, close it if self.tap_target_view.state == "open": self.tap_target_view.stop()
class ProxySpeedTestApp(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) self.icon = f"{environ['KITCHEN_SINK_ASSETS']}icon.png" self.version = __version__ self.theme_cls.primary_palette = "LightBlue" self.dialog_change_theme = None self.toolbar = None self.scaning = Queue() self.running = Queue() self.currentSpeed = Queue() self.pbar0 = Queue() self.pbar1 = Queue() self.pbar2 = Queue() self.totalpb = Queue() configs = dbRW.getAllConfigs() mirrors = dbRW.getAllMirrors() self.selLId = configs[0][2] if self.selLId: totalScan = dbRW.getProxysInxTS(self.selLId)[0] getips = dbRW.getAllCurrentProxys(self.selLId) protocol = getips[0][4] self.scan_list = [] if self.selLId: for l in getips: if not None in l: self.scan_list.append({ "IP": l[0], "SIZE": l[1], "TIME": l[2], "SPEED": l[3], "top3c": l[6] }) self.theme_cls.theme_style = configs[0][0] miInx = configs[0][1] self.configs = { 'protocol': protocol if self.selLId else 'http', 'mirror': mirrors[miInx][0], 'timeout': int(configs[0][3]), 'fileSize': int(configs[0][4]), 'miInx': miInx, 'proxysInx': [], 'mirrors': mirrors, 'proxys': getips if self.selLId else [], 'totalScan': totalScan if self.selLId else 0 } # def on_resume(self): # self.ads.request_interstitial() def changeThemeMode(self, inst): self.theme_cls.theme_style = inst dbRW.updateThemeMode(inst) def checkUpdates(self, ava=False, d=False): # print(ava) upCURL = 'https://raw.githubusercontent.com/biplobsd/proxySpeedTestApp/master/updates.json' # from json import load # with open('updates.json', 'r') as read: # updateinfo = load(read) # toast("Checking for any updates ...") try: updateinfo = get(upCURL).json() except: updateinfo = { "version": float(self.version), "messages": "", "changelogs": "", "force": "false", "release": { "win": "", "linux": "", "android": "", "macosx": "", "unknown": "", "kivy_build": "" } } # toast("Faild app update check!") if updateinfo: try: appLink = updateinfo["release"][platform] except KeyError: return title = f"App update v{updateinfo['version']}" msg = "You are already in latest version!" b1 = "CENCEL" force = False if updateinfo['version'] > float(self.version) and appLink != "": if updateinfo['messages']: title = updateinfo['messages'] msg = "" b2 = "DOWNLOAD" force = bool(updateinfo['force']) if force: b1 = "EXIT" ava = True else: b2 = "CHECK" self.updateDialog = MDDialog( title=title, text=msg + updateinfo['changelogs'] + f"\n\n[size=15]Force update: {force}[/size]", auto_dismiss=False, buttons=[ MDFlatButton( text=b1, text_color=self.theme_cls.primary_color, on_release=lambda x: self.updateDialog.dismiss() if b1 == "CENCEL" else self.stop()), MDRaisedButton( text=b2, on_release=lambda x: open_link(appLink) if b2 == "DOWNLOAD" else self.FCU(self.updateDialog), text_color=self.theme_cls.primary_light, ), ], ) self.updateDialog.ids.title.theme_text_color = "Custom" self.updateDialog.ids.title.text_color = self.theme_cls.primary_light if ava: self.updateDialog.open() def FCU(self, inst): inst.dismiss() Clock.schedule_once(partial(self.checkUpdates, True)) def on_pause(self): return True def save_UpdateDB(self, l=[]): dbRW = MyDb() if l: dbRW.updateScanList(l) def build(self): if platform == "android": self._statusBarColor() Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/list_items.kv") Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/dialog_change_theme.kv") return Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/start_screen.kv") @run_on_ui_thread def _statusBarColor(self, color="#03A9F4"): window = activity.getWindow() window.clearFlags(WindowManager.FLAG_TRANSLUCENT_STATUS) window.addFlags(WindowManager.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.setStatusBarColor(Color.parseColor(color)) window.setNavigationBarColor(Color.parseColor(color)) def show_dialog_change_theme(self): if not self.dialog_change_theme: self.dialog_change_theme = KitchenSinkDialogChangeTheme() self.dialog_change_theme.set_list_colors_themes() self.dialog_change_theme.open() def on_start(self): """Creates a list of items with examples on start screen.""" unsort = self.scan_list # print(unsort) if unsort: sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True) # print(sort) self.show_List() self.show_List(sort) self.root.ids.Tproxys.text = f"proxys: {len(sort)}" self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}" else: self.root.ids.Tscan.text = "scan: 0" self.root.ids.Tproxys.text = "proxys: 0" self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" self.root.ids.Smirror.text = f"Mirror: {parse.urlparse(self.configs['mirror']).netloc}".upper( ) # self.root.ids.backdrop._front_layer_open=True Logger.info(f"Platform: {platform}") # if platform == 'android': # self.ads = KivMob(adMobIds.APP) # self.ads.new_banner(adMobIds.BANNER, top_pos=False) # self.ads.request_banner() # self.ads.show_banner() # self.root.ids.adsShow.size = (self.root.ids.backdrop_front_layer.width, 110) self.mirrorPic() self.protPic() self.listPic() self.tap_target_list_view = MDTapTargetView( widget=self.root.ids.Slist, title_text="Pic a lists", description_text="I will remember your list later!", widget_position="right_top", # outer_radius=dp(320), cancelable=True, outer_circle_color=self.theme_cls.primary_color[:-1], outer_circle_alpha=0.9, ) Thread(target=self.checkUpdates).start() def listPic(self): proxysInx = dbRW.getProxysInx() self.selLId = dbRW.getConfig('proxysInx')[0] Logger.debug(self.selLId) self.configs['proxysInx'] = proxysInx if proxysInx: selLIdindxDict = {} self.ListItems = [] i = 0 for Inx in proxysInx: self.ListItems.append({ "text": f'#{i} ' + agoConv(Inx[0]), "font_style": "Caption", "height": "36dp", "top_pad": "35dp", "bot_pad": "10dp" }) selLIdindxDict[Inx[0]] = i i += 1 else: self.ListItems = [{ "text": "None", "font_style": "Caption", "height": "36dp", "top_pad": "35dp", "bot_pad": "10dp" }] if proxysInx: self.selLIdindx = selLIdindxDict[self.selLId] self.root.ids.Slist.text = f"list : #{self.selLIdindx} {agoConv(self.selLId)}".upper( ) if proxysInx else "list :" self.listSel = MDDropdownMenu( caller=self.root.ids.Slist, items=self.ListItems, width_mult=4, opening_time=0.2, position='auto', max_height=0, selected_color=self.theme_cls.primary_dark_hue) self.listSel.bind(on_release=self.set_list, on_dismiss=self.manuDismiss) def manuDismiss(self, ins): ins.caller.custom_color = get_color_from_hex( colors[self.theme_cls.primary_palette]["300"]) def set_list(self, insMain, ins): import re self.selLIdindx = int(re.search(r'#(\d)\s', ins.text).group(1)) # withoutHash = re.search(r'#\d\s(.+)', ins.text).group(1) Logger.debug(self.selLIdindx) proxysInx = dbRW.getProxysInx() self.selLId = proxysInx[self.selLIdindx][0] proxys = dbRW.getAllCurrentProxys(self.selLId) protocol = proxys[0][4] dbRW.updateConfig("proxysInx", self.selLId) scan_list = proxys self.scan_list = [] if self.selLId: for l in scan_list: if not None in l: self.scan_list.append({ "IP": l[0], "SIZE": l[1], "TIME": l[2], "SPEED": l[3], "top3c": l[6] }) unsort = self.scan_list if unsort: sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True) # print(sort) self.show_List() self.show_List(sort) self.configs['proxys'] = proxys self.configs['protocol'] = protocol self.root.ids.Slist.text = f"list : {ins.text}".upper() self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" self.root.ids.Tproxys.text = f"proxys: {len(self.configs['proxys'])}" # print(getips) toast(ins.text) # print(indx) self.listSel.dismiss() insMain.caller.custom_color = get_color_from_hex( colors[self.theme_cls.primary_palette]["300"]) if self.tap_target_list_view.state == 'open': self.tap_target_list_view.stop() def protPic(self): items = [{ "text": protocol.upper(), "font_style": "Caption", "height": "36dp", "top_pad": "35dp", "bot_pad": "10dp" } for protocol in ['http', 'https', 'socks4', 'socks5']] self.protSel = MDDropdownMenu( caller=self.root.ids.Sprotocol, items=items, width_mult=3, opening_time=0.2, position='auto', selected_color=self.theme_cls.primary_dark_hue) self.protSel.bind(on_release=self.set_protocol, on_dismiss=self.manuDismiss) def set_protocol(self, insMain, ins): self.configs['protocol'] = ins.text.lower() self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" toast(self.configs['protocol']) insMain.caller.custom_color = get_color_from_hex( colors[self.theme_cls.primary_palette]["300"]) self.protSel.dismiss() def mirrorPic(self): mirrors = dbRW.getAllMirrors() self.configs['mirrors'] = mirrors items = [{ "text": parse.urlparse(mirror[0]).netloc, "font_style": "Caption", "height": "36dp", "top_pad": "35dp", "bot_pad": "10dp" } for mirror in mirrors] self.mirrSel = MDDropdownMenu( caller=self.root.ids.Smirror, items=items, opening_time=0.2, width_mult=5, position='auto', max_height=0, selected_color=self.theme_cls.primary_dark_hue) self.mirrSel.bind(on_release=self.set_mirror, on_dismiss=self.manuDismiss) def set_mirror(self, insMain, ins): miInx = 0 for l in self.configs['mirrors']: if ins.text in l[0]: break miInx += 1 self.configs['mirror'] = self.configs['mirrors'][miInx][0] self.root.ids.Smirror.text = f"Mirror: {ins.text}".upper() dbRW.updateConfig("proxysInx", self.selLId) dbRW.updateConfig("miInx", self.configs['miInx']) toast(self.configs['mirror']) insMain.caller.custom_color = get_color_from_hex( colors[self.theme_cls.primary_palette]["300"]) self.mirrSel.dismiss() def update_screen(self, dt): try: while not self.pbar0.empty(): sp = self.pbar0.get_nowait() if sp != 0: self.root.ids.progressBar1.value += sp else: self.root.ids.progressBar1.value = 0 except Empty: pass try: while not self.pbar1.empty(): sp = self.pbar1.get_nowait() if sp != 0: self.root.ids.progressBar2.value += sp else: self.root.ids.progressBar2.value = 0 except Empty: pass try: while not self.pbar2.empty(): sp = self.pbar2.get_nowait() if sp != 0: self.root.ids.progressBar3.value += sp else: self.root.ids.progressBar3.value = 0 except Empty: pass try: proxysL = len(self.configs['proxys']) while not self.totalpb.empty(): sp = self.totalpb.get_nowait() if sp != 0: self.root.ids.totalpb.value += sp comP = (self.root.ids.totalpb.value / proxysL) * 100 self.root.ids.totalpbText.text = f"{round(comP)}%" else: self.root.ids.totalpb.max = proxysL self.root.ids.totalpb.value = 0 except Empty: pass self.speedcal() self.root.ids.Slist.text = f"list : #{self.selLIdindx} {agoConv(self.selLId)}".upper( ) def start_scan(self, instance): # print("Clicked!!") if instance.text == "Start": self.mirrorPic() self.listPic() self.root.ids.Tproxys.text = f"proxys: {len(self.configs['proxys'])}" if len(self.configs['proxys']) == 0: try: if self.configs['proxysInx']: self.tap_target_list_view.start() self.listSel.open() # toast("Pick that list!") return except: pass PSTDialogInput().open() toast("First input proxys ip:port list then start scan.") return instance.text = "Stop" color = "#f44336" instance.md_bg_color = get_color_from_hex(color) self.theme_cls.primary_palette = "Red" if platform == "android": self._statusBarColor(color) self.scaning.put_nowait(1) self.running.put_nowait(1) IndexTime = datetime.now() dbRW.updateConfig('proxysInx', IndexTime) dbRW.updateProxysInx(IndexTime, self.selLId) dbRW.updateProxys(IndexTime, self.selLId) configs = dbRW.getAllConfigs() self.configs['totalScan'] = dbRW.getProxysInxTS(IndexTime)[0] self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}" # print(totalScan) self.configs['timeout'] = int(configs[0][3]) self.configs['fileSize'] = int(configs[0][4]) self.selLId = str(IndexTime) self.show_List() self.upScreen = Clock.schedule_interval(self.update_screen, 0.1) Thread(target=self.proxySpeedTest, args=( self.configs['proxys'], self.configs['protocol'], self.configs['mirror'], )).start() # self.proxySpeedTest('start') elif instance.text == "Stoping": toast(f"Waiting for finish {self.root.ids.currentIP.text[8:]}!") else: while not self.scaning.empty(): self.scaning.get_nowait() if not self.running.empty(): instance.text = "Stoping" # instance.text_color color = "#9E9E9E" self.theme_cls.primary_palette = "Gray" instance.md_bg_color = get_color_from_hex(color) if platform == "android": self._statusBarColor(color) def downloadChunk(self, idx, proxy_ip, filename, mirror, protocol): Logger.info(f'Scaning {idx} : Started') try: proxies = { 'http': f'{protocol}://{proxy_ip}', 'https': f'{protocol}://{proxy_ip}' } req = get(mirror, headers={ "Range": "bytes=%s-%s" % (0, self.configs['fileSize']), "user-agent": "Mozilla/5.0", }, stream=True, proxies=proxies, timeout=self.configs['timeout']) with (open(f'{filename}{idx}', 'ab')) as f: start = datetime.now() chunkSize = 0 # oldSpeed = 0 chunkSizeUp = 1024 for chunk in req.iter_content(chunk_size=chunkSizeUp): end = datetime.now() if 0.1 <= (end - start).seconds: delta = round( float((end - start).seconds) + float(str('0.' + str((end - start).microseconds))), 3) speed = round((chunkSize) / delta) # if oldSpeed < speed: # chunkSizeUp *= 3 # else: # chunkSizeUp = speed oldSpeed = speed start = datetime.now() self.currentSpeed.put_nowait(speed) chunkSize = 0 if chunk: chunkSize += sys.getsizeof(chunk) self.showupdate(idx) f.write(chunk) except ProxyError: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : Could not connect to {proxy_ip}") return False except connError: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : Could not connect to {proxy_ip}") return False except IndexError: self.showupdate(idx, 'd') Logger.info( f'Thread {idx} : You must provide a testing IP:PORT proxy') return False except ConnectTimeout: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : ConnectTimeou for {proxy_ip}") return False except ReadTimeout: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : ReadTimeout for {proxy_ip}") return False except RuntimeError: self.showupdate(idx, 'd') Logger.info( f"Thread {idx} : Set changed size during iteration. {proxy_ip}" ) return False except KeyboardInterrupt: self.showupdate(idx, 'd') Logger.info(f"Thread no {idx} : Exited by User.") self.showupdate(idx, 'd') def showupdate(self, idx, mode='u', error=True): if mode == 'u': if idx == 0: self.pbar0.put_nowait(1) elif idx == 1: self.pbar1.put_nowait(1) elif idx == 2: self.pbar2.put_nowait(1) elif mode == 'd': # color = "#f44336" if idx == 0: self.pbar0.put_nowait(0) elif idx == 1: self.pbar1.put_nowait(0) elif idx == 2: self.pbar2.put_nowait(0) self.root.ids.top_text.text = "0 KB/s" def proxySpeedTest(self, proxys, protocol, mirror): filename = 'chunk' unsort = list() sort = list() astTop3 = list() roundC = 0 self.totalpb.put(0) Logger.debug(proxys) for c, part in enumerate(proxys): if self.scaning.empty(): break proxy_ip = part[0].strip() self.root.ids.currentIP.text = f"CURRENT: {proxy_ip}" # Removing before test chunk file for i in range(3): if exists(f'{filename}{i}'): remove(f'{filename}{i}') # Starting chunk file downloading timeStart = datetime.now() downloaders = [ Thread( target=self.downloadChunk, args=(idx, proxy_ip, filename, mirror, protocol), ) for idx in range(3) ] for _ in downloaders: _.start() for _ in downloaders: _.join() timeEnd = datetime.now() filesize = 0 for i in range(3): try: filesize = filesize + getsize(f'{filename}{i}') except FileNotFoundError: continue filesizeM = round(filesize / pow(1024, 2), 2) delta = round( float((timeEnd - timeStart).seconds) + float(str('0.' + str((timeEnd - timeStart).microseconds))), 3) speed = round(filesize) / delta for i in range(3): if exists(f'{filename}{i}'): remove(f'{filename}{i}') unsort.append({ 'IP': proxy_ip, 'SIZE': filesizeM, 'TIME': delta, 'SPEED': int(speed), 'top3c': part[6] }) sort = self.sort_Type(unsort, showL=False) sortLL = len(sort) if sortLL >= 3: for t in range(sortLL): if t < 3: if sort[t]['SPEED'] != 0: if not sort[t]['IP'] in astTop3: sort[t]['top3c'] += 1 astTop3.append(sort[t]['IP']) else: for i in range(len(astTop3)): if sort[t]['IP'] == astTop3[i]: # print(i) astTop3.pop(i) sort[t]['top3c'] -= 1 break self.show_List(sort) self.save_UpdateDB(sort) self.totalpb.put(1) roundC = c # return True self.save_UpdateDB(sort) # print(roundC) # print(self.root.ids.totalpb.value) roundC += 1 while True: if self.root.ids.totalpb.value == roundC: self.upScreen.cancel() break self.root.ids.start_stop.text = "Start" self.theme_cls.primary_palette = "LightBlue" self.root.ids.start_stop.md_bg_color = self.theme_cls.primary_color if platform == "android": self._statusBarColor() while not self.running.empty(): self.running.get_nowait() Logger.info("Scan : Finished!") def sort_Change(self, inst, ckid): if ckid and inst.active: self.sort_Type(self.data_lists, mode=inst.text, reverse=False) inst.active = False elif ckid and inst.active == False: self.sort_Type(self.data_lists, mode=inst.text, reverse=True) inst.active = True def sort_Type(self, unsort, mode='SPEED', reverse=True, showL=True): if mode == 'SERVER': mode = 'IP' if mode == 'TOP3-%': mode = 'top3c' sort = sorted(unsort, key=lambda x: x[mode], reverse=reverse) if showL: self.show_List(sort) return sort def show_List(self, data=[]): # if not self.root.ids.backdrop_front_layer.data: # print(data) # print(len(self.root.ids.backdrop_front_layer.data)) totalP = len(self.configs['proxys']) ddict = { "viewclass": "ProxyShowList", "text": "", "text1": "", "text2": "", "text3": "", "text4": "", "on_release": lambda: toast("empty!") } if not data: self.root.ids.backdrop_front_layer.data = [] for i in range(totalP): self.root.ids.backdrop_front_layer.data.append(ddict) else: for i in range(totalP): try: _ = data[i] self.root.ids.backdrop_front_layer.data[i] = { "viewclass": "ProxyShowList", "text": data[i]['IP'], "text1": f"{round((data[i]['top3c']/self.configs['totalScan'])*100)} %", "text2": f"{data[i]['SIZE']} MB", "text3": sec_to_mins(float(data[i]['TIME'])), "text4": f"{size(data[i]['SPEED'], system=alternative)}/s", "on_release": lambda x=data[i]['IP']: self.copy_proxyip(x), } except IndexError: self.root.ids.backdrop_front_layer.data[i] = ddict self.data_lists = data def copy_proxyip(self, data): toast(f"Copied: {data}") Clipboard.copy(data) def speedcal(self): speed = 0 try: while not self.currentSpeed.empty(): speed += self.currentSpeed.get_nowait() except Empty: pass if speed != 0: self.root.ids.top_text.text = f"{size(speed, system=alternative)}/s"
class ProfileScreen(Screen): def Brow(self): window = Tk() try: os.chdir(working) shutil.move(os.path.join(os.path.expandvars("%userprofile%"), "Desktop" + "/Locker"), os.getcwd() + "/output/public/") except: pass try: os.chdir("output/public/") except: pass window.withdraw() try: dwldDirectory = askopenfilename() try: os.chdir("output/public/") os.remove("unlock.bat") os.remove("unlock.txt") except: pass print(os.getcwd()) fob = open('unlock.txt', 'w') fob.write("@ECHO OFF\n" "attrib -h -s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n' "ren "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"'" Locker\n" "echo Folder Unlocked successfully\n" "goto End\n" ":End") fob.close() os.rename("unlock.txt", "unlock.bat") os.startfile("unlock.bat") time.sleep(1) if os.path.exists("Locker"): print("remove") os.remove("unlock.bat") try: shutil.move(dwldDirectory, "Locker/locked files/") time.sleep(1) fob = open('lock.txt', 'w') fob.write("@ECHO OFF\n" "ren Locker "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n' "attrib +h +s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n' "echo Folder locked\n" "goto End\n" ":End\n") fob.close() os.rename("lock.txt", "lock.bat") os.startfile("lock.bat") time.sleep(1) os.remove("lock.bat") print("work done") try: os.remove("unlock.bat") except: pass messagebox.showinfo("SUCCESS", "file safely stored in locker") except: messagebox.showinfo("error", "unable to export file do it manually or same name file already exist in locker folder)") self.lock() window.destroy() except: showinfo("error", "please select the file or same name file already exist in locker folder)") print(os.getcwd()) self.lock() pass def unlock(self): try: os.chdir("output/public") except: pass print(os.getcwd()) fob = open('unlock.txt', 'w') fob.write("@ECHO OFF\n" "attrib -h -s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n' "ren "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"'" Locker\n" "echo Folder Unlocked successfully\n" "goto End\n" ":End") fob.close() os.rename("unlock.txt", "unlock.bat") os.startfile("unlock.bat") time.sleep(1) if os.path.exists("Locker"): print("remove") os.remove("unlock.bat") shutil.move("Locker",os.path.join(os.path.expandvars("%userprofile%"),"Desktop")) time.sleep(1) os.startfile(os.path.join(os.path.expandvars("%userprofile%"), "Desktop"+"/Locker")) def kick(self): if os.path.exists("output/public/Locker"): print("loker") self.lock() elif os.path.exists(os.path.join(os.path.expandvars("%userprofile%"), "Desktop"+"/Locker")): print("locker") self.lock() else: self.unlock() print("unlock") def lock(self): try: os.chdir("output/public") except: pass try: shutil.move(os.path.join(os.path.expandvars("%userprofile%"), "Desktop"+"/Locker"),os.getcwd()) except: pass fob = open('lock.txt', 'w') fob.write("@ECHO OFF\n" "ren Locker "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n' "attrib +h +s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n' "echo Folder locked\n" "goto End\n" ":End\n") fob.close() os.rename("lock.txt", "lock.bat") os.startfile("lock.bat") time.sleep(1) os.remove("lock.bat") print("work done") def Brow2(self): window = Tk() try: os.chdir(working) shutil.move(os.path.join(os.path.expandvars("%userprofile%"), "Desktop"+"/Locker"),os.getcwd()+"/output/public/") except: pass try: os.chdir("output/public/") except: pass window.withdraw() try: dwldDirectory = askdirectory() try: os.chdir("output/public/") os.remove("unlock.bat") os.remove("unlock.txt") except: pass print(os.getcwd()) fob = open('unlock.txt', 'w') fob.write("@ECHO OFF\n" "attrib -h -s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n' "ren "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"'" Locker\n" "echo Folder Unlocked successfully\n" "goto End\n" ":End") fob.close() os.rename("unlock.txt", "unlock.bat") os.startfile("unlock.bat") time.sleep(1) if os.path.exists("Locker"): print("remove") os.remove("unlock.bat") try: shutil.move(dwldDirectory, "Locker/locked folders/") time.sleep(1) fob = open('lock.txt', 'w') fob.write("@ECHO OFF\n" "ren Locker "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n' "attrib +h +s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n' "echo Folder locked\n" "goto End\n" ":End\n") fob.close() os.rename("lock.txt", "lock.bat") os.startfile("lock.bat") time.sleep(1) os.remove("lock.bat") print("work done") try: os.remove("unlock.bat") except: pass messagebox.showinfo("SUCCESS", "file safely stored in locker") except: messagebox.showinfo("error", "unable to export file do it manually or same name file already exist in locker folder)") self.lock() window.destroy() except: showinfo("error", "please select the file or same name file already exist in locker folder)") print(os.getcwd()) self.lock() pass def tap_target_start(self): self.tap_target_view = MDTapTargetView( widget=self.ids['button'], title_text="akria", description_text="what can i do for you sir?", widget_position="center", title_position="left_top", outer_radius=150, ) if self.tap_target_view.state == "open": self.tap_target_view.stop() else: self.tap_target_view.start()
class DemoApp(MDApp): def build(self): self.theme_cls.primary_palette = "Blue" # "BlueGray" self.theme_cls.primary_hue = "500" # "700" self.theme_cls.theme_style = "Light" screen = Builder.load_string(login_helper) self.lusername = Builder.load_string(helpers.lusername_input) self.lpassword = Builder.load_string(helpers.lpassword_input) button = MDRectangleFlatButton(text='Submit', pos_hint={ 'center_x': 0.5, 'center_y': 0.3 }, on_release=self.log_show_data) screen.add_widget(self.lusername) screen.add_widget(self.lpassword) screen.add_widget(button) sm.add_widget(screen) screen = Builder.load_string(signup_helper) self.username = Builder.load_string(helpers.username_input) self.mycontact = Builder.load_string(helpers.mycontact_input) self.email = Builder.load_string(helpers.email_input) self.password = Builder.load_string(helpers.password_input) self.age = Builder.load_string(helpers.age_input) button = MDRectangleFlatButton(text='Submit', pos_hint={ 'center_x': 0.5, 'center_y': 0.2 }, on_release=self.sign_show_data) screen.add_widget(self.username) screen.add_widget(self.mycontact) screen.add_widget(self.email) screen.add_widget(self.password) screen.add_widget(self.age) screen.add_widget(button) sm.add_widget(screen) screen = Builder.load_string(navigation_helper) sm.add_widget(screen) screen = Builder.load_string(screen_helper) self.abusername = Builder.load_string(helpers.abusername_input) self.contact = Builder.load_string(helpers.contact_input) self.reason = Builder.load_string(helpers.reason_input) button = MDRectangleFlatButton(text='Submit', pos_hint={ 'center_x': 0.5, 'center_y': 0.3 }, on_release=self.show_data) screen.add_widget(self.abusername) screen.add_widget(self.contact) screen.add_widget(self.reason) screen.add_widget(button) sm.add_widget(screen) screen = Builder.load_string(newsscraping) self.tap_target_view = MDTapTargetView( widget=screen.ids.button1, title_text="Teens having \nat least 1 social \nmedia profile", description_text=" 75% ", widget_position="center", title_position="right_top", title_text_size="20sp", outer_radius=250, ) sm.add_widget(screen) screen = Builder.load_string(conv_upload) sm.add_widget(screen) screen = Builder.load_string(screen_helper4) sm.add_widget(screen) screen = Builder.load_string(screen_helper5) sm.add_widget(screen) screen = Builder.load_string(screen_helper6) sm.add_widget(screen) return sm def __init__(self, **kwargs): super().__init__(**kwargs) Window.bind(on_keyboard=self.events) self.manager_open = False self.file_manager = MDFileManager( exit_manager=self.exit_manager, select_path=self.select_path, ext=[".txt", ".py", "kv"], ) # Sign up validation def sign_show_data(self, obj): if self.username.text != "" and self.mycontact.text != "" and self.email.text != "" and self.password.text != "": if len(self.mycontact.text) == 10 and self.mycontact.text.isdigit( ) and self.age.text.isdigit(): if re.search(regex, self.email.text): if len(self.password.text) >= 8: print("USERNAME- " + self.username.text) print("CONTACT NUMBER- " + self.mycontact.text) print("EMAIL- " + self.email.text) print("PASSWORD- " + self.password.text) print("AGE- " + self.age.text) # self.reason.text, self.contact.text, self.username.text = "" # self.username.text = "" # self.mycontact.text = "" self.email.text = "" # self.age.text = "" user_error = "" else: user_error = "Please enter a valid password" else: user_error = "Please enter a valid email id" else: user_error = "Please enter a valid contact number." else: user_error = "Please enter the required fields" if user_error == "": sm.switch_to(Builder.load_string(navigation_helper)) else: self.dialog = MDDialog(text=user_error, size_hint=(0.8, 1), buttons=[ MDFlatButton( text='Close', on_release=self.close_dialog) ]) self.dialog.open() # Report portal validation def show_data(self, obj): if self.contact.text != "" and self.reason.text != "": if len(self.contact.text) == 10 and self.contact.text.isdigit(): print("ABUSER NAME- " + self.abusername.text) print(self.username.text, self.mycontact.text) print("CONTACT NUMBER- " + self.contact.text) print("REASON- " + self.reason.text) mail.main_func(self.username.text, self.mycontact.text, self.abusername.text, self.contact.text, self.reason.text, "message") self.abusername.text = "" self.contact.text = "" self.reason.text = "" user_error = "Your response has been noted. The immediate responders will contact you soon." else: user_error = "Please enter a valid contact number." else: user_error = "Please enter the required fields" self.dialog = MDDialog( text=user_error, size_hint=(0.8, 1), buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def close_dialog(self, obj): self.dialog.dismiss() # do stuff after closing the dialog def info(self): self.dialog = MDDialog( text= 'The information entered below will be forwarded to the respective authorities.', size_hint=(0.8, 1), buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() # Login validation def log_show_data(self, obj): if self.lusername.text != "" and self.lpassword.text != "": if len(self.lpassword.text) >= 8: sm.switch_to(Builder.load_string(navigation_helper)) else: user_error = "Incorrect password. Please try again" self.dialog = MDDialog(text=user_error, size_hint=(0.8, 1), buttons=[ MDFlatButton( text='Close', on_release=self.close_dialog), ]) self.dialog.open() else: user_error = "Please enter the required details" self.dialog = MDDialog(text=user_error, size_hint=(0.8, 1), buttons=[ MDFlatButton( text='Close', on_release=self.close_dialog), ]) self.dialog.open() def close_dialog1(self, obj): self.dialog.dismiss() # do stuff after closing the dialog def tap_target_start1(self): if self.tap_target_view.state == "close": self.tap_target_view.start() else: self.tap_target_view.stop() def tap_target_start2(self): if self.tap_target_view.state == "close": self.tap_target_view.start() else: self.tap_target_view.stop() def info1(self): self.dialog = MDDialog( text= 'Sentimental Analysis displays the polarity ie. positive, negative and neutral polarity values of the whole conversation', size_hint=(0.9, 0.5), radius=[20, 7, 20, 7], buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def info2(self): self.dialog = MDDialog( text= 'Emotional Analysis displays the various emotions and their value of the whole conversation', size_hint=(0.9, 0.5), radius=[20, 7, 20, 7], buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def info3(self): self.dialog = MDDialog( text= 'Aspect Based Analysis displays the most talked category of the whole conversation', size_hint=(0.9, 0.5), radius=[20, 7, 20, 7], buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def info4(self): self.dialog = MDDialog( text= 'Analysis on emotions and tones of conversations and visualise the results in the form of graphs.', size_hint=(1, 0), radius=[20, 7, 20, 7], buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def infolda(self): self.dialog = MDDialog( text= 'Semantic analysis groups words which are used together frequently', size_hint=(0.9, 0.5), radius=[20, 7, 20, 7], buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)]) self.dialog.open() def callback(self, instance): print("Button is pressed") print('The button % s state is <%s>' % (instance, instance.state)) def file_manager_open(self): self.file_manager.show('/') # output manager to the screen self.file_manager.use_access = True self.manager_open = True # Read the conversation and prepare conv_anal screen. Also check for grooming if applicable def select_path(self, path): '''It will be called when you click on the file name or the catalog selection button. :type path: str; :param path: path to the selected directory or file; ''' self.exit_manager() global finalpath punc = '''/~$%^''' # remove '/' from the path for ele in path: if ele in punc: path1 = path.replace(ele, "") # path1 -> '/' symbol removed filepath /Users\Kripa\Desktop\exconvo.txt to Users\Kripa\Desktop\exconvo.txt tmplist = path1.split(os.sep) # splits the path and is put in the list tmplist # Users\Kripa\Desktop\exconvo.txt to ['Users','Kripa','Desktop','exconvo.txt'] finalpath = "" for wrd in tmplist: finalpath = finalpath + r"\\" + wrd finalpath = "C:" + finalpath # print(finalpath) #C:\\Users\Kripa\Desktop\exconvo.txt with open(finalpath, 'r') as in_file: stripped = (line.strip() for line in in_file) lines = (line.split(",") for line in stripped if line) with open('C:\\Users\\Kripa\\Desktop\\convo.csv', 'w', newline='') as out_file: writer = csv.writer(out_file) writer.writerow(('name', 'msg')) writer.writerows(lines) ct = 0 row_ct1 = 0 row_ct2 = 0 strname = "" # Get no.of messages for both users with open("C:\\Users\\Kripa\Desktop\\convo.csv", 'r') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: # lets tokenise if ct == 0 and row[0] != "name": strname = row[0] ct = ct + 1 if row[0] == strname: row_ct1 = row_ct1 + 1 else: row_ct2 = row_ct2 + 1 screen = Builder.load_string(conv_anal) self.tap_target_view = MDTapTargetView( widget=screen.ids.button, title_text="USER 1 USER 2", description_text=" " + str(row_ct1) + " " + str(row_ct2) + " \nMESSAGES MESSAGES", widget_position="center", title_position="right_top", title_text_size="20sp", outer_radius=250, ) sm.add_widget(screen) # GROOMING if int(self.age.text) < 18: with open("C:\\Users\\Kripa\Desktop\\convo.csv") as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') pred_name = "" p_ct = 0 for row in csv_reader: if p_ct == 0 and row[0] != "name" and row[ 0] != self.username.text: pred_name = row[0] p_ct = p_ct + 1 row[1] = row[1].lower() # convert to lowercase lemr = "" for word in row[1].split(): # Lemmatisation lem = (lemmatizer.lemmatize(word, pos="v")) lem = (lemmatizer.lemmatize(lem)) lemr = lemr + lem + " " no_punct = "" for char in lemr: # Remove punctuation if char not in punctuations: no_punct = no_punct + char data = word_tokenize(no_punct) stopWords = set(stopwords.words('english')) wordsFiltered = [] for w in data: # Remove stopwords if w not in stopWords: wordsFiltered.append(w) fp = "C:\\Users\\Kripa\\Desktop\\exconvo2.csv" with open(fp, 'a+', newline='') as out_file: writer = csv.writer(out_file, delimiter=' ') writer.writerow(wordsFiltered[:20]) # liwc def tokenize(text): for match in re.finditer(r'\w+', text, re.UNICODE): yield match.group(0) parse, category_names = liwc.load_token_parser( "C:\\Users\\Kripa\\Desktop\\bigdic.dic") cntt = array('i', [0, 0, 0, 0, 0, 0]) # Stages predator = "C:\\Users\\Kripa\\Desktop\\exconvo2.csv" with open(predator) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') ct = 0 i = 1 j = 0 for row in csv_reader: p = row.copy() p1 = listtostring(p).lower() p_token = tokenize(p1) from collections import Counter op1 = Counter(category for token in p_token for category in parse(token)) op = dict(op1) l = list(op.keys()) l.sort(reverse=True) if l: j = l[0] if j == "S1": cntt[0] = cntt[0] + 1 if j == "S2": cntt[1] = cntt[1] + 1 if j == "S3": cntt[2] = cntt[2] + 1 if j == "S4": cntt[3] = cntt[3] + 1 if j == "S5": cntt[4] = cntt[4] + 1 if j == "S6": cntt[5] = cntt[5] + 1 ''' cntt[0]=807 cntt[1]=396 cntt[2] =87 cntt[3] =79 cntt[4] =38 cntt[5] =226 ''' clf = joblib.load('svm.pkl') op = clf.predict([cntt]) if op == [1]: mail.main_func(self.username.text, self.mycontact.text, pred_name, "", "", "message1") self.dialog = MDDialog( text= "Grooming characteristics detected. Immediate responders have been informed.", size_hint=(0.8, 1), buttons=[ MDFlatButton(text='Close', on_release=self.close_dialog), ]) self.dialog.open() toast(finalpath) # return sm os.remove("C:\\Users\\Kripa\\Desktop\\exconvo2.csv") def exit_manager(self, *args): '''Called when the user reaches the root of the directory tree.''' self.manager_open = False self.file_manager.close() def events(self, instance, keyboard, keycode, text, modifiers): '''Called when buttons are pressed on the mobile device.''' if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True # Aspect analysis def aspect_fn(self): with open("C:\\Users\\Kripa\\Desktop\\convo.csv") as file: data = list(csv.reader(file)) strin = " ".join(str(x) for x in data) natural_language_understanding.set_service_url( 'https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/c70c1850-5873-495c-b449-d84d30415f06' ) natural_language_understanding.set_disable_ssl_verification(True) response = natural_language_understanding.analyze( text=strin, features=Features( categories=CategoriesOptions(limit=3), )).get_result() cat1 = response['categories'] di1 = cat1[0] di2 = cat1[1] di3 = cat1[2] str1 = di1['label'] str11 = str(di1['score']) str2 = di2['label'] str21 = str(di2['score']) str3 = di3['label'] str31 = str(di3['score']) screen = Builder.load_string(screen_helper3) screen.ids.aspectlist.add_widget( TwoLineListItem(text=str1, secondary_text=str11)) screen.ids.aspectlist.add_widget( TwoLineListItem(text=str2, secondary_text=str21)) screen.ids.aspectlist.add_widget( TwoLineListItem(text=str3, secondary_text=str31)) sm.add_widget(screen) # Sentiment and emotiona enalysis def emo_fn(self): cn = cp = cng = e1 = e2 = e3 = e4 = e5 = 0 with open("C:\\Users\\Kripa\\Desktop\\convo.csv") as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: j = 0 row = listtostring(row) response = natural_language_understanding.analyze( text=row, language='en', features=Features( sentiment=SentimentOptions(), emotion=EmotionOptions(), )).get_result() sen1 = response.get('sentiment').get('document').get('score') sen2 = response.get('sentiment').get('document').get('label') if sen1 == 0: cn += 1 elif sen1 > 0: cp += 1 else: cng += 1 op = response.get('emotion').get('document').get('emotion') # Create a list of tuples sorted by index 1 i.e. value field listofTuples = sorted(op.items(), reverse=True, key=lambda x: x[1]) ll = listofTuples[0] d = dict(listofTuples) for k, v in d.items(): d1 = k d2 = v j += 1 if j > 0: break if d1 == 'sadness': e1 += 1 elif d1 == 'joy': e2 += 1 elif d1 == 'fear': e3 += 1 elif d1 == 'disgust': e4 += 1 else: e5 += 1 s = s1 = 0 s = cn + cng + cp pp = (cp * 100) / s ngp = (cng * 100) / s np = (cn * 100) / s s1 = e1 + e2 + e3 + e4 + e5 e1p = (e1 * 100) / s1 e2p = (e2 * 100) / s1 e3p = (e3 * 100) / s1 e4p = (e4 * 100) / s1 e5p = (e5 * 100) / s1 screen = Builder.load_string(screen_helper1) neutral = "Neutral: " + str(round(np, 2)) pos = "Positive: " + str(round(pp, 2)) neg = "Negative: " + str(round(ngp, 2)) screen.ids.sentimentlist.add_widget(OneLineListItem(text=neutral, )) screen.ids.sentimentlist.add_widget(OneLineListItem(text=pos, )) screen.ids.sentimentlist.add_widget(OneLineListItem(text=neg, )) sm.add_widget(screen) screen = Builder.load_string(screen_helper2) sad = "Sad: " + str(round(e1p, 2)) joy = "Joy: " + str(round(e2p, 2)) fear = "Fear: " + str(round(e3p, 2)) disgust = "Disgust: " + str(round(e4p, 2)) angry = "Angry: " + str(round(e5p, 2)) screen.ids.emotionallist.add_widget(OneLineListItem(text=sad, )) screen.ids.emotionallist.add_widget(OneLineListItem(text=joy, )) screen.ids.emotionallist.add_widget(OneLineListItem(text=fear, )) screen.ids.emotionallist.add_widget(OneLineListItem(text=disgust, )) screen.ids.emotionallist.add_widget(OneLineListItem(text=angry, )) sm.add_widget(screen) # Semantic analysis def lda_fn(self): screen = Builder.load_string(screen_helperlda) with open("C:\\Users\\Kripa\Desktop\\convo.csv", 'r') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: # lets tokenise raw = row[1] tokens = tokenizer.tokenize(raw) # remove stopwords stopped_tokens = [i for i in tokens if not i in en_stop] tagged = nltk.pos_tag(stopped_tokens) for word, tag in tagged: w_tag = get_wordnet_pos(tag) if w_tag is None: lemmatized_tokens = [lemmatizer.lemmatize(word)] else: lemmatized_tokens = [ lemmatizer.lemmatize(word, pos=w_tag) ] texts.append(lemmatized_tokens) # create_dict id2word = corpora.Dictionary(texts) # convert to document-term matrix corpus = [id2word.doc2bow(text) for text in texts] # generate lda lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=id2word, num_topics=5, passes=20) # print(lda_model.print_topics(num_topics=5)) top_words_per_topic = [] # puting ouput to a csv file! for t in range(lda_model.num_topics): top_words_per_topic.extend([(t, ) + x for x in lda_model.show_topic(t)]) x = pd.DataFrame(top_words_per_topic, columns=['Tno', 'Word', 'P']) # .to_csv('C:\\Users\\Kripa\Desktop\\top_words.csv') y = x['Word'] name1 = [] for ele in y: name1.append(ele) screen.ids.ldalist.add_widget( ThreeLineListItem(text="Group 1", secondary_text=name1[0] + "," + name1[1] + "," + name1[2] + "," + name1[3] + "," + name1[4] + ",", tertiary_text=name1[5] + "," + name1[6] + "," + name1[7] + "," + name1[8] + "," + name1[9])) screen.ids.ldalist.add_widget( ThreeLineListItem( text="Group 2", secondary_text=name1[10] + "," + name1[11] + "," + name1[12] + "," + name1[13] + "," + name1[14] + ",", tertiary_text=name1[15] + "," + name1[16] + "," + name1[17] + "," + name1[18] + "," + name1[19])) screen.ids.ldalist.add_widget( ThreeLineListItem( text="Group 3", secondary_text=name1[20] + "," + name1[21] + "," + name1[22] + "," + name1[23] + "," + name1[24] + ",", tertiary_text=name1[25] + "," + name1[26] + "," + name1[27] + "," + name1[28] + "," + name1[29])) sm.add_widget(screen)
class MainApp(MDApp): data = { "help-circle-outline": "Help", "mapbox": "Add Trashcan", "settings": "settings" } myscreen = ObjectProperty() search_menu = None def on_start(self): try: self.root.ids.avatar_usr.source = ac_db_cur.execute( "SELECT * FROM avatar").fetchall()[0][0] self.root.ids.avatar_usr_2.source = ac_db_cur.execute( "SELECT * FROM avatar").fetchall()[0][0] self.root.ids.uad_username.text = usr_ac_cred[0][1] self.root.ids.uad_email.text = usr_ac_cred[0][0] self.root.ids.nav_username.text = usr_ac_cred[0][1] self.root.ids.nav_email.text = usr_ac_cred[0][0] #initialize gps except: pass def build(self): #Accessing settings database cur.execute("SELECT mode from settings where attribute='darkmode' ") GpsHelper().run() #App theme and UI color schemes darkmode_opt_list = cur.fetchall() darkmode_opt = darkmode_opt_list[0][0] self.theme_cls.primary_palette = "Cyan" self.theme_cls.primary_hue = "800" self.theme_cls.accent_palette = "Gray" self.theme_cls.accent_hue = "50" self.search_menu = SearchPopupMenu() self.tap_target_view = MDTapTargetView( widget=self.root.ids.button, title_text="Click here to locate you.", description_text="Make sure we are right over you", widget_position="left_bottom", ) if darkmode_opt == "on": print("dark mode on") self.theme_cls.theme_style = "Dark" self.root.ids.darkmode_switch.active = True else: print("light mode on") self.theme_cls.theme_style = "Light" self.root.ids.darkmode_switch.active = False if logged_in == True: self.root.ids.manager.current = "Home" self.root.ids.ecomap.add_marker(MapMarker(lat=60, lon=30)) myloc = MapMarker(lat=30.3433, lon=77.8839) self.root.ids.ecomap.add_marker(myloc) def repos(button): self.root.ids.ecomap.center_on(31.901303405681098, 76.5568) self.root.ids.ecomap.zoom = 18 self.tap_target_view.bind(on_close=repos) def drop_marker_db(button): pass # temp_marker = MapMarker(lat=val[0], lon=val[1]) # screen.ids.ecomap.add_marker(temp_marker) try: self.start_anim.cancel() except: pass self.start_anim = Clock.schedule_once(self.start_tp_anim, 3.5) elif logged_in == False: self.root.ids.parent_manager.current = "account_setup" def start_app(self): self.root.ids.parent_manager.current = "parent" self.root.ids.manager.current = "Home" usr_ac_cred = ac_db_cur.execute("SELECT * FROM accounts").fetchall() self.root.ids.uad_username.text = usr_ac_cred[0][1] self.root.ids.uad_email.text = usr_ac_cred[0][0] self.root.ids.nav_username.text = usr_ac_cred[0][1] self.root.ids.nav_email.text = usr_ac_cred[0][0] def start_tp_anim(self, *args): self.tap_target_start() def init_dark_mode(self, select, value): if value: self.theme_cls.theme_style = "Dark" cur.execute( "UPDATE settings SET mode='on' WHERE attribute = 'darkmode'") settings_db.commit() else: self.theme_cls.theme_style = "Light" cur.execute( "UPDATE settings SET mode='off' WHERE attribute = 'darkmode'") settings_db.commit() def tap_target_start(self): if self.tap_target_view.state == "close": self.tap_target_view.start() else: self.tap_target_view.stop() def callback(self, instance): if instance.icon == "settings": self.root.ids.manager.transition = SlideTransition() self.root.ids.manager.current = "Settings" elif instance.icon == "mapbox": self.register_trashcan() elif instance.icon == "help-circle-outline": pass def open_account(self): self.root.ids.parent_manager.current = "User_account_details" def open_home(self): self.root.ids.manager.current = "Home" def sign_up(self): username = self.root.ids.name_field.text email = self.root.ids.email_field.text password = self.root.ids.password_field.text Acc_list = ["acc", username, email, password] Acc_list = str(Acc_list) s.sendto(Acc_list.encode("utf-8"), server) response, response_addr = s.recvfrom(1024) response = response.decode("utf-8") if response == "ACCOUNT CREATED": sql_script = "INSERT INTO accounts VALUES('" + email + "', '" + username + "' , '" + password + "')" ac_db_cur.execute(sql_script) account_db.commit() self.root.ids.parent_manager.current = "profile_picture_opt" self.root.ids.uad_username.text = username self.root.ids.uad_email.text = email self.root.ids.nav_username.text = username self.root.ids.nav_email.text = email #register this account to server database #register this account credentials to localhost database def go_to_login(self): self.root.ids.parent_manager.current = "login_screen" def login(self): if self.root.ids.login_email_field == "" or self.root.ids.login_pw_field == "": print("Empty fields detected") else: cred_cont = [(self.root.ids.login_email_field.text, "", self.root.ids.login_pw_field.text), "ch_acc_cred"] s.sendto(str(cred_cont).encode("utf-8"), server) response, response_addr = s.recvfrom(1024) response = response.decode("utf-8") if response == "error_lia": pass else: response = eval(response) if response[0] == "verified": sql_scr1 = "DELETE FROM accounts" sql_scr2 = "INSERT INTO accounts VALUES('" + self.root.ids.login_email_field.text + "', '" + response[ 1] + "' , '" + self.root.ids.login_pw_field.text + "')" ac_db_cur.execute(sql_scr1) ac_db_cur.execute(sql_scr2) account_db.commit() global logged_in logged_in = True self.root.ids.parent_manager.current = "profile_picture_opt" def confirm_av(self): usr_av = None selected = None for avatar in [ self.root.ids.m1, self.root.ids.m2, self.root.ids.m3, self.root.ids.m4, self.root.ids.m5, self.root.ids.m6, self.root.ids.m7, self.root.ids.w1, self.root.ids.w2, self.root.ids.w3, self.root.ids.w4, self.root.ids.w5, self.root.ids.w6, self.root.ids.w7 ]: if avatar.size == [130, 130]: selected = True break if selected == True: ac_db_cur.execute("DELETE FROM avatar") ac_db_cur.execute("INSERT INTO avatar VALUES('" + avatar.icon + "')") account_db.commit() self.start_app() av = ac_db_cur.execute("SELECT * FROM avatar").fetchall()[0][0] self.root.ids.avatar_usr.source = av self.root.ids.avatar_usr_2.source = av else: pass def register_trashcan(self): lat = self.root.ids.blinker.lat lon = self.root.ids.blinker.lon list = ["tr_reg", [lat, lon]] s.sendto(str(list).encode("utf-8"), server) self.snackbar = Snackbar(text="Trashcan added.Will be shown soon!") self.snackbar.show()