text
stringlengths
257
194k
id
stringlengths
7
88
metadata
dict
__index_level_0__
int64
0
81
// If you want to use Phoenix channels, run `mix help phx.gen.channel` // to get started and then uncomment the line below. // import "./user_socket.js" // You can include dependencies in two ways. // // The simplest option is to put them in assets/vendor and // import them using relative paths: // // import "../vendor/some-package.js" // // Alternatively, you can `npm install some-package --prefix assets` and import // them using a path starting with the package name: // // import "some-package" // // Include phoenix_html to handle method=PUT/DELETE in forms and buttons. import "phoenix_html"; // Establish Phoenix Socket and LiveView configuration. import { Socket } from "phoenix"; import { LiveSocket } from "phoenix_live_view"; import topbar from "../vendor/topbar"; import FileSaver from "../vendor/file-saver"; import Hammer from "../vendor/hammer.js"; let Hooks = {}; function genId() { return Date.now().toString(36) + Math.random().toString(36).substr(2); } Hooks.AssignUserId = { mounted() { let userId = localStorage.getItem("userId"); if (!userId) { userId = genId(); // replace this with your user id generation logic localStorage.setItem("userId", userId); } this.pushEvent("assign-user-id", { userId: userId }); fetch(`/api/session?local_user_id=${encodeURIComponent(userId)}`, { method: "post", }); }, }; Hooks.DownloadImage = { mounted() { this.el.addEventListener("click", (e) => { const link = this.el.getAttribute("phx-value-image"); const name = this.el.getAttribute("phx-value-name"); fetch(link) .then((response) => response.blob()) .then((blob) => { FileSaver.saveAs(blob, `${name}.png`); }); }); }, }; Hooks.Tinder = { mounted() { var tinderContainer = document.querySelector(".tinder"); var allCards = document.querySelectorAll(".tinder--card"); var nope = document.getElementById("nope"); var love = document.getElementById("love"); var nopeButton = document.getElementById("nope"); var loveButton = document.getElementById("love"); const liveview = this; const addShakeAnimation = (button) => { console.log("adding shake animation to button", button); button.classList.add("animate-shake"); // Remove the class after the animation duration (500ms) setTimeout(() => { button.classList.remove("animate-shake"); }, 500); }; document.addEventListener("keydown", function (event) { const nopeButton = document.getElementById("nope"); const loveButton = document.getElementById("love"); if (event.key === "ArrowLeft") { // Simulate a left swipe nopeButton.click(); } else if (event.key === "ArrowRight") { // Simulate a right swipe loveButton.click(); } }); function initCards(card, index) { var newCards = document.querySelectorAll(".tinder--card:not(.removed)"); newCards.forEach(function (card, index) { card.style.zIndex = allCards.length - index; card.style.transform = "scale(" + (20 - index) / 20 + ") translateY(-" + 30 * index + "px)"; card.style.opacity = (10 - index) / 10; }); tinderContainer.classList.add("loaded"); } initCards(); allCards.forEach(function (el) { var hammertime = new Hammer(el); hammertime.on("pan", function (event) { el.classList.add("moving"); }); hammertime.on("pan", function (event) { if (event.deltaX === 0) return; if (event.center.x === 0 && event.center.y === 0) return; tinderContainer.classList.toggle("tinder_love", event.deltaX > 0); tinderContainer.classList.toggle("tinder_nope", event.deltaX < 0); var xMulti = event.deltaX * 0.03; var yMulti = event.deltaY / 80; var rotate = xMulti * yMulti; event.target.style.transform = "translate(" + event.deltaX + "px, " + event.deltaY + "px) rotate(" + rotate + "deg)"; }); hammertime.on("panend", (event) => { el.classList.remove("moving"); tinderContainer.classList.remove("tinder_love"); tinderContainer.classList.remove("tinder_nope"); var moveOutWidth = document.body.clientWidth; var keep = Math.abs(event.deltaX) < 80 || Math.abs(event.velocityX) < 0.5; event.target.classList.toggle("removed", !keep); if (keep) { event.target.style.transform = ""; } else { var endX = Math.max( Math.abs(event.velocityX) * moveOutWidth, moveOutWidth ); var toX = event.deltaX > 0 ? endX : -endX; var endY = Math.abs(event.velocityY) * moveOutWidth; var toY = event.deltaY > 0 ? endY : -endY; var xMulti = event.deltaX * 0.03; var yMulti = event.deltaY / 80; var rotate = xMulti * yMulti; event.target.style.transform = "translate(" + toX + "px, " + (toY + event.deltaY) + "px) rotate(" + rotate + "deg)"; initCards(); } var direction = event.deltaX > 0 ? "allow" : "disallow"; var predictionData = event.target.getAttribute("data-prediction-id"); console.log("Panned card prediction data:", predictionData); if (direction === "allow") { addShakeAnimation(loveButton); } else { addShakeAnimation(nopeButton); } liveview.pushEvent("swipe_prediction", { prediction: predictionData, action: direction, }); }); }); function createButtonListener(love) { return function (event) { var cards = document.querySelectorAll(".tinder--card:not(.removed)"); var moveOutWidth = document.body.clientWidth * 1.5; if (!cards.length) return false; var card = cards[0]; // Retrieve the prediction data from the card var predictionData = card.getAttribute("data-prediction-id"); console.log("Swiped prediction:", predictionData); // Log or handle the prediction data as needed card.classList.add("removed"); if (love) { card.style.transform = "translate(" + moveOutWidth + "px, -100px) rotate(-30deg)"; addShakeAnimation(loveButton); } else { card.style.transform = "translate(-" + moveOutWidth + "px, -100px) rotate(30deg)"; console.log("swipe left!"); addShakeAnimation(nopeButton); } initCards(); // Push the event to the LiveView with the prediction data and the action liveview.pushEvent("swipe_prediction", { prediction: predictionData, action: love ? "allow" : "disallow", }); event.preventDefault(); }; } var nopeListener = createButtonListener(false); var loveListener = createButtonListener(true); nope.addEventListener("click", nopeListener); love.addEventListener("click", loveListener); }, destroyed() { if (this.hammer) { this.hammer.destroy(); this.hammer = null; } }, }; let csrfToken = document .querySelector("meta[name='csrf-token']") .getAttribute("content"); let liveSocket = new LiveSocket("/live", Socket, { params: { _csrf_token: csrfToken }, hooks: Hooks, }); window.addEventListener("phx:copy", async (event) => { let button = event.detail.dispatcher; // Assuming you want to share the URL stored in a data attribute named 'data-url' let urlToShare = event.target.getAttribute("data-url"); // Check if the Web Share API is available if (navigator.share) { try { await navigator.share({ title: "Check out this AI sticker I made", // Optional: Title of the content to share url: urlToShare, // The URL you want to share }); console.log("Content shared successfully"); } catch (error) { console.error("Error sharing content:", error); } } else { // Fallback for browsers that do not support the Web Share API // For example, copy the URL to clipboard navigator.clipboard.writeText(urlToShare).then(() => { button.innerText = "Link copied to clipboard!"; setTimeout(() => { button.innerText = "Share"; }, 2000); }); } }); // Show progress bar on live navigation and form submits topbar.config({ barColors: { 0: "#29d" }, shadowColor: "rgba(0, 0, 0, .3)" }); window.addEventListener("phx:page-loading-start", (_info) => topbar.show(300)); window.addEventListener("phx:page-loading-stop", (_info) => topbar.hide()); // connect if there are any LiveViews on the page liveSocket.connect(); // expose liveSocket on window for web console debug logs and latency simulation: // >> liveSocket.enableDebug() // >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session // >> liveSocket.disableLatencySim() window.liveSocket = liveSocket;
App.js/0
{ "file_path": "App.js", "repo_id": "App.js", "token_count": 3669 }
0
// Copyright 2023 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. package org.citra.citra_emu.fragments import android.app.Dialog import android.content.DialogInterface import android.net.Uri import android.os.Bundle import android.view.View import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.activityViewModels import androidx.lifecycle.ViewModelProvider import com.google.android.material.dialog.MaterialAlertDialogBuilder import org.citra.citra_emu.R import org.citra.citra_emu.databinding.DialogCitraDirectoryBinding import org.citra.citra_emu.ui.main.MainActivity import org.citra.citra_emu.utils.PermissionsHandler import org.citra.citra_emu.viewmodel.HomeViewModel class CitraDirectoryDialogFragment : DialogFragment() { private lateinit var binding: DialogCitraDirectoryBinding private val homeViewModel: HomeViewModel by activityViewModels() fun interface Listener { fun onPressPositiveButton(moveData: Boolean, path: Uri) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { binding = DialogCitraDirectoryBinding.inflate(layoutInflater) val path = Uri.parse(requireArguments().getString(PATH)) binding.checkBox.isChecked = savedInstanceState?.getBoolean(MOVE_DATE_ENABLE) ?: false val oldPath = PermissionsHandler.citraDirectory if (!PermissionsHandler.hasWriteAccess(requireActivity()) || oldPath.toString() == path.toString() ) { binding.checkBox.visibility = View.GONE } binding.path.text = path.path binding.path.isSelected = true isCancelable = false return MaterialAlertDialogBuilder(requireContext()) .setView(binding.root) .setTitle(R.string.select_citra_user_folder) .setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int -> homeViewModel.directoryListener?.onPressPositiveButton( if (binding.checkBox.visibility != View.GONE) { binding.checkBox.isChecked } else { false }, path ) } .setNegativeButton(android.R.string.cancel) { _: DialogInterface?, _: Int -> if (!PermissionsHandler.hasWriteAccess(requireContext())) { (requireActivity() as MainActivity).openCitraDirectory.launch(null) } } .show() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(MOVE_DATE_ENABLE, binding.checkBox.isChecked) } companion object { const val TAG = "citra_directory_dialog_fragment" private const val MOVE_DATE_ENABLE = "IS_MODE_DATA_ENABLE" private const val PATH = "path" fun newInstance( activity: FragmentActivity, path: String, listener: Listener ): CitraDirectoryDialogFragment { val dialog = CitraDirectoryDialogFragment() ViewModelProvider(activity)[HomeViewModel::class.java].directoryListener = listener val args = Bundle() args.putString(PATH, path) dialog.arguments = args return dialog } } }
CitraDirectoryDialogFragment.kt/0
{ "file_path": "CitraDirectoryDialogFragment.kt", "repo_id": "CitraDirectoryDialogFragment.kt", "token_count": 1456 }
1
// Copyright 2023 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. package org.citra.citra_emu.fragments import android.app.Dialog import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.google.android.material.dialog.MaterialAlertDialogBuilder import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.citra.citra_emu.CitraApplication import org.citra.citra_emu.R import org.citra.citra_emu.databinding.DialogCopyDirBinding import org.citra.citra_emu.model.SetupCallback import org.citra.citra_emu.utils.CitraDirectoryHelper import org.citra.citra_emu.utils.FileUtil import org.citra.citra_emu.utils.PermissionsHandler import org.citra.citra_emu.viewmodel.HomeViewModel class CopyDirProgressDialog : DialogFragment() { private var _binding: DialogCopyDirBinding? = null private val binding get() = _binding!! private val homeViewModel: HomeViewModel by activityViewModels() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { _binding = DialogCopyDirBinding.inflate(layoutInflater) isCancelable = false return MaterialAlertDialogBuilder(requireContext()) .setView(binding.root) .setTitle(R.string.moving_data) .create() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewLifecycleOwner.lifecycleScope.apply { launch { repeatOnLifecycle(Lifecycle.State.CREATED) { homeViewModel.messageText.collectLatest { binding.messageText.text = it } } } launch { repeatOnLifecycle(Lifecycle.State.CREATED) { homeViewModel.dirProgress.collectLatest { binding.progressBar.max = homeViewModel.maxDirProgress.value binding.progressBar.progress = it } } } launch { repeatOnLifecycle(Lifecycle.State.CREATED) { homeViewModel.copyComplete.collect { if (it) { homeViewModel.setUserDir( requireActivity(), PermissionsHandler.citraDirectory.path!! ) homeViewModel.copyInProgress = false homeViewModel.setPickingUserDir(false) Toast.makeText( requireContext(), R.string.copy_complete, Toast.LENGTH_SHORT ).show() dismiss() } } } } } } override fun onDestroy() { super.onDestroy() _binding = null } companion object { const val TAG = "CopyDirProgressDialog" fun newInstance( activity: FragmentActivity, previous: Uri, path: Uri, callback: SetupCallback? = null ): CopyDirProgressDialog? { val viewModel = ViewModelProvider(activity)[HomeViewModel::class.java] if (viewModel.copyInProgress) { return null } viewModel.clearCopyInfo() viewModel.copyInProgress = true activity.lifecycleScope.launch { withContext(Dispatchers.IO) { FileUtil.copyDir( previous.toString(), path.toString(), object : FileUtil.CopyDirListener { override fun onSearchProgress(directoryName: String) { viewModel.onUpdateSearchProgress( CitraApplication.appContext.resources, directoryName ) } override fun onCopyProgress(filename: String, progress: Int, max: Int) { viewModel.onUpdateCopyProgress( CitraApplication.appContext.resources, filename, progress, max ) } override fun onComplete() { CitraDirectoryHelper.initializeCitraDirectory(path) callback?.onStepCompleted() viewModel.setCopyComplete(true) } }) } } return CopyDirProgressDialog() } } }
CopyDirProgressDialogFragment.kt/0
{ "file_path": "CopyDirProgressDialogFragment.kt", "repo_id": "CopyDirProgressDialogFragment.kt", "token_count": 2949 }
2
// Copyright 2023 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. package org.citra.citra_emu.adapters import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import org.citra.citra_emu.R import org.citra.citra_emu.databinding.CardHomeOptionBinding import org.citra.citra_emu.fragments.MessageDialogFragment import org.citra.citra_emu.model.HomeSetting import org.citra.citra_emu.viewmodel.GamesViewModel class HomeSettingAdapter( private val activity: AppCompatActivity, private val viewLifecycle: LifecycleOwner, var options: List<HomeSetting> ) : RecyclerView.Adapter<HomeSettingAdapter.HomeOptionViewHolder>(), View.OnClickListener { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeOptionViewHolder { val binding = CardHomeOptionBinding.inflate(LayoutInflater.from(parent.context), parent, false) binding.root.setOnClickListener(this) return HomeOptionViewHolder(binding) } override fun getItemCount(): Int { return options.size } override fun onBindViewHolder(holder: HomeOptionViewHolder, position: Int) { holder.bind(options[position]) } override fun onClick(view: View) { val holder = view.tag as HomeOptionViewHolder if (holder.option.isEnabled.invoke()) { holder.option.onClick.invoke() } else { MessageDialogFragment.newInstance( holder.option.disabledTitleId, holder.option.disabledMessageId ).show(activity.supportFragmentManager, MessageDialogFragment.TAG) } } inner class HomeOptionViewHolder(val binding: CardHomeOptionBinding) : RecyclerView.ViewHolder(binding.root) { lateinit var option: HomeSetting init { itemView.tag = this } fun bind(option: HomeSetting) { this.option = option binding.optionTitle.text = activity.resources.getString(option.titleId) binding.optionDescription.text = activity.resources.getString(option.descriptionId) binding.optionIcon.setImageDrawable( ResourcesCompat.getDrawable( activity.resources, option.iconId, activity.theme ) ) viewLifecycle.lifecycleScope.launch { viewLifecycle.repeatOnLifecycle(Lifecycle.State.CREATED) { option.details.collect { updateOptionDetails(it) } } } binding.optionDetail.postDelayed( { binding.optionDetail.ellipsize = TextUtils.TruncateAt.MARQUEE binding.optionDetail.isSelected = true }, 3000 ) if (option.isEnabled.invoke()) { binding.optionTitle.alpha = 1f binding.optionDescription.alpha = 1f binding.optionIcon.alpha = 1f } else { binding.optionTitle.alpha = 0.5f binding.optionDescription.alpha = 0.5f binding.optionIcon.alpha = 0.5f } } private fun updateOptionDetails(detailString: String) { if (detailString != "") { binding.optionDetail.text = detailString binding.optionDetail.visibility = View.VISIBLE } } } }
HomeSettingAdapter.kt/0
{ "file_path": "HomeSettingAdapter.kt", "repo_id": "HomeSettingAdapter.kt", "token_count": 1735 }
3
// Copyright 2023 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. package org.citra.citra_emu.applets import android.R import androidx.annotation.Keep import org.citra.citra_emu.NativeLibrary import org.citra.citra_emu.fragments.MiiSelectorDialogFragment import org.citra.citra_emu.utils.Log import org.citra.citra_emu.vr.VrActivity import java.io.Serializable import java.util.Arrays @Keep object MiiSelector { lateinit var data: MiiSelectorData val finishLock = Object() private fun ExecuteImpl(config: MiiSelectorConfig) { val emulationActivity = NativeLibrary.sEmulationActivity.get() data = MiiSelectorData(0, 0) val fragment = MiiSelectorDialogFragment.newInstance(config) fragment.show(emulationActivity!!.supportFragmentManager, "mii_selector") } private fun vrExecuteImpl(config: MiiSelectorConfig) { data = MiiSelectorData(0, 0) val list = ArrayList<String>() list.add(NativeLibrary.sEmulationActivity.get()!!.getString(org.citra.citra_emu.R.string.standard_mii)) list.addAll(listOf<String>(*config.miiNames)) val initialIndex = if (config.initiallySelectedMiiIndex < list.size) config.initiallySelectedMiiIndex as Int else 0 data.index = initialIndex data.returnCode = 0 } @JvmStatic fun Execute(config: MiiSelectorConfig): MiiSelectorData? { if (NativeLibrary.sEmulationActivity.get() is VrActivity) { vrExecuteImpl(config) } else { NativeLibrary.sEmulationActivity.get()!!.runOnUiThread { ExecuteImpl(config) } synchronized(finishLock) { try { finishLock.wait() } catch (ignored: Exception) { } } } return data } @Keep class MiiSelectorConfig : Serializable { var enableCancelButton = false var title: String? = null var initiallySelectedMiiIndex: Long = 0 // List of Miis to display lateinit var miiNames: Array<String> } class MiiSelectorData (var returnCode: Long, var index: Int) }
MiiSelector.kt/0
{ "file_path": "MiiSelector.kt", "repo_id": "MiiSelector.kt", "token_count": 920 }
4
// Copyright 2023 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. package org.citra.citra_emu.display enum class ScreenLayout(val int: Int) { // These must match what is defined in src/common/settings.h DEFAULT(0), SINGLE_SCREEN(1), LARGE_SCREEN(2), SIDE_SCREEN(3), HYBRID_SCREEN(4), MOBILE_PORTRAIT(5), MOBILE_LANDSCAPE(6); companion object { fun from(int: Int): ScreenLayout { return entries.firstOrNull { it.int == int } ?: DEFAULT } } }
ScreenLayout.kt/0
{ "file_path": "ScreenLayout.kt", "repo_id": "ScreenLayout.kt", "token_count": 241 }
5
import crypto from 'crypto' import { URL } from 'url' import { Request } from 'node-fetch' import CozeHash from './lib/V4Hash.js' const UriEncode = (str) => { return encodeURIComponent(str).replace(/[!'()*]/g, (c) => { return '%' + c.charCodeAt(0).toString(16); }); } const SimpleS3V4Sign = async (req, Credential, SignedHeadersList, SecretAccessKey) => { const HTTPMethod = req.method const url = new URL(req.url) const CanonicalURI = url.pathname const CanonicalQueryString = [...url.searchParams.keys()].sort().map(key => `${UriEncode(key)}=${UriEncode(url.searchParams.get(key))}`).join('&') // const QBody = req.body // const QBodyJSON = !QBody ? "" : JSON.stringify(await req.json()) const HashedPayload = req.headers.get('x-amz-content-sha256')?req.headers.get('x-amz-content-sha256'):req.body?CozeHash.sha256(await req.clone().text()):CozeHash.sha256('') // req.headers.set('x-amz-content-sha256', HashedPayload) const SignedHeaders = SignedHeadersList.sort().join(';') const CanonicalHeaders = [...req.headers.keys()].sort().map(key => { if (SignedHeadersList.includes(key.toLowerCase())) { return `${key.toLowerCase()}:${req.headers.get(key).trim()}` } }).filter(Boolean).join('\n') + '\n' const CanonicalRequest = `${HTTPMethod}\n${CanonicalURI}\n${CanonicalQueryString}\n${CanonicalHeaders}\n${SignedHeaders}\n${HashedPayload}` // console.log('---------------------cononical request---------------------') // console.log(CanonicalRequest) const CanonicalRequestHash = CozeHash.sha256(CanonicalRequest) // console.log('--------------------------cononical request hash---------------------') // console.log([CanonicalRequestHash].join('')) const Algorithm = "AWS4-HMAC-SHA256" const RequestDateTime = req.headers.get('x-amz-date') const CredentialScope = Credential const StringToSign = `${Algorithm}\n${RequestDateTime}\n${CredentialScope}\n${CanonicalRequestHash}` // console.log('-------------------------------string to sign---------------------') // console.log(StringToSign) // console.log('-------------------------------string to sign end---------------------') // const StringToSignHash = CozeHash.sha256(StringToSign) const kDate = CozeHash.hmac(`AWS4${SecretAccessKey}`, RequestDateTime.slice(0, 8)) // console.log('kDate', [kDate].join('')) const kRegion = CozeHash.hmac(kDate, 'ap-singapore-1') // console.log('kRegion', [kRegion].join('')) const kService = CozeHash.hmac(kRegion, 'imagex') // console.log('kService', [kService].join('')) const kSigning = CozeHash.hmac(kService, 'aws4_request') // console.log('kSigning', [kSigning].join('')) const Signature = CozeHash.hmac(kSigning, StringToSign, "hex") // console.log('--------------------------Signature---------------------') return [Signature].join('') } export default SimpleS3V4Sign
SimpleS3V4Sign.js/0
{ "file_path": "SimpleS3V4Sign.js", "repo_id": "SimpleS3V4Sign.js", "token_count": 1089 }
6
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict */ // Animation export type AnimationProgressEventTypes = 'cancel' | 'finish' | 'remove'; export interface AnimationProgressEvent extends Event { +currentTime: number; +timelineTime: number; } type AnimationProgressEventHandler = (event: AnimationProgressEvent) => mixed; type AnimationProgressEventListener = | { handleEvent: AnimationProgressEventHandler, ... } | AnimationProgressEventHandler; export interface StrictAnimationProgressEventTarget { addEventListener( type: AnimationProgressEventTypes, listener: AnimationProgressEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; } // Clipboard export interface StrictClipboardEventTarget { addEventListener( type: ClipboardEventTypes, listener: ClipboardEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; removeEventListener( type: ClipboardEventTypes, listener: ClipboardEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; } // Focus export interface StrictFocusEventTarget { addEventListener( type: FocusEventTypes, listener: FocusEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; removeEventListener( type: FocusEventTypes, listener: FocusEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; } // Input export interface StrictInputEventTarget { addEventListener( type: InputEventTypes, listener: InputEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; removeEventListener( type: InputEventTypes, listener: InputEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; } // Keyboard export interface StrictKeyboardEventTarget { addEventListener( type: KeyboardEventTypes, listener: KeyboardEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; removeEventListener( type: KeyboardEventTypes, listener: KeyboardEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; } // Pointer export interface StrictPointerEventTarget { addEventListener( type: PointerEventTypes, listener: PointerEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; removeEventListener( type: PointerEventTypes, listener: PointerEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; } // Wheel export interface StrictWheelEventTarget { addEventListener( type: WheelEventTypes, listener: WheelEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; removeEventListener( type: WheelEventTypes, listener: WheelEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; } // TEMPORARY: Mouse export interface StrictMouseEventTarget { addEventListener( type: MouseEventTypes, listener: MouseEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; removeEventListener( type: MouseEventTypes, listener: MouseEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; } // TEMPORARY: Touch export interface StrictTouchEventTarget { addEventListener( type: TouchEventTypes, listener: TouchEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; removeEventListener( type: TouchEventTypes, listener: TouchEventListener, optionsOrUseCapture?: EventListenerOptionsOrUseCapture ): void; } // TODO: Figure out the actual types needed. export interface StrictEventTarget // TODO: Uncomment after D48380371 // StrictAnimationProgressEventTarget, extends StrictClipboardEventTarget, StrictFocusEventTarget, StrictInputEventTarget, StrictKeyboardEventTarget, StrictPointerEventTarget, StrictWheelEventTarget, StrictMouseEventTarget, StrictTouchEventTarget {} // Unsupported Event Types // ======================= // - AbortProgressEventTypes // - ProgressEventTypes // - DragEventTypes // - TransitionEventTypes // - MessageEventTypes // - BeforeUnloadEventTypes // - StorageEventTypes // - string // - AnimationEventTypes // - AnimationEventTypes // - AbortProgressEventTypes // - ProgressEventTypes // - DragEventTypes // - TransitionEventTypes // - MessageEventTypes // - BeforeUnloadEventTypes // - StorageEventTypes
StrictEventTarget.js/0
{ "file_path": "StrictEventTarget.js", "repo_id": "StrictEventTarget.js", "token_count": 1350 }
7
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict */ import type { StrictReactDOMProps } from './StrictReactDOMProps'; export type StrictReactDOMTextAreaProps = {| ...StrictReactDOMProps, defaultValue?: Stringish, disabled?: boolean, maxLength?: number, minLength?: number, // $FlowFixMe onBeforeInput?: any, // $FlowFixMe onChange?: any, // $FlowFixMe onInput?: any, // $FlowFixMe onInvalid?: any, // $FlowFixMe onSelect?: any, // $FlowFixMe onSelectionChange?: any, placeholder?: Stringish, readOnly?: boolean, required?: boolean, rows?: number, value?: Stringish |};
StrictReactDOMTextAreaProps.js/0
{ "file_path": "StrictReactDOMTextAreaProps.js", "repo_id": "StrictReactDOMTextAreaProps.js", "token_count": 257 }
8
CLIPSEG_MODELS = [ "models--CIDAS--clipseg-rd64-refined", ] class WAS_Node_Suite: @staticmethod def models(): return CLIPSEG_MODELS @staticmethod def add_weights(weights_to_download, node): node_class = node.get("class_type") model_name = node.get("inputs", {}).get("model") if ( node_class == "CLIPSeg Model Loader" and model_name == "CIDAS/clipseg-rd64-refined" ): weights_to_download.extend(CLIPSEG_MODELS) @staticmethod def weights_map(base_url): return { model: { "url": f"{base_url}/clipseg/{model}.tar", "dest": "ComfyUI/models/clipseg", } for model in CLIPSEG_MODELS } @staticmethod def check_for_unsupported_nodes(node): unsupported_nodes = { "BLIP Model Loader": "BLIP version 1 not supported by Transformers", "BLIP Analyze Image": "BLIP version 1 not supported by Transformers", "CLIPTextEncode (NSP)": "Makes an HTTP request out to a Github file", "Diffusers Model Loader": "Diffusers is not going to be included as a requirement for this custom node", "Diffusers Hub Model Down-Loader": "Diffusers is not going to be included as a requirement for this custom node", "SAM Model Loader": "There are better SAM Loader modules to use. This implementation is not supported", "Text Parse Noodle Soup Prompts": "Makes an HTTP request out to a Github file", "Text Random Prompt": "Makes an HTTP request out to Lexica, which is unsupported", "True Random.org Number Generator": "Needs an API key which cannot be supplied", "Image Seamless Texture": "img2texture dependency has not been added", "Image Rembg (Remove Background)": "rembg dependency has not been added because it causes custom nodes to fail", "MiDaS Model Loader": "WAS MiDaS nodes are not currently supported", "MiDaS Mask Image": "WAS MiDaS nodes are not currently supported", "MiDaS Depth Approximation": "WAS MiDaS nodes are not currently supported", "Text File History Loader": "History is not persisted", } node_class = node.get("class_type") if node_class in unsupported_nodes: reason = unsupported_nodes[node_class] raise ValueError(f"{node_class} node is not supported: {reason}")
WAS_Node_Suite.py/0
{ "file_path": "WAS_Node_Suite.py", "repo_id": "WAS_Node_Suite.py", "token_count": 1020 }
9
import logging import traceback from typing import Callable, List from alpha_codium.settings.config_loader import get_settings async def send_inference(f: Callable): all_models = _get_all_models() all_deployments = _get_all_deployments(all_models) # try each (model, deployment_id) pair until one is successful, otherwise raise exception for i, (model, deployment_id) in enumerate(zip(all_models, all_deployments)): try: get_settings().set("openai.deployment_id", deployment_id) return await f(model) except Exception: logging.warning( f"Failed to generate prediction with {model}" f"{(' from deployment ' + deployment_id) if deployment_id else ''}: " f"{traceback.format_exc()}" ) if i == len(all_models) - 1: # If it's the last iteration raise # Re-raise the last exception def _get_all_models() -> List[str]: model = get_settings().config.model fallback_models = get_settings().config.fallback_models if not isinstance(fallback_models, list): fallback_models = [m.strip() for m in fallback_models.split(",")] all_models = [model] + fallback_models return all_models def _get_all_deployments(all_models: List[str]) -> List[str]: deployment_id = get_settings().get("openai.deployment_id", None) fallback_deployments = get_settings().get("openai.fallback_deployments", []) if not isinstance(fallback_deployments, list) and fallback_deployments: fallback_deployments = [d.strip() for d in fallback_deployments.split(",")] if fallback_deployments: all_deployments = [deployment_id] + fallback_deployments if len(all_deployments) < len(all_models): raise ValueError( f"The number of deployments ({len(all_deployments)}) " f"is less than the number of models ({len(all_models)})" ) else: all_deployments = [deployment_id] * len(all_models) return all_deployments
ai_invoker.py/0
{ "file_path": "ai_invoker.py", "repo_id": "ai_invoker.py", "token_count": 844 }
10
#!/usr/bin/env python """ Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/) See the file 'LICENSE' for copying permission """ import os from lib.core.common import singleTimeWarnMessage from lib.core.enums import DBMS from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOWEST def dependencies(): singleTimeWarnMessage("tamper script '%s' is only meant to be run against %s" % (os.path.basename(__file__).split(".")[0], DBMS.ACCESS)) def tamper(payload, **kwargs): """ Appends (Access) NULL byte character (%00) at the end of payload Requirement: * Microsoft Access Notes: * Useful to bypass weak web application firewalls when the back-end database management system is Microsoft Access - further uses are also possible Reference: http://projects.webappsec.org/w/page/13246949/Null-Byte-Injection >>> tamper('1 AND 1=1') '1 AND 1=1%00' """ return "%s%%00" % payload if payload else payload
appendnullbyte.py/0
{ "file_path": "appendnullbyte.py", "repo_id": "appendnullbyte.py", "token_count": 354 }
11
from logging import Logger from typing import Any, Dict, List, Optional, Union from poke_env.environment.abstract_battle import AbstractBattle from poke_env.environment.move import Move from poke_env.environment.pokemon import Pokemon from poke_env.environment.pokemon_type import PokemonType class Battle(AbstractBattle): def __init__( self, battle_tag: str, username: str, logger: Logger, gen: int, save_replays: Union[str, bool] = False, ): super(Battle, self).__init__(battle_tag, username, logger, save_replays, gen) # Turn choice attributes self._available_moves: List[Move] = [] self._available_switches: List[Pokemon] = [] self._can_dynamax: bool = False self._can_mega_evolve: bool = False self._can_tera: Optional[PokemonType] = None self._can_z_move: bool = False self._opponent_can_dynamax = True self._opponent_can_mega_evolve = True self._opponent_can_z_move = True self._opponent_can_tera: bool = False self._force_switch: bool = False self._maybe_trapped: bool = False self._trapped: bool = False self.battle_msg_history = "" self.pokemon_hp_log_dict = {} self.speed_list = [] def clear_all_boosts(self): if self.active_pokemon is not None: self.active_pokemon.clear_boosts() if self.opponent_active_pokemon is not None: self.opponent_active_pokemon.clear_boosts() def end_illusion(self, pokemon_name: str, details: str): if pokemon_name[:2] == self._player_role: active = self.active_pokemon else: active = self.opponent_active_pokemon if active is None: raise ValueError("Cannot end illusion without an active pokemon.") self._end_illusion_on( illusioned=active, illusionist=pokemon_name, details=details ) def parse_request(self, request: Dict[str, Any]) -> None: """ Update the object from a request. The player's pokemon are all updated, as well as available moves, switches and other related information (z move, mega evolution, forced switch...). :param request: Parsed JSON request object. :type request: dict """ if "wait" in request and request["wait"]: self._wait = True else: self._wait = False side = request["side"] self._available_moves = [] self._available_switches = [] self._can_mega_evolve = False self._can_z_move = False self._can_dynamax = False self._can_tera = None self._maybe_trapped = False self._reviving = any( [m["reviving"] for m in side.get("pokemon", []) if "reviving" in m] ) self._trapped = False self._force_switch = request.get("forceSwitch", False) if self._force_switch: self._move_on_next_request = True if request["rqid"]: self._rqid = max(self._rqid, request["rqid"]) if request.get("teamPreview", False): self._teampreview = True number_of_mons = len(request["side"]["pokemon"]) self._max_team_size = request.get("maxTeamSize", number_of_mons) else: self._teampreview = False self._update_team_from_request(request["side"]) if "active" in request: active_request = request["active"][0] if active_request.get("trapped"): self._trapped = True if self.active_pokemon is not None: self._available_moves.extend( self.active_pokemon.available_moves_from_request(active_request) ) if active_request.get("canMegaEvo", False): self._can_mega_evolve = True if active_request.get("canZMove", False): self._can_z_move = True if active_request.get("canDynamax", False): self._can_dynamax = True if active_request.get("maybeTrapped", False): self._maybe_trapped = True if active_request.get("canTerastallize", False): self._can_tera = PokemonType.from_name( active_request["canTerastallize"] ) if side["pokemon"]: self._player_role = side["pokemon"][0]["ident"][:2] if not self.trapped and not self.reviving: for pokemon in side["pokemon"]: if pokemon: pokemon = self._team[pokemon["ident"]] if not pokemon.active and not pokemon.fainted: self._available_switches.append(pokemon) if not self.trapped and self.reviving: for pokemon in side["pokemon"]: if pokemon and pokemon.get("reviving", False): pokemon = self._team[pokemon["ident"]] if not pokemon.active: self._available_switches.append(pokemon) def switch(self, pokemon_str: str, details: str, hp_status: str): identifier = pokemon_str.split(":")[0][:2] if identifier == self._player_role: if self.active_pokemon: self.active_pokemon.switch_out() else: if self.opponent_active_pokemon: self.opponent_active_pokemon.switch_out() pokemon = self.get_pokemon(pokemon_str, details=details) pokemon.switch_in(details=details) pokemon.set_hp_status(hp_status) @property def active_pokemon(self) -> Optional[Pokemon]: """ :return: The active pokemon :rtype: Optional[Pokemon] """ for pokemon in self.team.values(): if pokemon.active: return pokemon @property def all_active_pokemons(self) -> List[Optional[Pokemon]]: """ :return: A list containing all active pokemons and/or Nones. :rtype: List[Optional[Pokemon]] """ return [self.active_pokemon, self.opponent_active_pokemon] @property def available_moves(self) -> List[Move]: """ :return: The list of moves the player can use during the current move request. :rtype: List[Move] """ return self._available_moves @property def available_switches(self) -> List[Pokemon]: """ :return: The list of switches the player can do during the current move request. :rtype: List[Pokemon] """ return self._available_switches @property def can_dynamax(self) -> bool: """ :return: Whether or not the current active pokemon can dynamax :rtype: bool """ return self._can_dynamax @property def can_mega_evolve(self) -> bool: """ :return: Whether or not the current active pokemon can mega evolve. :rtype: bool """ return self._can_mega_evolve @property def can_tera(self) -> Optional[PokemonType]: """ :return: None, or the type the active pokemon can terastallize into. :rtype: PokemonType, optional """ return self._can_tera @property def can_z_move(self) -> bool: """ :return: Whether or not the current active pokemon can z-move. :rtype: bool """ return self._can_z_move @property def force_switch(self) -> bool: """ :return: A boolean indicating whether the active pokemon is forced to switch out. :rtype: Optional[bool] """ return self._force_switch @property def maybe_trapped(self) -> bool: """ :return: A boolean indicating whether the active pokemon is maybe trapped by the opponent. :rtype: bool """ return self._maybe_trapped @property def opponent_active_pokemon(self) -> Optional[Pokemon]: """ :return: The opponent active pokemon :rtype: Pokemon """ for pokemon in self.opponent_team.values(): if pokemon.active: return pokemon return None @property def opponent_can_dynamax(self) -> bool: """ :return: Whether or not opponent's current active pokemon can dynamax :rtype: bool """ return self._opponent_can_dynamax @opponent_can_dynamax.setter def opponent_can_dynamax(self, value: bool): self._opponent_can_dynamax = value @property def opponent_can_mega_evolve(self) -> bool: """ :return: Whether or not opponent's current active pokemon can mega-evolve :rtype: bool """ return self._opponent_can_mega_evolve @opponent_can_mega_evolve.setter def opponent_can_mega_evolve(self, value: bool): self._opponent_can_mega_evolve = value @property def opponent_can_tera(self) -> bool: """ :return: Whether or not opponent's current active pokemon can terastallize :rtype: bool """ return self._opponent_can_tera @property def opponent_can_z_move(self) -> bool: """ :return: Whether or not opponent's current active pokemon can z-move :rtype: bool """ return self._opponent_can_z_move @opponent_can_z_move.setter def opponent_can_z_move(self, value: bool): self._opponent_can_z_move = value @property def trapped(self) -> bool: """ :return: A boolean indicating whether the active pokemon is trapped, either by the opponent or as a side effect of one your moves. :rtype: bool """ return self._trapped @trapped.setter def trapped(self, value: bool): self._trapped = value
battle.py/0
{ "file_path": "battle.py", "repo_id": "battle.py", "token_count": 4442 }
12
import torch import torch.nn as nn import torch.nn.functional as F class REBNCONV(nn.Module): def __init__(self,in_ch=3,out_ch=3,dirate=1,stride=1): super(REBNCONV,self).__init__() self.conv_s1 = nn.Conv2d(in_ch,out_ch,3,padding=1*dirate,dilation=1*dirate,stride=stride) self.bn_s1 = nn.BatchNorm2d(out_ch) self.relu_s1 = nn.ReLU(inplace=True) def forward(self,x): hx = x xout = self.relu_s1(self.bn_s1(self.conv_s1(hx))) return xout ## upsample tensor 'src' to have the same spatial size with tensor 'tar' def _upsample_like(src,tar): src = F.interpolate(src,size=tar.shape[2:],mode='bilinear') return src ### RSU-7 ### class RSU7(nn.Module): def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512): super(RSU7,self).__init__() self.in_ch = in_ch self.mid_ch = mid_ch self.out_ch = out_ch self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) ## 1 -> 1/2 self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool4 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool5 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv6 = REBNCONV(mid_ch,mid_ch,dirate=1) self.rebnconv7 = REBNCONV(mid_ch,mid_ch,dirate=2) self.rebnconv6d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv5d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) def forward(self,x): b, c, h, w = x.shape hx = x hxin = self.rebnconvin(hx) hx1 = self.rebnconv1(hxin) hx = self.pool1(hx1) hx2 = self.rebnconv2(hx) hx = self.pool2(hx2) hx3 = self.rebnconv3(hx) hx = self.pool3(hx3) hx4 = self.rebnconv4(hx) hx = self.pool4(hx4) hx5 = self.rebnconv5(hx) hx = self.pool5(hx5) hx6 = self.rebnconv6(hx) hx7 = self.rebnconv7(hx6) hx6d = self.rebnconv6d(torch.cat((hx7,hx6),1)) hx6dup = _upsample_like(hx6d,hx5) hx5d = self.rebnconv5d(torch.cat((hx6dup,hx5),1)) hx5dup = _upsample_like(hx5d,hx4) hx4d = self.rebnconv4d(torch.cat((hx5dup,hx4),1)) hx4dup = _upsample_like(hx4d,hx3) hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) return hx1d + hxin ### RSU-6 ### class RSU6(nn.Module): def __init__(self, in_ch=3, mid_ch=12, out_ch=3): super(RSU6,self).__init__() self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool4 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=1) self.rebnconv6 = REBNCONV(mid_ch,mid_ch,dirate=2) self.rebnconv5d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) def forward(self,x): hx = x hxin = self.rebnconvin(hx) hx1 = self.rebnconv1(hxin) hx = self.pool1(hx1) hx2 = self.rebnconv2(hx) hx = self.pool2(hx2) hx3 = self.rebnconv3(hx) hx = self.pool3(hx3) hx4 = self.rebnconv4(hx) hx = self.pool4(hx4) hx5 = self.rebnconv5(hx) hx6 = self.rebnconv6(hx5) hx5d = self.rebnconv5d(torch.cat((hx6,hx5),1)) hx5dup = _upsample_like(hx5d,hx4) hx4d = self.rebnconv4d(torch.cat((hx5dup,hx4),1)) hx4dup = _upsample_like(hx4d,hx3) hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) return hx1d + hxin ### RSU-5 ### class RSU5(nn.Module): def __init__(self, in_ch=3, mid_ch=12, out_ch=3): super(RSU5,self).__init__() self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool3 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=1) self.rebnconv5 = REBNCONV(mid_ch,mid_ch,dirate=2) self.rebnconv4d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) def forward(self,x): hx = x hxin = self.rebnconvin(hx) hx1 = self.rebnconv1(hxin) hx = self.pool1(hx1) hx2 = self.rebnconv2(hx) hx = self.pool2(hx2) hx3 = self.rebnconv3(hx) hx = self.pool3(hx3) hx4 = self.rebnconv4(hx) hx5 = self.rebnconv5(hx4) hx4d = self.rebnconv4d(torch.cat((hx5,hx4),1)) hx4dup = _upsample_like(hx4d,hx3) hx3d = self.rebnconv3d(torch.cat((hx4dup,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) return hx1d + hxin ### RSU-4 ### class RSU4(nn.Module): def __init__(self, in_ch=3, mid_ch=12, out_ch=3): super(RSU4,self).__init__() self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) self.pool1 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=1) self.pool2 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=1) self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=2) self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=1) self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) def forward(self,x): hx = x hxin = self.rebnconvin(hx) hx1 = self.rebnconv1(hxin) hx = self.pool1(hx1) hx2 = self.rebnconv2(hx) hx = self.pool2(hx2) hx3 = self.rebnconv3(hx) hx4 = self.rebnconv4(hx3) hx3d = self.rebnconv3d(torch.cat((hx4,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.rebnconv2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.rebnconv1d(torch.cat((hx2dup,hx1),1)) return hx1d + hxin ### RSU-4F ### class RSU4F(nn.Module): def __init__(self, in_ch=3, mid_ch=12, out_ch=3): super(RSU4F,self).__init__() self.rebnconvin = REBNCONV(in_ch,out_ch,dirate=1) self.rebnconv1 = REBNCONV(out_ch,mid_ch,dirate=1) self.rebnconv2 = REBNCONV(mid_ch,mid_ch,dirate=2) self.rebnconv3 = REBNCONV(mid_ch,mid_ch,dirate=4) self.rebnconv4 = REBNCONV(mid_ch,mid_ch,dirate=8) self.rebnconv3d = REBNCONV(mid_ch*2,mid_ch,dirate=4) self.rebnconv2d = REBNCONV(mid_ch*2,mid_ch,dirate=2) self.rebnconv1d = REBNCONV(mid_ch*2,out_ch,dirate=1) def forward(self,x): hx = x hxin = self.rebnconvin(hx) hx1 = self.rebnconv1(hxin) hx2 = self.rebnconv2(hx1) hx3 = self.rebnconv3(hx2) hx4 = self.rebnconv4(hx3) hx3d = self.rebnconv3d(torch.cat((hx4,hx3),1)) hx2d = self.rebnconv2d(torch.cat((hx3d,hx2),1)) hx1d = self.rebnconv1d(torch.cat((hx2d,hx1),1)) return hx1d + hxin class myrebnconv(nn.Module): def __init__(self, in_ch=3, out_ch=1, kernel_size=3, stride=1, padding=1, dilation=1, groups=1): super(myrebnconv,self).__init__() self.conv = nn.Conv2d(in_ch, out_ch, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups) self.bn = nn.BatchNorm2d(out_ch) self.rl = nn.ReLU(inplace=True) def forward(self,x): return self.rl(self.bn(self.conv(x))) class BriaRMBG(nn.Module): def __init__(self,in_ch=3,out_ch=1): super(BriaRMBG,self).__init__() self.conv_in = nn.Conv2d(in_ch,64,3,stride=2,padding=1) self.pool_in = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage1 = RSU7(64,32,64) self.pool12 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage2 = RSU6(64,32,128) self.pool23 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage3 = RSU5(128,64,256) self.pool34 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage4 = RSU4(256,128,512) self.pool45 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage5 = RSU4F(512,256,512) self.pool56 = nn.MaxPool2d(2,stride=2,ceil_mode=True) self.stage6 = RSU4F(512,256,512) # decoder self.stage5d = RSU4F(1024,256,512) self.stage4d = RSU4(1024,128,256) self.stage3d = RSU5(512,64,128) self.stage2d = RSU6(256,32,64) self.stage1d = RSU7(128,16,64) self.side1 = nn.Conv2d(64,out_ch,3,padding=1) self.side2 = nn.Conv2d(64,out_ch,3,padding=1) self.side3 = nn.Conv2d(128,out_ch,3,padding=1) self.side4 = nn.Conv2d(256,out_ch,3,padding=1) self.side5 = nn.Conv2d(512,out_ch,3,padding=1) self.side6 = nn.Conv2d(512,out_ch,3,padding=1) # self.outconv = nn.Conv2d(6*out_ch,out_ch,1) def forward(self,x): hx = x hxin = self.conv_in(hx) #hx = self.pool_in(hxin) #stage 1 hx1 = self.stage1(hxin) hx = self.pool12(hx1) #stage 2 hx2 = self.stage2(hx) hx = self.pool23(hx2) #stage 3 hx3 = self.stage3(hx) hx = self.pool34(hx3) #stage 4 hx4 = self.stage4(hx) hx = self.pool45(hx4) #stage 5 hx5 = self.stage5(hx) hx = self.pool56(hx5) #stage 6 hx6 = self.stage6(hx) hx6up = _upsample_like(hx6,hx5) #-------------------- decoder -------------------- hx5d = self.stage5d(torch.cat((hx6up,hx5),1)) hx5dup = _upsample_like(hx5d,hx4) hx4d = self.stage4d(torch.cat((hx5dup,hx4),1)) hx4dup = _upsample_like(hx4d,hx3) hx3d = self.stage3d(torch.cat((hx4dup,hx3),1)) hx3dup = _upsample_like(hx3d,hx2) hx2d = self.stage2d(torch.cat((hx3dup,hx2),1)) hx2dup = _upsample_like(hx2d,hx1) hx1d = self.stage1d(torch.cat((hx2dup,hx1),1)) #side output d1 = self.side1(hx1d) d1 = _upsample_like(d1,x) d2 = self.side2(hx2d) d2 = _upsample_like(d2,x) d3 = self.side3(hx3d) d3 = _upsample_like(d3,x) d4 = self.side4(hx4d) d4 = _upsample_like(d4,x) d5 = self.side5(hx5d) d5 = _upsample_like(d5,x) d6 = self.side6(hx6) d6 = _upsample_like(d6,x) return [F.sigmoid(d1), F.sigmoid(d2), F.sigmoid(d3), F.sigmoid(d4), F.sigmoid(d5), F.sigmoid(d6)],[hx1d,hx2d,hx3d,hx4d,hx5d,hx6]
briarmbg.py/0
{ "file_path": "briarmbg.py", "repo_id": "briarmbg.py", "token_count": 7844 }
13
# -*- coding: utf-8 -*- # Celery is good for data-intensive application or some long-running tasks in other simple cases use Fastapi background # tasks # Reference https://towardsdatascience.com/deploying-ml-models-in-production-with-fastapi-and-celery-7063e539a5db from celery import Celery from app.core.config import settings celery = Celery( "async_task", broker=f"redis://{settings.REDIS_HOST}:{settings.REDIS_PORT}", backend=settings.SYNC_CELERY_DATABASE_URI, include="app.api.celery_task", # route where tasks are defined ) celery.conf.update({"beat_dburi": settings.SYNC_CELERY_BEAT_DATABASE_URI}) celery.autodiscover_tasks()
celery.py/0
{ "file_path": "celery.py", "repo_id": "celery.py", "token_count": 242 }
14
import io import os import torch import torchvision from .dist import get_rank from omegaconf import OmegaConf from torch import distributed as dist from ldm.util import instantiate_from_config from ldm.models.diffusion.plms import PLMSSampler from torch.utils.tensorboard import SummaryWriter from dataset.jsondataset import sub_batch, batch_to_device def read_official_ckpt(ckpt_path): "Read offical pretrained SD ckpt and convert into our style" state_dict = torch.load(ckpt_path, map_location="cpu")["state_dict"] out = {} out["model"] = {} out["text_encoder"] = {} out["autoencoder"] = {} out["unexpected"] = {} out["diffusion"] = {} for k,v in state_dict.items(): if k.startswith('model.diffusion_model'): out["model"][k.replace("model.diffusion_model.", "")] = v elif k.startswith('cond_stage_model'): out["text_encoder"][k.replace("cond_stage_model.", "")] = v elif k.startswith('first_stage_model'): out["autoencoder"][k.replace("first_stage_model.", "")] = v elif k in ["model_ema.decay", "model_ema.num_updates"]: out["unexpected"][k] = v else: out["diffusion"][k] = v return out def _load_checkpoint_for_ema(model_ema, checkpoint): """ Workaround for ModelEma._load_checkpoint to accept an already-loaded object """ mem_file = io.BytesIO() torch.save({'state_dict_ema':checkpoint}, mem_file) mem_file.seek(0) model_ema._load_checkpoint(mem_file) def create_expt_folder_with_auto_resuming(OUTPUT_ROOT, name): name = os.path.join( OUTPUT_ROOT, name ) writer = None checkpoint = None if os.path.exists(name): all_tags = os.listdir(name) all_existing_tags = [ tag for tag in all_tags if tag.startswith('tag') ] all_existing_tags.sort() all_existing_tags = all_existing_tags[::-1] for previous_tag in all_existing_tags: potential_ckpt = os.path.join( name, previous_tag, 'checkpoint_latest.pth' ) if os.path.exists(potential_ckpt): checkpoint = potential_ckpt if get_rank() == 0: print('auto-resuming ckpt found '+ potential_ckpt) break curr_tag = 'tag'+str(len(all_existing_tags)).zfill(2) name = os.path.join( name, curr_tag ) # output/name/tagxx else: name = os.path.join( name, 'tag00' ) # output/name/tag00 if get_rank() == 0: os.makedirs(name) os.makedirs( os.path.join(name,'Log') ) writer = SummaryWriter( os.path.join(name,'Log') ) return name, writer, checkpoint class ImageCaptionSaver: def __init__(self, base_path, nrow=8, normalize=True, scale_each=True, range=(-1,1) ): self.base_path = base_path self.nrow = nrow self.normalize = normalize self.scale_each = scale_each self.range = range def __call__(self, images, real, masked_real, captions, seen, batch=None): save_path = os.path.join(self.base_path, str(seen).zfill(8)+'.png') torchvision.utils.save_image( images, save_path, nrow=self.nrow, normalize=self.normalize, scale_each=self.scale_each, range=self.range ) save_path = os.path.join(self.base_path, str(seen).zfill(8)+'_real.png') torchvision.utils.save_image( real, save_path, nrow=self.nrow) if masked_real is not None: # only inpaiting mode case save_path = os.path.join(self.base_path, str(seen).zfill(8)+'_mased_real.png') torchvision.utils.save_image( masked_real, save_path, nrow=self.nrow, normalize=self.normalize, scale_each=self.scale_each, range=self.range) assert images.shape[0] == len(captions) save_path = os.path.join(self.base_path, 'captions.txt') with open(save_path, "a") as f: f.write( str(seen).zfill(8) + ':\n' ) for cap in captions: f.write( cap + '\n' ) f.write( '\n' ) def load_autoresume_ckpt(checkpoint, config, model, ema, opt, scheduler): starting_iter = 0 if checkpoint is not None: checkpoint = torch.load(checkpoint, map_location="cpu") missing_keys, unexpected_keys = model.load_state_dict(checkpoint["model"], strict=False) # assert unexpected_keys == [] and missing_keys == [], "missing keys in pretrained model: {}, unexpected_keys keys in pretrained model: {}".format(missing_keys, unexpected_keys) print("missing keys in pretrained model: {}".format(missing_keys)) print("unexpected keys in pretrained model: {}".format(unexpected_keys)) if config.enable_ema: ema.load_state_dict(checkpoint["ema"], strict=False) if not config.re_init_opt: opt.load_state_dict(checkpoint["opt"]) scheduler.load_state_dict(checkpoint["scheduler"]) starting_iter = checkpoint["iters"] if starting_iter >= config.total_iters: synchronize() print("Training finished. Start exiting") exit() return starting_iter @torch.no_grad() def save_ckpt(config, model, text_encoder, autoencoder, opt, scheduler, config_dict, diffusion, ema, iter_idx, name): if get_rank() == 0: model_wo_wrapper = model.module if config.distributed else model ckpt = dict(model = model_wo_wrapper.state_dict(), text_encoder = text_encoder.state_dict(), autoencoder = autoencoder.state_dict(), opt = opt.state_dict(), scheduler = scheduler.state_dict(), iters = iter_idx+1, config_dict = config_dict, ) ckpt['diffusion'] = diffusion.state_dict() if config.enable_ema: ckpt["ema"] = ema.state_dict() torch.save( ckpt, os.path.join(name, "checkpoint_latest.pth") ) @torch.no_grad() def save_ckpt_and_result(config, model, text_encoder, autoencoder, opt, scheduler, config_dict, diffusion, ema, iter_idx, loader_train, dataset_train, grounding_tokenizer_input, image_caption_saver, name, device): if get_rank() == 0: model_wo_wrapper = model.module if config.distributed else model iter_name = iter_idx + 1 # we use iter_idx + 1 as the checkpoint name if not config.disable_inference_in_training: # Do an inference on one training batch batch_here = config.batch_size batch_num = 0 # we save result for 10 iters for visualization and debugging purpose for idx, batch in enumerate(loader_train): if batch_num >= 10: break iter_name = iter_idx + 1 + idx batch = sub_batch(batch, batch_here) batch_to_device(batch, device) if "boxes" in batch: real_images_with_box_drawing = [] # we save this durining trianing for better visualization for i in range(batch_here): temp_data = {"image": batch["image"][i], "boxes":batch["boxes"][i]} im = dataset_train.decode_func.vis_getitem_data(out=temp_data, return_tensor=True, print_caption=False) real_images_with_box_drawing.append(im) real_images_with_box_drawing = torch.stack(real_images_with_box_drawing) else: # keypoint case real_images_with_box_drawing = batch["image"]*0.5 + 0.5 uc = text_encoder.encode( batch_here*[""] ) context = text_encoder.encode( batch["caption"] ) # check if self.diffusion has config attribute and prediction_type is v_prediction if hasattr(diffusion, 'config') and diffusion.config.prediction_type == "v_prediction": plms_sampler = diffusion else: plms_sampler = PLMSSampler(diffusion, model_wo_wrapper) shape = (batch_here, model_wo_wrapper.in_channels, model_wo_wrapper.image_size, model_wo_wrapper.image_size) grounding_input = grounding_tokenizer_input.prepare(batch, return_att_masks=config.use_masked_att) input = dict( x=None, timesteps=None, context=context, grounding_input=grounding_input ) samples = plms_sampler.sample(S=50, shape=shape, input=input, uc=uc, guidance_scale=5) autoencoder_wo_wrapper = autoencoder # Note itself is without wrapper since we do not train that. samples = autoencoder_wo_wrapper.decode(samples).cpu() samples = torch.clamp(samples, min=-1, max=1) masked_real_image = None image_caption_saver(samples, real_images_with_box_drawing, masked_real_image, batch["caption"], iter_name, batch) batch_num += 1 ckpt = dict(model = model_wo_wrapper.state_dict(), text_encoder = text_encoder.state_dict(), autoencoder = autoencoder.state_dict(), opt = opt.state_dict(), scheduler = scheduler.state_dict(), iters = iter_idx+1, config_dict = config_dict, ) ckpt['diffusion'] = diffusion.state_dict() if config.enable_ema: ckpt["ema"] = ema.state_dict() torch.save( ckpt, os.path.join(name, "checkpoint_"+str(iter_name).zfill(8)+".pth") ) torch.save( ckpt, os.path.join(name, "checkpoint_latest.pth") ) def synchronize(): if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.barrier() def load_model_ckpt(ckpt_path, args, device): saved_ckpt = torch.load(ckpt_path) if hasattr(args, 'test_config') and args.test_config != "": config = OmegaConf.load(args.test_config) config = vars(config)["_content"] print("config for evaluation: ", config) else: config = saved_ckpt["config_dict"]["_content"] model = instantiate_from_config(config['model']).to(device).eval() autoencoder = instantiate_from_config(config['autoencoder']).to(device).eval() text_encoder = instantiate_from_config(config['text_encoder']).to(device).eval() diffusion = instantiate_from_config(config['diffusion']).to(device) try: # load ema model if exists print("Loading ema") model.load_state_dict( saved_ckpt['ema'] ) except: print("Loading non-ema model") model.load_state_dict( saved_ckpt['model'] ) autoencoder.load_state_dict( saved_ckpt["autoencoder"] ) text_encoder.load_state_dict( saved_ckpt["text_encoder"], strict=False ) diffusion.load_state_dict( saved_ckpt["diffusion"] ) return model, autoencoder, text_encoder, diffusion, config
checkpoint.py/0
{ "file_path": "checkpoint.py", "repo_id": "checkpoint.py", "token_count": 5014 }
15
#!/usr/bin/env python3 # Script to run android build commands in a more convenient way # Note: replace `package` and `launch_activity` with your own # Author: Amanda M. Watson (amwatson) import os import subprocess as sp import sys # ================ # Global constants # ================ package = "org.citra.citra_emu" launch_activity = "org.citra.citra_emu.ui.main.MainActivity" # ======================== # Global mutable variables # ======================== has_executed_build = False # ================ # Helper functions # ================ def shell_cmd(cmd): return sp.call(cmd.split()) def adb_shell_cmd(cmd): return shell_cmd(f"adb shell {cmd}") def check_submodules(): sm_status = sp.run("git submodule status", stdout=sp.PIPE, stderr=sp.PIPE, shell=True, text=True) if sm_status.stderr.strip(): print(f"Error checking submodules: {status_error}") return status_error if any(line.startswith('-') for line in sm_status.stdout.strip().splitlines()): print("Submodule(s) not found -- updating submodules...") update_error = shell_cmd("git submodule update --init --recursive") if update_error: print(f"Error updating submodules: {update_error}") return update_error print("Submodules updated successfully.") print("All submodules are up to date.") return 0 # ================== # Available commands # ================== def start(_): return adb_shell_cmd(f"am start {package}/{launch_activity}") def stop(_): return adb_shell_cmd(f"am force-stop {package}") def install(build_config): return (check_submodules() >= 0) and shell_cmd(f"./gradlew installNightly{build_config}") def uninstall(build_config): return shell_cmd(f"./gradlew uninstallNightly{build_config}") def build(build_config): return (check_submodules() >= 0) and shell_cmd(f"./gradlew assemble{build_config}") def clean(_): return shell_cmd("./gradlew clean") # Main def main(): argv = sys.argv[1:] if len(argv) == 0: print( """Usage: build.py [debug | release] <options...> options: - build - install - uninstall - start - stop - clean Options will execute in order, e.g. cmd.py clean build install start stop uninstall""") exit(-1) build_configs = ["debug", "release"] active_build_config = "release" if (argv[0] in build_configs): active_build_config = argv[0] argv = argv[1:] for idx, arg in enumerate(argv): try: if (globals()[arg](active_build_config.capitalize()) != 0): if (arg == "install" and active_build_config == "release"): print("**Warning: this command fails if a release keystore is not specified") if (len(argv[idx+1:]) > 0): print("ERROR: The following commands were not executed: ", argv[idx+1:]) exit(-2) elif (arg == "build"): has_executed_build = True except KeyError: print("Error: unrecognized command '%s'" % arg) exit(-3) if __name__ == "__main__": main()
cmd.py/0
{ "file_path": "cmd.py", "repo_id": "cmd.py", "token_count": 1304 }
16
from .imagefunc import * class ColorImage: def __init__(self): pass @classmethod def INPUT_TYPES(self): return { "required": { "width": ("INT", {"default": 512, "min": 4, "max": 99999, "step": 1}), "height": ("INT", {"default": 512, "min": 4, "max": 99999, "step": 1}), "color": ("STRING", {"default": "#000000"},), }, "optional": { } } RETURN_TYPES = ("IMAGE", ) RETURN_NAMES = ("image", ) FUNCTION = 'color_image' CATEGORY = '😺dzNodes/LayerUtility' OUTPUT_NODE = True def color_image(self, width, height, color, ): ret_image = Image.new('RGB', (width, height), color=color) return (pil2tensor(ret_image), ) NODE_CLASS_MAPPINGS = { "LayerUtility: ColorImage": ColorImage } NODE_DISPLAY_NAME_MAPPINGS = { "LayerUtility: ColorImage": "LayerUtility: ColorImage" }
color_image.py/0
{ "file_path": "color_image.py", "repo_id": "color_image.py", "token_count": 454 }
17
# -*- coding: utf-8 -*- from caseconverter import camelcase from pydantic import BaseModel class QueryBase(BaseModel): """Query base schema.""" class Config: populate_by_name = True @staticmethod def alias_generator( s: str, ) -> str: return camelcase(s)
common_schema.py/0
{ "file_path": "common_schema.py", "repo_id": "common_schema.py", "token_count": 143 }
18
#!/usr/bin/env python """ Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/) See the file 'LICENSE' for copying permission """ import binascii import inspect import logging import os import random import re import socket import string import struct import sys import time import traceback try: import websocket from websocket import WebSocketException except ImportError: class WebSocketException(Exception): pass from lib.core.agent import agent from lib.core.common import asciifyUrl from lib.core.common import calculateDeltaSeconds from lib.core.common import checkFile from lib.core.common import checkSameHost from lib.core.common import chunkSplitPostData from lib.core.common import clearConsoleLine from lib.core.common import dataToStdout from lib.core.common import escapeJsonValue from lib.core.common import evaluateCode from lib.core.common import extractRegexResult from lib.core.common import filterNone from lib.core.common import findMultipartPostBoundary from lib.core.common import getCurrentThreadData from lib.core.common import getHeader from lib.core.common import getHostHeader from lib.core.common import getRequestHeader from lib.core.common import getSafeExString from lib.core.common import logHTTPTraffic from lib.core.common import openFile from lib.core.common import popValue from lib.core.common import parseJson from lib.core.common import pushValue from lib.core.common import randomizeParameterValue from lib.core.common import randomInt from lib.core.common import randomStr from lib.core.common import readInput from lib.core.common import removeReflectiveValues from lib.core.common import safeVariableNaming from lib.core.common import singleTimeLogMessage from lib.core.common import singleTimeWarnMessage from lib.core.common import stdev from lib.core.common import unArrayizeValue from lib.core.common import unsafeVariableNaming from lib.core.common import urldecode from lib.core.common import urlencode from lib.core.common import wasLastResponseDelayed from lib.core.compat import patchHeaders from lib.core.compat import xrange from lib.core.convert import encodeBase64 from lib.core.convert import getBytes from lib.core.convert import getText from lib.core.convert import getUnicode from lib.core.data import cmdLineOptions from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.datatype import AttribDict from lib.core.decorators import stackedmethod from lib.core.dicts import POST_HINT_CONTENT_TYPES from lib.core.enums import ADJUST_TIME_DELAY from lib.core.enums import AUTH_TYPE from lib.core.enums import CUSTOM_LOGGING from lib.core.enums import HINT from lib.core.enums import HTTP_HEADER from lib.core.enums import HTTPMETHOD from lib.core.enums import NULLCONNECTION from lib.core.enums import PAYLOAD from lib.core.enums import PLACE from lib.core.enums import POST_HINT from lib.core.enums import REDIRECTION from lib.core.enums import WEB_PLATFORM from lib.core.exception import SqlmapCompressionException from lib.core.exception import SqlmapConnectionException from lib.core.exception import SqlmapGenericException from lib.core.exception import SqlmapSkipTargetException from lib.core.exception import SqlmapSyntaxException from lib.core.exception import SqlmapTokenException from lib.core.exception import SqlmapValueException from lib.core.settings import ASTERISK_MARKER from lib.core.settings import BOUNDARY_BACKSLASH_MARKER from lib.core.settings import DEFAULT_CONTENT_TYPE from lib.core.settings import DEFAULT_COOKIE_DELIMITER from lib.core.settings import DEFAULT_GET_POST_DELIMITER from lib.core.settings import DEFAULT_USER_AGENT from lib.core.settings import EVALCODE_ENCODED_PREFIX from lib.core.settings import HTTP_ACCEPT_ENCODING_HEADER_VALUE from lib.core.settings import HTTP_ACCEPT_HEADER_VALUE from lib.core.settings import IPS_WAF_CHECK_PAYLOAD from lib.core.settings import IS_WIN from lib.core.settings import JAVASCRIPT_HREF_REGEX from lib.core.settings import LARGE_READ_TRIM_MARKER from lib.core.settings import LIVE_COOKIES_TIMEOUT from lib.core.settings import MAX_CONNECTION_READ_SIZE from lib.core.settings import MAX_CONNECTIONS_REGEX from lib.core.settings import MAX_CONNECTION_TOTAL_SIZE from lib.core.settings import MAX_CONSECUTIVE_CONNECTION_ERRORS from lib.core.settings import MAX_MURPHY_SLEEP_TIME from lib.core.settings import META_REFRESH_REGEX from lib.core.settings import MAX_TIME_RESPONSES from lib.core.settings import MIN_TIME_RESPONSES from lib.core.settings import PAYLOAD_DELIMITER from lib.core.settings import PERMISSION_DENIED_REGEX from lib.core.settings import PLAIN_TEXT_CONTENT_TYPE from lib.core.settings import RANDOM_INTEGER_MARKER from lib.core.settings import RANDOM_STRING_MARKER from lib.core.settings import REPLACEMENT_MARKER from lib.core.settings import SAFE_HEX_MARKER from lib.core.settings import TEXT_CONTENT_TYPE_REGEX from lib.core.settings import UNENCODED_ORIGINAL_VALUE from lib.core.settings import UNICODE_ENCODING from lib.core.settings import URI_HTTP_HEADER from lib.core.settings import WARN_TIME_STDEV from lib.core.settings import WEBSOCKET_INITIAL_TIMEOUT from lib.core.settings import YUGE_FACTOR from lib.request.basic import decodePage from lib.request.basic import forgeHeaders from lib.request.basic import processResponse from lib.request.comparison import comparison from lib.request.direct import direct from lib.request.methodrequest import MethodRequest from lib.utils.safe2bin import safecharencode from thirdparty import six from thirdparty.odict import OrderedDict from thirdparty.six import unichr as _unichr from thirdparty.six.moves import http_client as _http_client from thirdparty.six.moves import urllib as _urllib from thirdparty.socks.socks import ProxyError class Connect(object): """ This class defines methods used to perform HTTP requests """ @staticmethod def _getPageProxy(**kwargs): try: if (len(inspect.stack()) > sys.getrecursionlimit() // 2): # Note: https://github.com/sqlmapproject/sqlmap/issues/4525 warnMsg = "unable to connect to the target URL" raise SqlmapConnectionException(warnMsg) except (TypeError, UnicodeError): pass try: return Connect.getPage(**kwargs) except RuntimeError: return None, None, None @staticmethod def _retryProxy(**kwargs): threadData = getCurrentThreadData() threadData.retriesCount += 1 if conf.proxyList and threadData.retriesCount >= conf.retries and not kb.locks.handlers.locked(): warnMsg = "changing proxy" logger.warning(warnMsg) conf.proxy = None threadData.retriesCount = 0 setHTTPHandlers() if kb.testMode and kb.previousMethod == PAYLOAD.METHOD.TIME: # timed based payloads can cause web server unresponsiveness # if the injectable piece of code is some kind of JOIN-like query warnMsg = "most likely web server instance hasn't recovered yet " warnMsg += "from previous timed based payload. If the problem " warnMsg += "persists please wait for a few minutes and rerun " warnMsg += "without flag 'T' in option '--technique' " warnMsg += "(e.g. '--flush-session --technique=BEUS') or try to " warnMsg += "lower the value of option '--time-sec' (e.g. '--time-sec=2')" singleTimeWarnMessage(warnMsg) elif kb.originalPage is None: if conf.tor: warnMsg = "please make sure that you have " warnMsg += "Tor installed and running so " warnMsg += "you could successfully use " warnMsg += "switch '--tor' " if IS_WIN: warnMsg += "(e.g. 'https://www.torproject.org/download/')" else: warnMsg += "(e.g. 'https://help.ubuntu.com/community/Tor')" else: warnMsg = "if the problem persists please check that the provided " warnMsg += "target URL is reachable" items = [] if not conf.randomAgent: items.append("switch '--random-agent'") if not any((conf.proxy, conf.proxyFile, conf.tor)): items.append("proxy switches ('--proxy', '--proxy-file'...)") if items: warnMsg += ". In case that it is, " warnMsg += "you can try to rerun with " warnMsg += " and/or ".join(items) singleTimeWarnMessage(warnMsg) elif conf.threads > 1: warnMsg = "if the problem persists please try to lower " warnMsg += "the number of used threads (option '--threads')" singleTimeWarnMessage(warnMsg) kwargs['retrying'] = True return Connect._getPageProxy(**kwargs) @staticmethod def _connReadProxy(conn): retVal = b"" if not kb.dnsMode and conn: headers = conn.info() if kb.pageCompress and headers and hasattr(headers, "getheader") and (headers.getheader(HTTP_HEADER.CONTENT_ENCODING, "").lower() in ("gzip", "deflate") or "text" not in headers.getheader(HTTP_HEADER.CONTENT_TYPE, "").lower()): retVal = conn.read(MAX_CONNECTION_TOTAL_SIZE) if len(retVal) == MAX_CONNECTION_TOTAL_SIZE: warnMsg = "large compressed response detected. Disabling compression" singleTimeWarnMessage(warnMsg) kb.pageCompress = False raise SqlmapCompressionException else: while True: if not conn: break else: try: part = conn.read(MAX_CONNECTION_READ_SIZE) except AssertionError: part = b"" if len(part) == MAX_CONNECTION_READ_SIZE: warnMsg = "large response detected. This could take a while" singleTimeWarnMessage(warnMsg) part = re.sub(getBytes(r"(?si)%s.+?%s" % (kb.chars.stop, kb.chars.start)), getBytes("%s%s%s" % (kb.chars.stop, LARGE_READ_TRIM_MARKER, kb.chars.start)), part) retVal += part else: retVal += part break if len(retVal) > MAX_CONNECTION_TOTAL_SIZE: warnMsg = "too large response detected. Automatically trimming it" singleTimeWarnMessage(warnMsg) break if conf.yuge: retVal = YUGE_FACTOR * retVal return retVal @staticmethod def getPage(**kwargs): """ This method connects to the target URL or proxy and returns the target URL page content """ if conf.offline: return None, None, None url = kwargs.get("url", None) or conf.url get = kwargs.get("get", None) post = kwargs.get("post", None) method = kwargs.get("method", None) cookie = kwargs.get("cookie", None) ua = kwargs.get("ua", None) or conf.agent referer = kwargs.get("referer", None) or conf.referer host = kwargs.get("host", None) or conf.host direct_ = kwargs.get("direct", False) multipart = kwargs.get("multipart", None) silent = kwargs.get("silent", False) raise404 = kwargs.get("raise404", True) timeout = kwargs.get("timeout", None) or conf.timeout auxHeaders = kwargs.get("auxHeaders", None) response = kwargs.get("response", False) ignoreTimeout = kwargs.get("ignoreTimeout", False) or kb.ignoreTimeout or conf.ignoreTimeouts refreshing = kwargs.get("refreshing", False) retrying = kwargs.get("retrying", False) crawling = kwargs.get("crawling", False) checking = kwargs.get("checking", False) skipRead = kwargs.get("skipRead", False) finalCode = kwargs.get("finalCode", False) chunked = kwargs.get("chunked", False) or conf.chunked start = time.time() if isinstance(conf.delay, (int, float)) and conf.delay > 0: time.sleep(conf.delay) threadData = getCurrentThreadData() with kb.locks.request: kb.requestCounter += 1 threadData.lastRequestUID = kb.requestCounter if conf.proxyFreq: if kb.requestCounter % conf.proxyFreq == 0: conf.proxy = None warnMsg = "changing proxy" logger.warning(warnMsg) setHTTPHandlers() if conf.dummy or conf.murphyRate and randomInt() % conf.murphyRate == 0: if conf.murphyRate: time.sleep(randomInt() % (MAX_MURPHY_SLEEP_TIME + 1)) page, headers, code = randomStr(int(randomInt()), alphabet=[_unichr(_) for _ in xrange(256)]), None, None if not conf.murphyRate else randomInt(3) threadData.lastPage = page threadData.lastCode = code return page, headers, code if conf.liveCookies: with kb.locks.liveCookies: if not checkFile(conf.liveCookies, raiseOnError=False) or os.path.getsize(conf.liveCookies) == 0: warnMsg = "[%s] [WARNING] live cookies file '%s' is empty or non-existent. Waiting for timeout (%d seconds)" % (time.strftime("%X"), conf.liveCookies, LIVE_COOKIES_TIMEOUT) dataToStdout(warnMsg) valid = False for _ in xrange(LIVE_COOKIES_TIMEOUT): if checkFile(conf.liveCookies, raiseOnError=False) and os.path.getsize(conf.liveCookies) > 0: valid = True break else: dataToStdout('.') time.sleep(1) dataToStdout("\n") if not valid: errMsg = "problem occurred while loading cookies from file '%s'" % conf.liveCookies raise SqlmapValueException(errMsg) cookie = openFile(conf.liveCookies).read().strip() cookie = re.sub(r"(?i)\ACookie:\s*", "", cookie) if multipart: post = multipart else: if not post: chunked = False elif chunked: post = _urllib.parse.unquote(post) post = chunkSplitPostData(post) webSocket = url.lower().startswith("ws") if not _urllib.parse.urlsplit(url).netloc: url = _urllib.parse.urljoin(conf.url, url) # flag to know if we are dealing with the same target host target = checkSameHost(url, conf.url) if not retrying: # Reset the number of connection retries threadData.retriesCount = 0 # fix for known issue when urllib2 just skips the other part of provided # url splitted with space char while urlencoding it in the later phase url = url.replace(" ", "%20") if "://" not in url: url = "http://%s" % url conn = None page = None code = None status = None _ = _urllib.parse.urlsplit(url) requestMsg = u"HTTP request [#%d]:\r\n%s " % (threadData.lastRequestUID, method or (HTTPMETHOD.POST if post is not None else HTTPMETHOD.GET)) requestMsg += getUnicode(("%s%s" % (_.path or "/", ("?%s" % _.query) if _.query else "")) if not any((refreshing, crawling, checking)) else url) responseMsg = u"HTTP response " requestHeaders = u"" responseHeaders = None logHeaders = u"" skipLogTraffic = False raise404 = raise404 and not kb.ignoreNotFound # support for non-latin (e.g. cyrillic) URLs as urllib/urllib2 doesn't # support those by default url = asciifyUrl(url) try: socket.setdefaulttimeout(timeout) if direct_: if '?' in url: url, params = url.split('?', 1) params = urlencode(params) url = "%s?%s" % (url, params) elif any((refreshing, crawling, checking)): pass elif target: if conf.forceSSL: url = re.sub(r"(?i)\A(http|ws):", r"\g<1>s:", url) url = re.sub(r"(?i):80/", ":443/", url) if PLACE.GET in conf.parameters and not get: get = conf.parameters[PLACE.GET] if not conf.skipUrlEncode: get = urlencode(get, limit=True) if get: if '?' in url: url = "%s%s%s" % (url, DEFAULT_GET_POST_DELIMITER, get) requestMsg += "%s%s" % (DEFAULT_GET_POST_DELIMITER, get) else: url = "%s?%s" % (url, get) requestMsg += "?%s" % get if PLACE.POST in conf.parameters and not post and method != HTTPMETHOD.GET: post = conf.parameters[PLACE.POST] elif get: url = "%s?%s" % (url, get) requestMsg += "?%s" % get requestMsg += " %s" % _http_client.HTTPConnection._http_vsn_str # Prepare HTTP headers headers = forgeHeaders({HTTP_HEADER.COOKIE: cookie, HTTP_HEADER.USER_AGENT: ua, HTTP_HEADER.REFERER: referer, HTTP_HEADER.HOST: getHeader(dict(conf.httpHeaders), HTTP_HEADER.HOST) or getHostHeader(url)}, base=None if target else {}) if HTTP_HEADER.COOKIE in headers: cookie = headers[HTTP_HEADER.COOKIE] if kb.authHeader: headers[HTTP_HEADER.AUTHORIZATION] = kb.authHeader if kb.proxyAuthHeader: headers[HTTP_HEADER.PROXY_AUTHORIZATION] = kb.proxyAuthHeader if not conf.requestFile or not target: if not getHeader(headers, HTTP_HEADER.ACCEPT): headers[HTTP_HEADER.ACCEPT] = HTTP_ACCEPT_HEADER_VALUE if not getHeader(headers, HTTP_HEADER.ACCEPT_ENCODING): headers[HTTP_HEADER.ACCEPT_ENCODING] = HTTP_ACCEPT_ENCODING_HEADER_VALUE if kb.pageCompress else "identity" elif conf.requestFile and getHeader(headers, HTTP_HEADER.USER_AGENT) == DEFAULT_USER_AGENT: for header in headers: if header.upper() == HTTP_HEADER.USER_AGENT.upper(): del headers[header] break if post is not None and not multipart and not getHeader(headers, HTTP_HEADER.CONTENT_TYPE): headers[HTTP_HEADER.CONTENT_TYPE] = POST_HINT_CONTENT_TYPES.get(kb.postHint, DEFAULT_CONTENT_TYPE if unArrayizeValue(conf.base64Parameter) != HTTPMETHOD.POST else PLAIN_TEXT_CONTENT_TYPE) if headers.get(HTTP_HEADER.CONTENT_TYPE) == POST_HINT_CONTENT_TYPES[POST_HINT.MULTIPART]: warnMsg = "missing 'boundary parameter' in '%s' header. " % HTTP_HEADER.CONTENT_TYPE warnMsg += "Will try to reconstruct" singleTimeWarnMessage(warnMsg) boundary = findMultipartPostBoundary(conf.data) if boundary: headers[HTTP_HEADER.CONTENT_TYPE] = "%s; boundary=%s" % (headers[HTTP_HEADER.CONTENT_TYPE], boundary) if conf.keepAlive: headers[HTTP_HEADER.CONNECTION] = "keep-alive" if chunked: headers[HTTP_HEADER.TRANSFER_ENCODING] = "chunked" if auxHeaders: headers = forgeHeaders(auxHeaders, headers) if kb.headersFile: content = openFile(kb.headersFile, "rb").read() for line in content.split("\n"): line = getText(line.strip()) if ':' in line: header, value = line.split(':', 1) headers[header] = value if conf.localhost: headers[HTTP_HEADER.HOST] = "localhost" for key, value in list(headers.items()): if key.upper() == HTTP_HEADER.ACCEPT_ENCODING.upper(): value = re.sub(r"(?i)(,)br(,)?", lambda match: ',' if match.group(1) and match.group(2) else "", value) or "identity" del headers[key] if isinstance(value, six.string_types): for char in (r"\r", r"\n"): value = re.sub(r"(%s)([^ \t])" % char, r"\g<1>\t\g<2>", value) headers[getBytes(key) if six.PY2 else key] = getBytes(value.strip("\r\n")) # Note: Python3 has_header() expects non-bytes value if six.PY2: url = getBytes(url) # Note: Python3 requires text while Python2 has problems when mixing text with binary POST if webSocket: ws = websocket.WebSocket() ws.settimeout(WEBSOCKET_INITIAL_TIMEOUT if kb.webSocketRecvCount is None else timeout) ws.connect(url, header=("%s: %s" % _ for _ in headers.items() if _[0] not in ("Host",)), cookie=cookie) # WebSocket will add Host field of headers automatically ws.send(urldecode(post or "")) _page = [] if kb.webSocketRecvCount is None: while True: try: _page.append(ws.recv()) except websocket.WebSocketTimeoutException: kb.webSocketRecvCount = len(_page) break else: for i in xrange(max(1, kb.webSocketRecvCount)): _page.append(ws.recv()) page = "\n".join(_page) ws.close() code = ws.status status = _http_client.responses[code] class _(dict): pass responseHeaders = _(ws.getheaders()) responseHeaders.headers = ["%s: %s\r\n" % (_[0].capitalize(), _[1]) for _ in responseHeaders.items()] requestHeaders += "\r\n".join(["%s: %s" % (u"-".join(_.capitalize() for _ in getUnicode(key).split(u'-')) if hasattr(key, "capitalize") else getUnicode(key), getUnicode(value)) for (key, value) in responseHeaders.items()]) requestMsg += "\r\n%s" % requestHeaders if post is not None: requestMsg += "\r\n\r\n%s" % getUnicode(post) requestMsg += "\r\n" threadData.lastRequestMsg = requestMsg logger.log(CUSTOM_LOGGING.TRAFFIC_OUT, requestMsg) else: post = getBytes(post) if unArrayizeValue(conf.base64Parameter) == HTTPMETHOD.POST: if kb.place != HTTPMETHOD.POST: conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data) else: post = urldecode(post, convall=True) post = encodeBase64(post) if target and cmdLineOptions.method or method and method not in (HTTPMETHOD.GET, HTTPMETHOD.POST): req = MethodRequest(url, post, headers) req.set_method(cmdLineOptions.method or method) elif url is not None: req = _urllib.request.Request(url, post, headers) else: return None, None, None for function in kb.preprocessFunctions: try: function(req) except Exception as ex: errMsg = "error occurred while running preprocess " errMsg += "function '%s' ('%s')" % (function.__name__, getSafeExString(ex)) raise SqlmapGenericException(errMsg) else: post, headers = req.data, req.headers requestHeaders += "\r\n".join(["%s: %s" % (u"-".join(_.capitalize() for _ in getUnicode(key).split(u'-')) if hasattr(key, "capitalize") else getUnicode(key), getUnicode(value)) for (key, value) in req.header_items()]) if not getRequestHeader(req, HTTP_HEADER.COOKIE) and conf.cj: conf.cj._policy._now = conf.cj._now = int(time.time()) with conf.cj._cookies_lock: cookies = conf.cj._cookies_for_request(req) requestHeaders += "\r\n%s" % ("Cookie: %s" % ";".join("%s=%s" % (getUnicode(cookie.name), getUnicode(cookie.value)) for cookie in cookies)) if post is not None: if not getRequestHeader(req, HTTP_HEADER.CONTENT_LENGTH) and not chunked: requestHeaders += "\r\n%s: %d" % (string.capwords(HTTP_HEADER.CONTENT_LENGTH), len(post)) if not getRequestHeader(req, HTTP_HEADER.CONNECTION): requestHeaders += "\r\n%s: %s" % (HTTP_HEADER.CONNECTION, "close" if not conf.keepAlive else "keep-alive") requestMsg += "\r\n%s" % requestHeaders if post is not None: requestMsg += "\r\n\r\n%s" % getUnicode(post) if not chunked: requestMsg += "\r\n" if not multipart: threadData.lastRequestMsg = requestMsg logger.log(CUSTOM_LOGGING.TRAFFIC_OUT, requestMsg) if conf.cj: for cookie in conf.cj: if cookie.value is None: cookie.value = "" else: for char in (r"\r", r"\n"): cookie.value = re.sub(r"(%s)([^ \t])" % char, r"\g<1>\t\g<2>", cookie.value) conn = _urllib.request.urlopen(req) if not kb.authHeader and getRequestHeader(req, HTTP_HEADER.AUTHORIZATION) and (conf.authType or "").lower() == AUTH_TYPE.BASIC.lower(): kb.authHeader = getUnicode(getRequestHeader(req, HTTP_HEADER.AUTHORIZATION)) if not kb.proxyAuthHeader and getRequestHeader(req, HTTP_HEADER.PROXY_AUTHORIZATION): kb.proxyAuthHeader = getRequestHeader(req, HTTP_HEADER.PROXY_AUTHORIZATION) # Return response object if response: return conn, None, None # Get HTTP response if hasattr(conn, "redurl"): page = (threadData.lastRedirectMsg[1] if kb.choices.redirect == REDIRECTION.NO else Connect._connReadProxy(conn)) if not skipRead else None skipLogTraffic = kb.choices.redirect == REDIRECTION.NO code = conn.redcode if not finalCode else code else: page = Connect._connReadProxy(conn) if not skipRead else None if conn: code = (code or conn.code) if conn.code == kb.originalCode else conn.code # do not override redirection code (for comparison purposes) responseHeaders = conn.info() responseHeaders[URI_HTTP_HEADER] = conn.geturl() if hasattr(conn, "geturl") else url if getattr(conn, "redurl", None) is not None: responseHeaders[HTTP_HEADER.LOCATION] = conn.redurl responseHeaders = patchHeaders(responseHeaders) kb.serverHeader = responseHeaders.get(HTTP_HEADER.SERVER, kb.serverHeader) else: code = None responseHeaders = {} page = decodePage(page, responseHeaders.get(HTTP_HEADER.CONTENT_ENCODING), responseHeaders.get(HTTP_HEADER.CONTENT_TYPE), percentDecode=not crawling) status = getUnicode(conn.msg) if conn and getattr(conn, "msg", None) else None kb.connErrorCounter = 0 if not refreshing: refresh = responseHeaders.get(HTTP_HEADER.REFRESH, "").split("url=")[-1].strip() if extractRegexResult(META_REFRESH_REGEX, page): refresh = extractRegexResult(META_REFRESH_REGEX, page) debugMsg = "got HTML meta refresh header" logger.debug(debugMsg) if not refresh: refresh = extractRegexResult(JAVASCRIPT_HREF_REGEX, page) if refresh: debugMsg = "got Javascript redirect logic" logger.debug(debugMsg) if refresh: if kb.alwaysRefresh is None: msg = "got a refresh intent " msg += "(redirect like response common to login pages) to '%s'. " % refresh msg += "Do you want to apply it from now on? [Y/n]" kb.alwaysRefresh = readInput(msg, default='Y', boolean=True) if kb.alwaysRefresh: if re.search(r"\Ahttps?://", refresh, re.I): url = refresh else: url = _urllib.parse.urljoin(url, refresh) threadData.lastRedirectMsg = (threadData.lastRequestUID, page) kwargs["refreshing"] = True kwargs["url"] = url kwargs["get"] = None kwargs["post"] = None try: return Connect._getPageProxy(**kwargs) except SqlmapSyntaxException: pass # Explicit closing of connection object if conn and not conf.keepAlive: try: if hasattr(conn.fp, '_sock'): conn.fp._sock.close() conn.close() except Exception as ex: warnMsg = "problem occurred during connection closing ('%s')" % getSafeExString(ex) logger.warning(warnMsg) except SqlmapConnectionException as ex: if conf.proxyList and not kb.threadException: warnMsg = "unable to connect to the target URL ('%s')" % getSafeExString(ex) logger.critical(warnMsg) threadData.retriesCount = conf.retries return Connect._retryProxy(**kwargs) else: raise except _urllib.error.HTTPError as ex: page = None responseHeaders = None if checking: return None, None, None try: page = ex.read() if not skipRead else None responseHeaders = ex.info() responseHeaders[URI_HTTP_HEADER] = ex.geturl() responseHeaders = patchHeaders(responseHeaders) page = decodePage(page, responseHeaders.get(HTTP_HEADER.CONTENT_ENCODING), responseHeaders.get(HTTP_HEADER.CONTENT_TYPE), percentDecode=not crawling) except socket.timeout: warnMsg = "connection timed out while trying " warnMsg += "to get error page information (%d)" % ex.code logger.warning(warnMsg) return None, None, None except KeyboardInterrupt: raise except: pass finally: page = getUnicode(page) code = ex.code status = getUnicode(getattr(ex, "reason", None) or getSafeExString(ex).split(": ", 1)[-1]) kb.originalCode = kb.originalCode or code threadData.lastHTTPError = (threadData.lastRequestUID, code, status) kb.httpErrorCodes[code] = kb.httpErrorCodes.get(code, 0) + 1 responseMsg += "[#%d] (%s %s):\r\n" % (threadData.lastRequestUID, code, status) if responseHeaders and getattr(responseHeaders, "headers", None): logHeaders = "".join(getUnicode(responseHeaders.headers)).strip() logHTTPTraffic(requestMsg, "%s%s\r\n\r\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_READ_SIZE]), start, time.time()) skipLogTraffic = True if conf.verbose <= 5: responseMsg += getUnicode(logHeaders) elif conf.verbose > 5: responseMsg += "%s\r\n\r\n%s" % (logHeaders, (page or "")[:MAX_CONNECTION_READ_SIZE]) if not multipart: logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg) if code in conf.abortCode: errMsg = "aborting due to detected HTTP code '%d'" % code singleTimeLogMessage(errMsg, logging.CRITICAL) raise SystemExit if ex.code not in (conf.ignoreCode or []): if ex.code == _http_client.UNAUTHORIZED: errMsg = "not authorized, try to provide right HTTP " errMsg += "authentication type and valid credentials (%d). " % code errMsg += "If this is intended, try to rerun by providing " errMsg += "a valid value for option '--ignore-code'" raise SqlmapConnectionException(errMsg) elif chunked and ex.code in (_http_client.METHOD_NOT_ALLOWED, _http_client.LENGTH_REQUIRED): warnMsg = "turning off HTTP chunked transfer encoding " warnMsg += "as it seems that the target site doesn't support it (%d)" % code singleTimeWarnMessage(warnMsg) conf.chunked = kwargs["chunked"] = False return Connect.getPage(**kwargs) elif ex.code == _http_client.REQUEST_URI_TOO_LONG: warnMsg = "request URI is marked as too long by the target. " warnMsg += "you are advised to try a switch '--no-cast' and/or '--no-escape'" singleTimeWarnMessage(warnMsg) elif ex.code == _http_client.NOT_FOUND: if raise404: errMsg = "page not found (%d)" % code raise SqlmapConnectionException(errMsg) else: debugMsg = "page not found (%d)" % code singleTimeLogMessage(debugMsg, logging.DEBUG) elif ex.code == _http_client.GATEWAY_TIMEOUT: if ignoreTimeout: return None if not conf.ignoreTimeouts else "", None, None else: warnMsg = "unable to connect to the target URL (%d - %s)" % (ex.code, _http_client.responses[ex.code]) if threadData.retriesCount < conf.retries and not kb.threadException: warnMsg += ". sqlmap is going to retry the request" logger.critical(warnMsg) return Connect._retryProxy(**kwargs) elif kb.testMode: logger.critical(warnMsg) return None, None, None else: raise SqlmapConnectionException(warnMsg) else: debugMsg = "got HTTP error code: %d ('%s')" % (code, status) logger.debug(debugMsg) except (_urllib.error.URLError, socket.error, socket.timeout, _http_client.HTTPException, struct.error, binascii.Error, ProxyError, SqlmapCompressionException, WebSocketException, TypeError, ValueError, OverflowError, AttributeError, OSError, AssertionError, KeyError): tbMsg = traceback.format_exc() if conf.debug: dataToStdout(tbMsg) if checking: return None, None, None elif "KeyError:" in tbMsg: if "content-length" in tbMsg: return None, None, None else: raise elif "AttributeError:" in tbMsg: if "WSAECONNREFUSED" in tbMsg: return None, None, None else: raise elif "no host given" in tbMsg: warnMsg = "invalid URL address used (%s)" % repr(url) raise SqlmapSyntaxException(warnMsg) elif any(_ in tbMsg for _ in ("forcibly closed", "Connection is already closed", "ConnectionAbortedError")): warnMsg = "connection was forcibly closed by the target URL" elif "timed out" in tbMsg: if kb.testMode and kb.testType not in (None, PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED): singleTimeWarnMessage("there is a possibility that the target (or WAF/IPS) is dropping 'suspicious' requests") kb.droppingRequests = True warnMsg = "connection timed out to the target URL" elif "Connection reset" in tbMsg: if not conf.disablePrecon: singleTimeWarnMessage("turning off pre-connect mechanism because of connection reset(s)") conf.disablePrecon = True if kb.testMode: singleTimeWarnMessage("there is a possibility that the target (or WAF/IPS) is resetting 'suspicious' requests") kb.droppingRequests = True warnMsg = "connection reset to the target URL" elif "URLError" in tbMsg or "error" in tbMsg: warnMsg = "unable to connect to the target URL" match = re.search(r"Errno \d+\] ([^>\n]+)", tbMsg) if match: warnMsg += " ('%s')" % match.group(1).strip() elif "NTLM" in tbMsg: warnMsg = "there has been a problem with NTLM authentication" elif "Invalid header name" in tbMsg: # (e.g. PostgreSQL ::Text payload) return None, None, None elif "BadStatusLine" in tbMsg: warnMsg = "connection dropped or unknown HTTP " warnMsg += "status code received" if not conf.agent and not conf.randomAgent: warnMsg += ". Try to force the HTTP User-Agent " warnMsg += "header with option '--user-agent' or switch '--random-agent'" elif "IncompleteRead" in tbMsg: warnMsg = "there was an incomplete read error while retrieving data " warnMsg += "from the target URL" elif "Handshake status" in tbMsg: status = re.search(r"Handshake status ([\d]{3})", tbMsg) errMsg = "websocket handshake status %s" % status.group(1) if status else "unknown" raise SqlmapConnectionException(errMsg) elif "SqlmapCompressionException" in tbMsg: warnMsg = "problems with response (de)compression" retrying = True else: warnMsg = "unable to connect to the target URL" if "BadStatusLine" not in tbMsg and any((conf.proxy, conf.tor)): warnMsg += " or proxy" if silent: return None, None, None with kb.locks.connError: kb.connErrorCounter += 1 if kb.connErrorCounter >= MAX_CONSECUTIVE_CONNECTION_ERRORS and kb.choices.connError is None: message = "there seems to be a continuous problem with connection to the target. " message += "Are you sure that you want to continue? [y/N] " kb.choices.connError = readInput(message, default='N', boolean=True) if kb.choices.connError is False: raise SqlmapSkipTargetException if "forcibly closed" in tbMsg: logger.critical(warnMsg) return None, None, None elif ignoreTimeout and any(_ in tbMsg for _ in ("timed out", "IncompleteRead", "Interrupted system call")): return None if not conf.ignoreTimeouts else "", None, None elif threadData.retriesCount < conf.retries and not kb.threadException: warnMsg += ". sqlmap is going to retry the request" if not retrying: warnMsg += "(s)" logger.critical(warnMsg) else: logger.debug(warnMsg) return Connect._retryProxy(**kwargs) elif kb.testMode or kb.multiThreadMode: logger.critical(warnMsg) return None, None, None else: raise SqlmapConnectionException(warnMsg) finally: if isinstance(page, six.binary_type): if HTTP_HEADER.CONTENT_TYPE in (responseHeaders or {}) and not re.search(TEXT_CONTENT_TYPE_REGEX, responseHeaders[HTTP_HEADER.CONTENT_TYPE]): page = six.text_type(page, errors="ignore") else: page = getUnicode(page) for function in kb.postprocessFunctions: try: page, responseHeaders, code = function(page, responseHeaders, code) except Exception as ex: errMsg = "error occurred while running postprocess " errMsg += "function '%s' ('%s')" % (function.__name__, getSafeExString(ex)) raise SqlmapGenericException(errMsg) for _ in (getattr(conn, "redcode", None), code): if _ is not None and _ in conf.abortCode: errMsg = "aborting due to detected HTTP code '%d'" % _ singleTimeLogMessage(errMsg, logging.CRITICAL) raise SystemExit threadData.lastPage = page threadData.lastCode = code socket.setdefaulttimeout(conf.timeout) # Dirty patch for Python3.11.0a7 (e.g. https://github.com/sqlmapproject/sqlmap/issues/5091) if not sys.version.startswith("3.11."): if conf.retryOn and re.search(conf.retryOn, page, re.I): if threadData.retriesCount < conf.retries: warnMsg = "forced retry of the request because of undesired page content" logger.warning(warnMsg) return Connect._retryProxy(**kwargs) processResponse(page, responseHeaders, code, status) if not skipLogTraffic: if conn and getattr(conn, "redurl", None): _ = _urllib.parse.urlsplit(conn.redurl) _ = ("%s%s" % (_.path or "/", ("?%s" % _.query) if _.query else "")) requestMsg = re.sub(r"(\n[A-Z]+ ).+?( HTTP/\d)", r"\g<1>%s\g<2>" % getUnicode(_).replace("\\", "\\\\"), requestMsg, 1) if kb.resendPostOnRedirect is False: requestMsg = re.sub(r"(\[#\d+\]:\n)POST ", r"\g<1>GET ", requestMsg) requestMsg = re.sub(r"(?i)Content-length: \d+\n", "", requestMsg) requestMsg = re.sub(r"(?s)\n\n.+", "\n", requestMsg) responseMsg += "[#%d] (%s %s):\r\n" % (threadData.lastRequestUID, conn.code, status) elif "\n" not in responseMsg: responseMsg += "[#%d] (%s %s):\r\n" % (threadData.lastRequestUID, code, status) if responseHeaders: logHeaders = "".join(getUnicode(responseHeaders.headers)).strip() logHTTPTraffic(requestMsg, "%s%s\r\n\r\n%s" % (responseMsg, logHeaders, (page or "")[:MAX_CONNECTION_READ_SIZE]), start, time.time()) if conf.verbose <= 5: responseMsg += getUnicode(logHeaders) elif conf.verbose > 5: responseMsg += "%s\r\n\r\n%s" % (logHeaders, (page or "")[:MAX_CONNECTION_READ_SIZE]) if not multipart: logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg) return page, responseHeaders, code @staticmethod @stackedmethod def queryPage(value=None, place=None, content=False, getRatioValue=False, silent=False, method=None, timeBasedCompare=False, noteResponseTime=True, auxHeaders=None, response=False, raise404=None, removeReflection=True, disableTampering=False, ignoreSecondOrder=False): """ This method calls a function to get the target URL page content and returns its page ratio (0 <= ratio <= 1) or a boolean value representing False/True match in case of !getRatioValue """ if conf.direct: return direct(value, content) get = None post = None cookie = None ua = None referer = None host = None page = None pageLength = None uri = None code = None if not place: place = kb.injection.place or PLACE.GET kb.place = place if not auxHeaders: auxHeaders = {} raise404 = place != PLACE.URI if raise404 is None else raise404 method = method or conf.method postUrlEncode = kb.postUrlEncode value = agent.adjustLateValues(value) payload = agent.extractPayload(value) threadData = getCurrentThreadData() if conf.httpHeaders: headers = OrderedDict(conf.httpHeaders) contentType = max(headers[_] or "" if _.upper() == HTTP_HEADER.CONTENT_TYPE.upper() else "" for _ in headers) or None if (kb.postHint or conf.skipUrlEncode) and postUrlEncode: postUrlEncode = False if not (conf.skipUrlEncode and contentType): # NOTE: https://github.com/sqlmapproject/sqlmap/issues/5092 conf.httpHeaders = [_ for _ in conf.httpHeaders if _[1] != contentType] contentType = POST_HINT_CONTENT_TYPES.get(kb.postHint, PLAIN_TEXT_CONTENT_TYPE) conf.httpHeaders.append((HTTP_HEADER.CONTENT_TYPE, contentType)) if "urlencoded" in contentType: postUrlEncode = True if payload: delimiter = conf.paramDel or (DEFAULT_GET_POST_DELIMITER if place != PLACE.COOKIE else DEFAULT_COOKIE_DELIMITER) if not disableTampering and kb.tamperFunctions: for function in kb.tamperFunctions: hints = {} try: payload = function(payload=payload, headers=auxHeaders, delimiter=delimiter, hints=hints) except Exception as ex: errMsg = "error occurred while running tamper " errMsg += "function '%s' ('%s')" % (function.__name__, getSafeExString(ex)) raise SqlmapGenericException(errMsg) if not isinstance(payload, six.string_types): errMsg = "tamper function '%s' returns " % function.__name__ errMsg += "invalid payload type ('%s')" % type(payload) raise SqlmapValueException(errMsg) value = agent.replacePayload(value, payload) if hints: if HINT.APPEND in hints: value = "%s%s%s" % (value, delimiter, hints[HINT.APPEND]) if HINT.PREPEND in hints: if place == PLACE.URI: match = re.search(r"\w+\s*=\s*%s" % PAYLOAD_DELIMITER, value) or re.search(r"[^?%s/]=\s*%s" % (re.escape(delimiter), PAYLOAD_DELIMITER), value) if match: value = value.replace(match.group(0), "%s%s%s" % (hints[HINT.PREPEND], delimiter, match.group(0))) else: value = "%s%s%s" % (hints[HINT.PREPEND], delimiter, value) logger.log(CUSTOM_LOGGING.PAYLOAD, safecharencode(payload.replace('\\', BOUNDARY_BACKSLASH_MARKER)).replace(BOUNDARY_BACKSLASH_MARKER, '\\')) if place == PLACE.CUSTOM_POST and kb.postHint: if kb.postHint in (POST_HINT.SOAP, POST_HINT.XML): # payloads in SOAP/XML should have chars > and < replaced # with their HTML encoded counterparts payload = payload.replace("&#", SAFE_HEX_MARKER) payload = payload.replace('&', "&amp;").replace('>', "&gt;").replace('<', "&lt;").replace('"', "&quot;").replace("'", "&apos;") # Reference: https://stackoverflow.com/a/1091953 payload = payload.replace(SAFE_HEX_MARKER, "&#") elif kb.postHint == POST_HINT.JSON: payload = escapeJsonValue(payload) elif kb.postHint == POST_HINT.JSON_LIKE: payload = payload.replace("'", REPLACEMENT_MARKER).replace('"', "'").replace(REPLACEMENT_MARKER, '"') payload = escapeJsonValue(payload) payload = payload.replace("'", REPLACEMENT_MARKER).replace('"', "'").replace(REPLACEMENT_MARKER, '"') value = agent.replacePayload(value, payload) else: # GET, POST, URI and Cookie payload needs to be thoroughly URL encoded if (place in (PLACE.GET, PLACE.URI, PLACE.COOKIE) or place == PLACE.CUSTOM_HEADER and value.split(',')[0].upper() == HTTP_HEADER.COOKIE.upper()) and not conf.skipUrlEncode or place in (PLACE.POST, PLACE.CUSTOM_POST) and postUrlEncode: skip = False if place == PLACE.COOKIE or place == PLACE.CUSTOM_HEADER and value.split(',')[0].upper() == HTTP_HEADER.COOKIE.upper(): if kb.choices.cookieEncode is None: msg = "do you want to URL encode cookie values (implementation specific)? %s" % ("[Y/n]" if not conf.url.endswith(".aspx") else "[y/N]") # Reference: https://support.microsoft.com/en-us/kb/313282 kb.choices.cookieEncode = readInput(msg, default='Y' if not conf.url.endswith(".aspx") else 'N', boolean=True) if not kb.choices.cookieEncode: skip = True if not skip: if place in (PLACE.POST, PLACE.CUSTOM_POST): # potential problems in other cases (e.g. URL encoding of whole URI - including path) value = urlencode(value, spaceplus=kb.postSpaceToPlus) payload = urlencode(payload, safe='%', spaceplus=kb.postSpaceToPlus) value = agent.replacePayload(value, payload) postUrlEncode = False if conf.hpp: if not any(conf.url.lower().endswith(_.lower()) for _ in (WEB_PLATFORM.ASP, WEB_PLATFORM.ASPX)): warnMsg = "HTTP parameter pollution should work only against " warnMsg += "ASP(.NET) targets" singleTimeWarnMessage(warnMsg) if place in (PLACE.GET, PLACE.POST): _ = re.escape(PAYLOAD_DELIMITER) match = re.search(r"(?P<name>\w+)=%s(?P<value>.+?)%s" % (_, _), value) if match: payload = match.group("value") for splitter in (urlencode(' '), ' '): if splitter in payload: prefix, suffix = ("*/", "/*") if splitter == ' ' else (urlencode(_) for _ in ("*/", "/*")) parts = payload.split(splitter) parts[0] = "%s%s" % (parts[0], suffix) parts[-1] = "%s%s=%s%s" % (DEFAULT_GET_POST_DELIMITER, match.group("name"), prefix, parts[-1]) for i in xrange(1, len(parts) - 1): parts[i] = "%s%s=%s%s%s" % (DEFAULT_GET_POST_DELIMITER, match.group("name"), prefix, parts[i], suffix) payload = "".join(parts) for splitter in (urlencode(','), ','): payload = payload.replace(splitter, "%s%s=" % (DEFAULT_GET_POST_DELIMITER, match.group("name"))) value = agent.replacePayload(value, payload) else: warnMsg = "HTTP parameter pollution works only with regular " warnMsg += "GET and POST parameters" singleTimeWarnMessage(warnMsg) if place: value = agent.removePayloadDelimiters(value) if PLACE.GET in conf.parameters: get = conf.parameters[PLACE.GET] if place != PLACE.GET or not value else value elif place == PLACE.GET: # Note: for (e.g.) checkWaf() when there are no GET parameters get = value if PLACE.POST in conf.parameters: post = conf.parameters[PLACE.POST] if place != PLACE.POST or not value else value elif place == PLACE.POST: post = value if PLACE.CUSTOM_POST in conf.parameters: post = conf.parameters[PLACE.CUSTOM_POST].replace(kb.customInjectionMark, "") if place != PLACE.CUSTOM_POST or not value else value post = post.replace(ASTERISK_MARKER, '*') if post else post if PLACE.COOKIE in conf.parameters: cookie = conf.parameters[PLACE.COOKIE] if place != PLACE.COOKIE or not value else value if PLACE.USER_AGENT in conf.parameters: ua = conf.parameters[PLACE.USER_AGENT] if place != PLACE.USER_AGENT or not value else value if PLACE.REFERER in conf.parameters: referer = conf.parameters[PLACE.REFERER] if place != PLACE.REFERER or not value else value if PLACE.HOST in conf.parameters: host = conf.parameters[PLACE.HOST] if place != PLACE.HOST or not value else value if PLACE.URI in conf.parameters: uri = conf.url if place != PLACE.URI or not value else value else: uri = conf.url if value and place == PLACE.CUSTOM_HEADER: if value.split(',')[0].capitalize() == PLACE.COOKIE: cookie = value.split(',', 1)[-1] else: auxHeaders[value.split(',')[0]] = value.split(',', 1)[-1] if conf.csrfToken: token = AttribDict() def _adjustParameter(paramString, parameter, newValue): retVal = paramString if urlencode(parameter) in paramString: parameter = urlencode(parameter) match = re.search(r"%s=[^&]*" % re.escape(parameter), paramString, re.I) if match: retVal = re.sub(r"(?i)%s" % re.escape(match.group(0)), ("%s=%s" % (parameter, newValue)).replace('\\', r'\\'), paramString) else: match = re.search(r"(%s[\"']:[\"'])([^\"']+)" % re.escape(parameter), paramString, re.I) if match: retVal = re.sub(r"(?i)%s" % re.escape(match.group(0)), "%s%s" % (match.group(1), newValue), paramString) return retVal for attempt in xrange(conf.csrfRetries + 1): if token: break if attempt > 0: warnMsg = "unable to find anti-CSRF token '%s' at '%s'" % (conf.csrfToken._original, conf.csrfUrl or conf.url) warnMsg += ". sqlmap is going to retry the request" logger.warning(warnMsg) page, headers, code = Connect.getPage(url=conf.csrfUrl or conf.url, data=conf.csrfData or (conf.data if conf.csrfUrl == conf.url else None), method=conf.csrfMethod or (conf.method if conf.csrfUrl == conf.url else None), cookie=conf.parameters.get(PLACE.COOKIE), direct=True, silent=True, ua=conf.parameters.get(PLACE.USER_AGENT), referer=conf.parameters.get(PLACE.REFERER), host=conf.parameters.get(PLACE.HOST)) page = urldecode(page) # for anti-CSRF tokens with special characters in their name (e.g. 'foo:bar=...') match = re.search(r"(?i)<input[^>]+\bname=[\"']?(?P<name>%s)\b[^>]*\bvalue=[\"']?(?P<value>[^>'\"]*)" % conf.csrfToken, page or "", re.I) if not match: match = re.search(r"(?i)<input[^>]+\bvalue=[\"']?(?P<value>[^>'\"]*)[\"']?[^>]*\bname=[\"']?(?P<name>%s)\b" % conf.csrfToken, page or "", re.I) if not match: match = re.search(r"(?P<name>%s)[\"']:[\"'](?P<value>[^\"']+)" % conf.csrfToken, page or "", re.I) if not match: match = re.search(r"\b(?P<name>%s)\s*[:=]\s*(?P<value>\w+)" % conf.csrfToken, getUnicode(headers), re.I) if not match: match = re.search(r"\b(?P<name>%s)\s*=\s*['\"]?(?P<value>[^;'\"]+)" % conf.csrfToken, page or "", re.I) if not match: match = re.search(r"<meta\s+name=[\"']?(?P<name>%s)[\"']?[^>]+\b(value|content)=[\"']?(?P<value>[^>\"']+)" % conf.csrfToken, page or "", re.I) if match: token.name, token.value = match.group("name"), match.group("value") match = re.search(r"String\.fromCharCode\(([\d+, ]+)\)", token.value) if match: token.value = "".join(_unichr(int(_)) for _ in match.group(1).replace(' ', "").split(',')) if not token: if conf.csrfUrl and conf.csrfToken and conf.csrfUrl != conf.url and code == _http_client.OK: if headers and PLAIN_TEXT_CONTENT_TYPE in headers.get(HTTP_HEADER.CONTENT_TYPE, ""): token.name = conf.csrfToken token.value = page if not token and conf.cj and any(re.search(conf.csrfToken, _.name, re.I) for _ in conf.cj): for _ in conf.cj: if re.search(conf.csrfToken, _.name, re.I): token.name, token.value = _.name, _.value if not any(re.search(conf.csrfToken, ' '.join(_), re.I) for _ in (conf.paramDict.get(PLACE.GET, {}), conf.paramDict.get(PLACE.POST, {}))): if post: post = "%s%s%s=%s" % (post, conf.paramDel or DEFAULT_GET_POST_DELIMITER, token.name, token.value) elif get: get = "%s%s%s=%s" % (get, conf.paramDel or DEFAULT_GET_POST_DELIMITER, token.name, token.value) else: get = "%s=%s" % (token.name, token.value) break if not token: errMsg = "anti-CSRF token '%s' can't be found at '%s'" % (conf.csrfToken._original, conf.csrfUrl or conf.url) if not conf.csrfUrl: errMsg += ". You can try to rerun by providing " errMsg += "a valid value for option '--csrf-url'" raise SqlmapTokenException(errMsg) if token: token.value = token.value.strip("'\"") for candidate in (PLACE.GET, PLACE.POST, PLACE.CUSTOM_POST, PLACE.URI): if candidate in conf.parameters: if candidate == PLACE.URI and uri: uri = _adjustParameter(uri, token.name, token.value) elif candidate == PLACE.GET and get: get = _adjustParameter(get, token.name, token.value) elif candidate in (PLACE.POST, PLACE.CUSTOM_POST) and post: post = _adjustParameter(post, token.name, token.value) for i in xrange(len(conf.httpHeaders)): if conf.httpHeaders[i][0].lower() == token.name.lower(): conf.httpHeaders[i] = (conf.httpHeaders[i][0], token.value) if conf.rParam: def _randomizeParameter(paramString, randomParameter): retVal = paramString match = re.search(r"(\A|\b)%s=(?P<value>[^&;]*)" % re.escape(randomParameter), paramString) if match: origValue = match.group("value") newValue = randomizeParameterValue(origValue) if randomParameter not in kb.randomPool else random.sample(kb.randomPool[randomParameter], 1)[0] retVal = re.sub(r"(\A|\b)%s=[^&;]*" % re.escape(randomParameter), "%s=%s" % (randomParameter, newValue), paramString) else: match = re.search(r"(\A|\b)(%s\b[^\w]+)(?P<value>\w+)" % re.escape(randomParameter), paramString) if match: origValue = match.group("value") newValue = randomizeParameterValue(origValue) if randomParameter not in kb.randomPool else random.sample(kb.randomPool[randomParameter], 1)[0] retVal = paramString.replace(match.group(0), "%s%s" % (match.group(2), newValue)) return retVal for randomParameter in conf.rParam: for item in (PLACE.GET, PLACE.POST, PLACE.COOKIE, PLACE.URI, PLACE.CUSTOM_POST): if item in conf.parameters: if item == PLACE.GET and get: get = _randomizeParameter(get, randomParameter) elif item in (PLACE.POST, PLACE.CUSTOM_POST) and post: post = _randomizeParameter(post, randomParameter) elif item == PLACE.COOKIE and cookie: cookie = _randomizeParameter(cookie, randomParameter) elif item == PLACE.URI and uri: uri = _randomizeParameter(uri, randomParameter) if conf.evalCode: delimiter = conf.paramDel or DEFAULT_GET_POST_DELIMITER variables = {"uri": uri, "lastPage": threadData.lastPage, "_locals": locals(), "cookie": cookie} originals = {} if not get and PLACE.URI in conf.parameters: query = _urllib.parse.urlsplit(uri).query or "" else: query = None for item in filterNone((get, post if not kb.postHint else None, query)): for part in item.split(delimiter): if '=' in part: name, value = part.split('=', 1) name = name.strip() if safeVariableNaming(name) != name: conf.evalCode = re.sub(r"\b%s\b" % re.escape(name), safeVariableNaming(name), conf.evalCode) name = safeVariableNaming(name) value = urldecode(value, convall=True, spaceplus=(item == post and kb.postSpaceToPlus)) variables[name] = value if post and kb.postHint in (POST_HINT.JSON, POST_HINT.JSON_LIKE): for name, value in (parseJson(post) or {}).items(): if safeVariableNaming(name) != name: conf.evalCode = re.sub(r"\b%s\b" % re.escape(name), safeVariableNaming(name), conf.evalCode) name = safeVariableNaming(name) variables[name] = value if cookie: for part in cookie.split(conf.cookieDel or DEFAULT_COOKIE_DELIMITER): if '=' in part: name, value = part.split('=', 1) name = name.strip() if safeVariableNaming(name) != name: conf.evalCode = re.sub(r"\b%s\b" % re.escape(name), safeVariableNaming(name), conf.evalCode) name = safeVariableNaming(name) value = urldecode(value, convall=True) variables[name] = value while True: try: compile(getBytes(re.sub(r"\s*;\s*", "\n", conf.evalCode)), "", "exec") except SyntaxError as ex: if ex.text: original = replacement = getUnicode(ex.text.strip()) if '=' in original: name, value = original.split('=', 1) name = name.strip() if safeVariableNaming(name) != name: replacement = re.sub(r"\b%s\b" % re.escape(name), safeVariableNaming(name), replacement) else: for _ in re.findall(r"[A-Za-z_]+", original)[::-1]: if safeVariableNaming(_) != _: replacement = replacement.replace(_, safeVariableNaming(_)) break if original == replacement: conf.evalCode = conf.evalCode.replace(EVALCODE_ENCODED_PREFIX, "") break else: conf.evalCode = conf.evalCode.replace(getUnicode(ex.text.strip(), UNICODE_ENCODING), replacement) else: break else: break originals.update(variables) evaluateCode(conf.evalCode, variables) for variable in list(variables.keys()): if unsafeVariableNaming(variable) != variable: value = variables[variable] del variables[variable] variables[unsafeVariableNaming(variable)] = value uri = variables["uri"] cookie = variables["cookie"] for name, value in variables.items(): if name != "__builtins__" and originals.get(name, "") != value: if isinstance(value, (int, float, six.string_types, six.binary_type)): found = False value = getUnicode(value, UNICODE_ENCODING) if kb.postHint == POST_HINT.MULTIPART: boundary = "--%s" % re.search(r"boundary=([^\s]+)", contentType).group(1) if boundary: parts = post.split(boundary) match = re.search(r'\bname="%s"' % re.escape(name), post) if not match and parts: parts.insert(2, parts[1]) parts[2] = re.sub(r'\bname="[^"]+".*', 'name="%s"' % re.escape(name), parts[2]) for i in xrange(len(parts)): part = parts[i] if re.search(r'\bname="%s"' % re.escape(name), part): match = re.search(r"(?s)\A.+?\r?\n\r?\n", part) if match: found = True first = match.group(0) second = part[len(first):] second = re.sub(r"(?s).+?(\r?\n?\-*\Z)", r"%s\g<1>" % re.escape(value), second) parts[i] = "%s%s" % (first, second) post = boundary.join(parts) elif kb.postHint and re.search(r"\b%s\b" % re.escape(name), post or ""): if kb.postHint in (POST_HINT.XML, POST_HINT.SOAP): if re.search(r"<%s\b" % re.escape(name), post): found = True post = re.sub(r"(?s)(<%s\b[^>]*>)(.*?)(</%s)" % (re.escape(name), re.escape(name)), r"\g<1>%s\g<3>" % value.replace('\\', r'\\'), post) elif re.search(r"\b%s>" % re.escape(name), post): found = True post = re.sub(r"(?s)(\b%s>)(.*?)(</[^<]*\b%s>)" % (re.escape(name), re.escape(name)), r"\g<1>%s\g<3>" % value.replace('\\', r'\\'), post) elif kb.postHint in (POST_HINT.JSON, POST_HINT.JSON_LIKE): match = re.search(r"['\"]%s['\"]:" % re.escape(name), post) if match: quote = match.group(0)[0] post = post.replace("\\%s" % quote, BOUNDARY_BACKSLASH_MARKER) match = re.search(r"(%s%s%s:\s*)(\d+|%s[^%s]*%s)" % (quote, re.escape(name), quote, quote, quote, quote), post) if match: found = True post = post.replace(match.group(0), "%s%s" % (match.group(1), value if value.isdigit() else "%s%s%s" % (match.group(0)[0], value, match.group(0)[0]))) post = post.replace(BOUNDARY_BACKSLASH_MARKER, "\\%s" % quote) regex = r"\b(%s)\b([^\w]+)(\w+)" % re.escape(name) if not found and re.search(regex, (post or "")): found = True post = re.sub(regex, r"\g<1>\g<2>%s" % value.replace('\\', r'\\'), post) regex = r"((\A|%s)%s=).+?(%s|\Z)" % (re.escape(delimiter), re.escape(name), re.escape(delimiter)) if not found and re.search(regex, (post or "")): found = True post = re.sub(regex, r"\g<1>%s\g<3>" % value.replace('\\', r'\\'), post) if re.search(regex, (get or "")): found = True get = re.sub(regex, r"\g<1>%s\g<3>" % value.replace('\\', r'\\'), get) if re.search(regex, (query or "")): found = True uri = re.sub(regex.replace(r"\A", r"\?"), r"\g<1>%s\g<3>" % value.replace('\\', r'\\'), uri) regex = r"((\A|%s\s*)%s=).+?(%s|\Z)" % (re.escape(conf.cookieDel or DEFAULT_COOKIE_DELIMITER), re.escape(name), re.escape(conf.cookieDel or DEFAULT_COOKIE_DELIMITER)) if re.search(regex, (cookie or "")): found = True cookie = re.sub(regex, r"\g<1>%s\g<3>" % value.replace('\\', r'\\'), cookie) if not found: if post is not None: if kb.postHint in (POST_HINT.JSON, POST_HINT.JSON_LIKE): match = re.search(r"['\"]", post) if match: quote = match.group(0) post = re.sub(r"\}\Z", "%s%s}" % (',' if re.search(r"\w", post) else "", "%s%s%s:%s" % (quote, name, quote, value if value.isdigit() else "%s%s%s" % (quote, value, quote))), post) else: post += "%s%s=%s" % (delimiter, name, value) elif get is not None: get += "%s%s=%s" % (delimiter, name, value) elif cookie is not None: cookie += "%s%s=%s" % (conf.cookieDel or DEFAULT_COOKIE_DELIMITER, name, value) if not conf.skipUrlEncode: get = urlencode(get, limit=True) if post is not None: if place not in (PLACE.POST, PLACE.CUSTOM_POST) and hasattr(post, UNENCODED_ORIGINAL_VALUE): post = getattr(post, UNENCODED_ORIGINAL_VALUE) elif postUrlEncode: post = urlencode(post, spaceplus=kb.postSpaceToPlus) if timeBasedCompare and not conf.disableStats: if len(kb.responseTimes.get(kb.responseTimeMode, [])) < MIN_TIME_RESPONSES: clearConsoleLine() kb.responseTimes.setdefault(kb.responseTimeMode, []) if conf.tor: warnMsg = "it's highly recommended to avoid usage of switch '--tor' for " warnMsg += "time-based injections because of inherent high latency time" singleTimeWarnMessage(warnMsg) warnMsg = "[%s] [WARNING] %stime-based comparison requires " % (time.strftime("%X"), "(case) " if kb.responseTimeMode else "") warnMsg += "%s statistical model, please wait" % ("larger" if len(kb.responseTimes) == 1 else "reset of") dataToStdout(warnMsg) while len(kb.responseTimes[kb.responseTimeMode]) < MIN_TIME_RESPONSES: value = kb.responseTimePayload.replace(RANDOM_INTEGER_MARKER, str(randomInt(6))).replace(RANDOM_STRING_MARKER, randomStr()) if kb.responseTimePayload else kb.responseTimePayload Connect.queryPage(value=value, content=True, raise404=False) dataToStdout('.') dataToStdout(" (done)\n") elif not kb.testMode: warnMsg = "it is very important to not stress the network connection " warnMsg += "during usage of time-based payloads to prevent potential " warnMsg += "disruptions " singleTimeWarnMessage(warnMsg) if not kb.laggingChecked: kb.laggingChecked = True deviation = stdev(kb.responseTimes[kb.responseTimeMode]) if deviation is not None and deviation > WARN_TIME_STDEV: kb.adjustTimeDelay = ADJUST_TIME_DELAY.DISABLE warnMsg = "considerable lagging has been detected " warnMsg += "in connection response(s). Please use as high " warnMsg += "value for option '--time-sec' as possible (e.g. " warnMsg += "10 or more)" logger.critical(warnMsg) if (conf.safeFreq or 0) > 0: kb.queryCounter += 1 if kb.queryCounter % conf.safeFreq == 0: if conf.safeUrl: Connect.getPage(url=conf.safeUrl, post=conf.safePost, cookie=cookie, direct=True, silent=True, ua=ua, referer=referer, host=host) elif kb.safeReq: Connect.getPage(url=kb.safeReq.url, post=kb.safeReq.post, method=kb.safeReq.method, auxHeaders=kb.safeReq.headers) start = time.time() if kb.nullConnection and not content and not response and not timeBasedCompare: noteResponseTime = False try: pushValue(kb.pageCompress) kb.pageCompress = False if kb.nullConnection == NULLCONNECTION.HEAD: method = HTTPMETHOD.HEAD elif kb.nullConnection == NULLCONNECTION.RANGE: auxHeaders[HTTP_HEADER.RANGE] = "bytes=-1" _, headers, code = Connect.getPage(url=uri, get=get, post=post, method=method, cookie=cookie, ua=ua, referer=referer, host=host, silent=silent, auxHeaders=auxHeaders, raise404=raise404, skipRead=(kb.nullConnection == NULLCONNECTION.SKIP_READ)) if headers: try: if kb.nullConnection in (NULLCONNECTION.HEAD, NULLCONNECTION.SKIP_READ) and headers.get(HTTP_HEADER.CONTENT_LENGTH): pageLength = int(headers[HTTP_HEADER.CONTENT_LENGTH].split(',')[0]) elif kb.nullConnection == NULLCONNECTION.RANGE and headers.get(HTTP_HEADER.CONTENT_RANGE): pageLength = int(headers[HTTP_HEADER.CONTENT_RANGE][headers[HTTP_HEADER.CONTENT_RANGE].find('/') + 1:]) except ValueError: pass finally: kb.pageCompress = popValue() if pageLength is None: try: page, headers, code = Connect.getPage(url=uri, get=get, post=post, method=method, cookie=cookie, ua=ua, referer=referer, host=host, silent=silent, auxHeaders=auxHeaders, response=response, raise404=raise404, ignoreTimeout=timeBasedCompare) except MemoryError: page, headers, code = None, None, None warnMsg = "site returned insanely large response" if kb.testMode: warnMsg += " in testing phase. This is a common " warnMsg += "behavior in custom WAF/IPS solutions" singleTimeWarnMessage(warnMsg) if not ignoreSecondOrder: if conf.secondUrl: page, headers, code = Connect.getPage(url=conf.secondUrl, cookie=cookie, ua=ua, silent=silent, auxHeaders=auxHeaders, response=response, raise404=False, ignoreTimeout=timeBasedCompare, refreshing=True) elif kb.secondReq and IPS_WAF_CHECK_PAYLOAD not in _urllib.parse.unquote(value or ""): def _(value): if kb.customInjectionMark in (value or ""): if payload is None: value = value.replace(kb.customInjectionMark, "") else: try: value = re.sub(r"\w*%s" % re.escape(kb.customInjectionMark), payload, value) except re.error: value = re.sub(r"\w*%s" % re.escape(kb.customInjectionMark), re.escape(payload), value) return value page, headers, code = Connect.getPage(url=_(kb.secondReq[0]), post=_(kb.secondReq[2]), method=kb.secondReq[1], cookie=kb.secondReq[3], silent=silent, auxHeaders=dict(auxHeaders, **dict(kb.secondReq[4])), response=response, raise404=False, ignoreTimeout=timeBasedCompare, refreshing=True) threadData.lastQueryDuration = calculateDeltaSeconds(start) kb.originalCode = code if kb.originalCode is None else kb.originalCode kb.originalPage = page if kb.originalPage is None else kb.originalPage if kb.testMode: kb.testQueryCount += 1 if timeBasedCompare: return wasLastResponseDelayed() elif noteResponseTime: kb.responseTimes.setdefault(kb.responseTimeMode, []) kb.responseTimes[kb.responseTimeMode].append(threadData.lastQueryDuration) if len(kb.responseTimes[kb.responseTimeMode]) > MAX_TIME_RESPONSES: kb.responseTimes[kb.responseTimeMode] = kb.responseTimes[kb.responseTimeMode][-MAX_TIME_RESPONSES // 2:] if not response and removeReflection: page = removeReflectiveValues(page, payload) kb.maxConnectionsFlag = re.search(MAX_CONNECTIONS_REGEX, page or "", re.I) is not None message = extractRegexResult(PERMISSION_DENIED_REGEX, page or "", re.I) if message: kb.permissionFlag = True singleTimeWarnMessage("potential permission problems detected ('%s')" % message) headers = patchHeaders(headers) if content or response: return page, headers, code if getRatioValue: return comparison(page, headers, code, getRatioValue=False, pageLength=pageLength), comparison(page, headers, code, getRatioValue=True, pageLength=pageLength) else: return comparison(page, headers, code, getRatioValue, pageLength) def setHTTPHandlers(): # Cross-referenced function raise NotImplementedError
connect.py/0
{ "file_path": "connect.py", "repo_id": "connect.py", "token_count": 40754 }
19
import os import json import argparse import pandas as pd def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--annotation-file", type=str, required=True) parser.add_argument("--result-dir", type=str, required=True) parser.add_argument("--upload-dir", type=str, required=True) parser.add_argument("--experiment", type=str, required=True) return parser.parse_args() if __name__ == "__main__": args = get_args() df = pd.read_table(args.annotation_file) cur_df = df.copy() cur_df = cur_df.drop(columns=['hint', 'category', 'source', 'image', 'comment', 'l2-category']) cur_df.insert(6, 'prediction', None) for pred in open(os.path.join(args.result_dir, f"{args.experiment}.jsonl")): pred = json.loads(pred) cur_df.loc[df['index'] == pred['question_id'], 'prediction'] = pred['text'] cur_df.to_excel(os.path.join(args.upload_dir, f"{args.experiment}.xlsx"), index=False, engine='openpyxl')
convert_mmbench_for_submission.py/0
{ "file_path": "convert_mmbench_for_submission.py", "repo_id": "convert_mmbench_for_submission.py", "token_count": 384 }
20
import { HTML_FONT_SIZE } from "../Theme.types" export const DEFAULT_MIN_SCREEN = 360 export const DEFAULT_MAX_SCREEN = 1600 /** * It returns a CSS `clamp` function string that will fluidly * transition between a `minSize` and `maxSize` based on the screen size provided */ export const createFluidValue = (minSize: number, maxSize: number, defaultBaseSize = HTML_FONT_SIZE) => { return `clamp(${pxToRem(minSize, defaultBaseSize)}, ${getPreferredValue( minSize, maxSize, DEFAULT_MIN_SCREEN, DEFAULT_MAX_SCREEN, defaultBaseSize )}, ${pxToRem(maxSize, defaultBaseSize)})` } /** * Determines how fluid typography scales */ const getPreferredValue = ( minSize: number, maxSize: number, minScreenSize: number, maxScreenSize: number, defaultBaseSize: number ) => { const vwCalc = cleanNumber((100 * (maxSize - minSize)) / (maxScreenSize - minScreenSize)) const remCalc = cleanNumber((minScreenSize * maxSize - maxScreenSize * minSize) / (minScreenSize - maxScreenSize)) return `${vwCalc}vw + ${pxToRem(remCalc, defaultBaseSize)}` } const pxToRem = (px: number | string, defaultBaseSize: number) => `${cleanNumber(Number(px) / defaultBaseSize)}rem` const cleanNumber = (num: number) => Math.round((num + Number.EPSILON) * 100) / 100
create-fluid-value.ts/0
{ "file_path": "create-fluid-value.ts", "repo_id": "create-fluid-value.ts", "token_count": 436 }
21
import os import copy from dataclasses import dataclass, field import json from typing import Dict, Sequence, Optional import torch import transformers from bunny.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN from torch.utils.data import Dataset from bunny import conversation as conversation_lib from bunny.util.mm_utils import tokenizer_image_token from PIL import Image @dataclass class DataArguments: data_path: str = field(default=None, metadata={"help": "Path to the training data."}) lazy_preprocess: bool = False is_multimodal: bool = True image_folder: Optional[str] = field(default=None) image_aspect_ratio: str = field(default=None) def preprocess_multimodal( sources: Sequence[str], data_args: DataArguments ) -> Dict: is_multimodal = data_args.is_multimodal if not is_multimodal: return sources for source in sources: for sentence in source: if DEFAULT_IMAGE_TOKEN in sentence['value']: sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip() sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value'] sentence['value'] = sentence['value'].strip() replace_token = DEFAULT_IMAGE_TOKEN sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) return sources def preprocess_bunny( sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False ) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {"human": conv.roles[0], "gpt": conv.roles[1]} # Apply prompt templates conversations = [] for i, source in enumerate(sources): if roles[source[0]["from"]] != conv.roles[0]: # Skip the first one if it is not from human source = source[1:] conv.messages = [] for j, sentence in enumerate(source): role = roles[sentence["from"]] assert role == conv.roles[j % 2], f"{i}" conv.append_message(role, sentence["value"]) conversations.append(conv.get_prompt()) # Tokenize conversations if has_image: input_ids = torch.stack( [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) else: input_ids = tokenizer( conversations, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ).input_ids targets = input_ids.clone() assert conv.sep_style == conversation_lib.SeparatorStyle.TWO # Mask targets sep = conv.sep + conv.roles[1] + ": " for conversation, target in zip(conversations, targets): total_len = int(target.ne(tokenizer.pad_token_id).sum()) rounds = conversation.split(conv.sep2) cur_len = 0 end_token_cnt = 0 for i, rou in enumerate(rounds): if rou == "": break parts = rou.split(sep) if len(parts) != 2: break parts[0] += sep if has_image: round_len = len(tokenizer_image_token(rou, tokenizer)) instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 1 else: round_len = len(tokenizer(rou).input_ids) instruction_len = len(tokenizer(parts[0]).input_ids) - 1 round_len += 1 end_token_cnt += 1 target[cur_len: cur_len + instruction_len] = IGNORE_INDEX cur_len += round_len target[cur_len:] = IGNORE_INDEX cur_len -= end_token_cnt if cur_len < tokenizer.model_max_length: if cur_len != total_len: target[:] = IGNORE_INDEX print( f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)" ) return dict( input_ids=input_ids, labels=targets, ) def preprocess_plain( sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, ) -> Dict: # add end signal and concatenate together conversations = [] for source in sources: assert len(source) == 2 assert DEFAULT_IMAGE_TOKEN in source[0]['value'] source[0]['value'] = DEFAULT_IMAGE_TOKEN conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep conversations.append(conversation) # tokenize conversations input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] targets = copy.deepcopy(input_ids) for target, source in zip(targets, sources): tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer)) target[:tokenized_len] = IGNORE_INDEX return dict(input_ids=input_ids, labels=targets) def preprocess( sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False ) -> Dict: if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: return preprocess_plain(sources, tokenizer) if conversation_lib.default_conversation.version == "bunny": return preprocess_bunny(sources, tokenizer, has_image=has_image) class LazySupervisedDataset(Dataset): """Dataset for supervised fine-tuning.""" def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments): super(LazySupervisedDataset, self).__init__() list_data_dict = json.load(open(data_path, "r")) print("Formatting inputs...Skip in lazy mode") self.tokenizer = tokenizer self.list_data_dict = list_data_dict self.data_args = data_args def __len__(self): return len(self.list_data_dict) @property def lengths(self): length_list = [] for sample in self.list_data_dict: img_tokens = 128 if 'image' in sample else 0 length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens) return length_list @property def modality_lengths(self): length_list = [] for sample in self.list_data_dict: cur_len = sum(len(conv['value'].split()) for conv in sample['conversations']) cur_len = cur_len if 'image' in sample else -cur_len length_list.append(cur_len) return length_list def __getitem__(self, i) -> Dict[str, torch.Tensor]: sources = self.list_data_dict[i] if isinstance(i, int): sources = [sources] assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME if 'image' in sources[0]: image_file = self.list_data_dict[i]['image'] image_folder = self.data_args.image_folder processor = self.data_args.image_processor image = Image.open(os.path.join(image_folder, image_file)).convert('RGB') if self.data_args.image_aspect_ratio == 'pad': def expand2square(pil_img, background_color): width, height = pil_img.size if width == height: return pil_img elif width > height: result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2)) return result else: result = Image.new(pil_img.mode, (height, height), background_color) result.paste(pil_img, ((height - width) // 2, 0)) return result image = expand2square(image, tuple(int(x * 255) for x in processor.image_mean)) image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] else: image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] sources = preprocess_multimodal( copy.deepcopy([e["conversations"] for e in sources]), self.data_args) else: sources = copy.deepcopy([e["conversations"] for e in sources]) data_dict = preprocess( sources, self.tokenizer, has_image=('image' in self.list_data_dict[i])) if isinstance(i, int): data_dict = dict(input_ids=data_dict["input_ids"][0], labels=data_dict["labels"][0]) # image exist in the data if 'image' in self.list_data_dict[i]: data_dict['image'] = image elif self.data_args.is_multimodal: # image does not exist in the data, but the model is multimodal crop_size = self.data_args.image_processor.crop_size data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width']) return data_dict @dataclass class DataCollatorForSupervisedDataset(object): """Collate examples for supervised fine-tuning.""" tokenizer: transformers.PreTrainedTokenizer def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels")) if self.tokenizer.pad_token_id == self.tokenizer.eos_token_id: for input_id in input_ids: input_id[input_id == self.tokenizer.eos_token_id] = -300 input_ids = torch.nn.utils.rnn.pad_sequence( input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id) labels = torch.nn.utils.rnn.pad_sequence( labels, batch_first=True, padding_value=IGNORE_INDEX) input_ids = input_ids[:, :self.tokenizer.model_max_length] attention_mask = input_ids.ne(self.tokenizer.pad_token_id) labels = labels[:, :self.tokenizer.model_max_length] if self.tokenizer.pad_token_id == self.tokenizer.eos_token_id: for input_id in input_ids: input_id[input_id == -300] = self.tokenizer.eos_token_id batch = dict( input_ids=input_ids, labels=labels, attention_mask=attention_mask, ) if 'image' in instances[0]: images = [instance['image'] for instance in instances] if all(x is not None and x.shape == images[0].shape for x in images): batch['images'] = torch.stack(images) else: batch['images'] = images return batch def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: """Make dataset and collator for supervised fine-tuning.""" train_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args) data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) return dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator)
data_utils.py/0
{ "file_path": "data_utils.py", "repo_id": "data_utils.py", "token_count": 5270 }
22
from typing import Dict, Optional, Sequence, List import copy import transformers import torch from tinyllava.data.process import register_preprocess from tinyllava.mm_utils import tokenizer_image_token from tinyllava import conversation as conversation_lib from tinyllava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, \ DEFAULT_IM_END_TOKEN @register_preprocess('default') def preprocess_default( sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False ) -> Dict: conversations = [] for source in sources: header = f"{conversation_lib.default_conversation.system}\n\n" conversation = _add_speaker_and_signal(header, source) conversations.append(conversation) # tokenize conversations def get_tokenize_len(prompts): return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts] if has_image: input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] else: conversations_tokenized = _tokenize_fn(conversations, tokenizer) input_ids = conversations_tokenized["input_ids"] targets = copy.deepcopy(input_ids) for target, source in zip(targets, sources): if has_image: tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) else: tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] speakers = [sentence["from"] for sentence in source] _mask_targets(target, tokenized_lens, speakers) return dict(input_ids=input_ids, labels=targets) def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict: """Tokenize a list of strings.""" tokenized_list = [ tokenizer( text, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ) for text in strings ] input_ids = labels = [ tokenized.input_ids[0] for tokenized in tokenized_list ] input_ids_lens = labels_lens = [ tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list ] return dict( input_ids=input_ids, labels=labels, input_ids_lens=input_ids_lens, labels_lens=labels_lens, ) def _add_speaker_and_signal(header, source, get_conversation=True): """Add speaker and start/end signal on each round.""" BEGIN_SIGNAL = "### " END_SIGNAL = "\n" conversation = header for sentence in source: from_str = sentence["from"] if from_str.lower() == "human": from_str = conversation_lib.default_conversation.roles[0] elif from_str.lower() == "gpt": from_str = conversation_lib.default_conversation.roles[1] else: from_str = 'unknown' sentence["value"] = (BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL) if get_conversation: conversation += sentence["value"] conversation += BEGIN_SIGNAL return conversation def _mask_targets(target, tokenized_lens, speakers): # cur_idx = 0 cur_idx = tokenized_lens[0] tokenized_lens = tokenized_lens[1:] target[:cur_idx] = IGNORE_INDEX for tokenized_len, speaker in zip(tokenized_lens, speakers): if speaker == "human": target[cur_idx + 2:cur_idx + tokenized_len] = IGNORE_INDEX cur_idx += tokenized_len
default.py/0
{ "file_path": "default.py", "repo_id": "default.py", "token_count": 1540 }
23
_base_ = ( '../../third_party/mmdeploy/configs/mmdet/detection/' 'detection_onnxruntime-fp16_dynamic.py') codebase_config = dict( type='mmyolo', task='ObjectDetection', model_type='end2end', post_processing=dict( score_threshold=0.1, confidence_threshold=0.005, iou_threshold=0.3, max_output_boxes_per_class=100, pre_top_k=1000, keep_top_k=100, background_label_id=-1), module=['mmyolo.deploy']) backend_config = dict( type='onnxruntime')
detection_onnxruntime-fp16_dynamic.py/0
{ "file_path": "detection_onnxruntime-fp16_dynamic.py", "repo_id": "detection_onnxruntime-fp16_dynamic.py", "token_count": 256 }
24
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. """ Misc functions, including distributed helpers. Mostly copy-paste from torchvision references. """ import io import os import time import torch import torch.distributed as dist def init_distributed_mode(args): if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: args.rank = int(os.environ["RANK"]) args.world_size = int(os.environ['WORLD_SIZE']) args.gpu = int(os.environ['LOCAL_RANK']) elif 'SLURM_PROCID' in os.environ: args.rank = int(os.environ['SLURM_PROCID']) args.gpu = args.rank % torch.cuda.device_count() else: print('Not using distributed mode') args.distributed = False return args.distributed = True torch.cuda.set_device(args.gpu) args.dist_backend = 'nccl' print('| distributed init (rank {}): {}'.format( args.rank, args.dist_url), flush=True) torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, world_size=args.world_size, rank=args.rank) time.sleep(60) torch.distributed.barrier() setup_for_distributed(args.rank == 0) def setup_for_distributed(is_master): """ This function disables printing when not in master process """ import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop('force', False) if is_master or force: builtin_print(*args, **kwargs) __builtin__.print = print def is_dist_avail_and_initialized(): if not dist.is_available(): return False if not dist.is_initialized(): return False return True def get_world_size(): if not is_dist_avail_and_initialized(): return 1 return dist.get_world_size() def get_rank(): if not is_dist_avail_and_initialized(): return 0 return dist.get_rank() def is_main_process(): return get_rank() == 0
dist.py/0
{ "file_path": "dist.py", "repo_id": "dist.py", "token_count": 835 }
25
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
32
Edit dataset card