Registry values for use with the State

状态与通知API
本文档定义了一系列用于获取设备状态及通知信息的注册表路径和值,涵盖了应用活动、显示旋转设置、键盘连接状态等多个方面,有助于开发者更好地了解并利用这些信息进行应用开发。

//*************************************************************
//
// snapi.h
//
// Registry values for use with the State & Notification Broker APIs in regext.h
//
//*************************************************************
 
 
////////////////////////////////////////////////////////////////////////////////
// ActiveApplication
// Gets the name of the application that was previously active and the name of the application that is currently active, separated by the 'Escape' character ('/e').
#define SN_ACTIVEAPPLICATION_ROOT HKEY_CURRENT_USER
#define SN_ACTIVEAPPLICATION_PATH TEXT("System//State//Shell")
#define SN_ACTIVEAPPLICATION_VALUE TEXT("Active Application")
 
 
////////////////////////////////////////////////////////////////////////////////
// DisplayRotation
// Gets the orientation of the display, specified as the number of degrees, ranging from 0 to 360. Portrait = 0. Landscape = 90 or -90.
#define SN_DISPLAYROTATION_ROOT HKEY_LOCAL_MACHINE
#define SN_DISPLAYROTATION_PATH TEXT("System//GDI//Rotation")
#define SN_DISPLAYROTATION_VALUE TEXT("Angle")
 
 
////////////////////////////////////////////////////////////////////////////////
// KeyboardPresent
// Gets a value indicating whether a keyboard is attached and enabled.
#define SN_KEYBOARDPRESENT_ROOT HKEY_LOCAL_MACHINE
#define SN_KEYBOARDPRESENT_PATH TEXT("Software//Microsoft//Shell")
#define SN_KEYBOARDPRESENT_VALUE TEXT("HasKeyboard")
 
 
////////////////////////////////////////////////////////////////////////////////
// CradlePresent
// Gets a value indicating whether the device is connected to a cradle.
#define SN_CRADLEPRESENT_ROOT HKEY_LOCAL_MACHINE
#define SN_CRADLEPRESENT_PATH TEXT("System//State//Hardware")
#define SN_CRADLEPRESENT_VALUE TEXT("Cradled")
 
 
////////////////////////////////////////////////////////////////////////////////
// CameraPresent
// Gets a value indicating whether a camera is attached and enabled.
#define SN_CAMERAPRESENT_ROOT HKEY_LOCAL_MACHINE
#define SN_CAMERAPRESENT_PATH TEXT("System//State//Hardware")
#define SN_CAMERAPRESENT_VALUE TEXT("Camera")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingSmsUnread
// Gets the number of unread SMS messages.
#define SN_MESSAGINGSMSUNREAD_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGSMSUNREAD_PATH TEXT("System//State//Messages//SMS//Unread")
#define SN_MESSAGINGSMSUNREAD_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingMmsUnread
// Gets the number of unread MMS messages
#define SN_MESSAGINGMMSUNREAD_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGMMSUNREAD_PATH TEXT("System//State//Messages//MMS//Unread")
#define SN_MESSAGINGMMSUNREAD_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingVoiceMailTotalUnread
// Gets the number of unplayed voice mail messages.
#define SN_MESSAGINGVOICEMAILTOTALUNREAD_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGVOICEMAILTOTALUNREAD_PATH TEXT("System//State//Messages//VMail//Total//Unread")
#define SN_MESSAGINGVOICEMAILTOTALUNREAD_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingVoiceMail1Unread
// Gets the number of unplayed voice mail messages for line 1.
#define SN_MESSAGINGVOICEMAIL1UNREAD_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGVOICEMAIL1UNREAD_PATH TEXT("System//State//Messages//VMail//Line1//Unread")
#define SN_MESSAGINGVOICEMAIL1UNREAD_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingVoiceMail2Unread
// Gets the number of unplayed voice mail messages for line 2
#define SN_MESSAGINGVOICEMAIL2UNREAD_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGVOICEMAIL2UNREAD_PATH TEXT("System//State//Messages//VMail//Line2//Unread")
#define SN_MESSAGINGVOICEMAIL2UNREAD_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingActiveSyncEmailUnread
// Gets the number of unread ActiveSync e-mail messages.
#define SN_MESSAGINGACTIVESYNCEMAILUNREAD_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGACTIVESYNCEMAILUNREAD_PATH TEXT("System//State//Messages//Sync//Unread")
#define SN_MESSAGINGACTIVESYNCEMAILUNREAD_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingTotalEmailUnread
// Gets the total number of unread e-mail messages from all POP3/IMAP accounts.
#define SN_MESSAGINGTOTALEMAILUNREAD_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGTOTALEMAILUNREAD_PATH TEXT("System//State//Messages//TotalEmail//Unread")
#define SN_MESSAGINGTOTALEMAILUNREAD_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingOtherEmailUnread
// Gets the number of unread e-mail messages from all non-ActiveSync messaging accounts.
#define SN_MESSAGINGOTHEREMAILUNREAD_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGOTHEREMAILUNREAD_PATH TEXT("System//State//Messages//OtherEmail//Unread")
#define SN_MESSAGINGOTHEREMAILUNREAD_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingLastEmailAccountName
// Gets the name of the e-mail account that was last active.
#define SN_MESSAGINGLASTEMAILACCOUNTNAME_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGLASTEMAILACCOUNTNAME_PATH TEXT("System//State//Messages")
#define SN_MESSAGINGLASTEMAILACCOUNTNAME_VALUE TEXT("Last Received Account")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingSmsAccountName
// Gets the name of the SMS messaging account.
#define SN_MESSAGINGSMSACCOUNTNAME_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGSMSACCOUNTNAME_PATH TEXT("System//State//Messages//SMS")
#define SN_MESSAGINGSMSACCOUNTNAME_VALUE TEXT("Account Name")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingMmsAccountName
// Gets the name of the MMS messaging account.
#define SN_MESSAGINGMMSACCOUNTNAME_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGMMSACCOUNTNAME_PATH TEXT("System//State//Messages//MMS")
#define SN_MESSAGINGMMSACCOUNTNAME_VALUE TEXT("Account Name")
 
 
////////////////////////////////////////////////////////////////////////////////
// MessagingActiveSyncAccountName
// Get the name of the Outlook e-mail messaging account.
#define SN_MESSAGINGACTIVESYNCACCOUNTNAME_ROOT HKEY_CURRENT_USER
#define SN_MESSAGINGACTIVESYNCACCOUNTNAME_PATH TEXT("System//State//Messages//Sync")
#define SN_MESSAGINGACTIVESYNCACCOUNTNAME_VALUE TEXT("Account Name")
 
 
////////////////////////////////////////////////////////////////////////////////
// TasksActive
// Gets the number of active tasks.
#define SN_TASKSACTIVE_ROOT HKEY_CURRENT_USER
#define SN_TASKSACTIVE_PATH TEXT("System//State//Tasks")
#define SN_TASKSACTIVE_VALUE TEXT("Active")
 
 
////////////////////////////////////////////////////////////////////////////////
// TasksHighPriority
// Gets the number of high priority tasks that are currently active.
#define SN_TASKSHIGHPRIORITY_ROOT HKEY_CURRENT_USER
#define SN_TASKSHIGHPRIORITY_PATH TEXT("System//State//Tasks")
#define SN_TASKSHIGHPRIORITY_VALUE TEXT("High Priority")
 
 
////////////////////////////////////////////////////////////////////////////////
// TasksDueToday
// Gets the number of active tasks that are due today.
#define SN_TASKSDUETODAY_ROOT HKEY_CURRENT_USER
#define SN_TASKSDUETODAY_PATH TEXT("System//State//Tasks")
#define SN_TASKSDUETODAY_VALUE TEXT("Due Today")
 
 
////////////////////////////////////////////////////////////////////////////////
// TasksOverdue
// Gets the number of overdue tasks.
#define SN_TASKSOVERDUE_ROOT HKEY_CURRENT_USER
#define SN_TASKSOVERDUE_PATH TEXT("System//State//Tasks")
#define SN_TASKSOVERDUE_VALUE TEXT("Overdue")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarNextAppointmentSubject
// Gets the subject of the next Appointment.
#define SN_CALENDARNEXTAPPOINTMENTSUBJECT_ROOT HKEY_CURRENT_USER
#define SN_CALENDARNEXTAPPOINTMENTSUBJECT_PATH TEXT("System//State//Appointments//Next")
#define SN_CALENDARNEXTAPPOINTMENTSUBJECT_VALUE TEXT("Subject")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarNextAppointmentLocation
// Gets the location of the next Appointment.
#define SN_CALENDARNEXTAPPOINTMENTLOCATION_ROOT HKEY_CURRENT_USER
#define SN_CALENDARNEXTAPPOINTMENTLOCATION_PATH TEXT("System//State//Appointments//Next")
#define SN_CALENDARNEXTAPPOINTMENTLOCATION_VALUE TEXT("Location")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarNextAppointmentStart
// Gets the starting time of the next Appointment.
#define SN_CALENDARNEXTAPPOINTMENTSTART_ROOT HKEY_CURRENT_USER
#define SN_CALENDARNEXTAPPOINTMENTSTART_PATH TEXT("System//State//Appointments//Next")
#define SN_CALENDARNEXTAPPOINTMENTSTART_VALUE TEXT("Start Time")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarNextAppointmentEnd
// Gets the ending time of the next Appointment.
#define SN_CALENDARNEXTAPPOINTMENTEND_ROOT HKEY_CURRENT_USER
#define SN_CALENDARNEXTAPPOINTMENTEND_PATH TEXT("System//State//Appointments//Next")
#define SN_CALENDARNEXTAPPOINTMENTEND_VALUE TEXT("End Time")
 
 
////////////////////////////////////////////////////////////////////////////////
// MediaPlayerAlbumArtist
// Gets the album artist's name of the currently playing track in Windows Media Player.
#define SN_MEDIAPLAYERALBUMARTIST_ROOT HKEY_CURRENT_USER
#define SN_MEDIAPLAYERALBUMARTIST_PATH TEXT("System//State//MediaPlayer")
#define SN_MEDIAPLAYERALBUMARTIST_VALUE TEXT("WM/AlbumArtist")
 
 
////////////////////////////////////////////////////////////////////////////////
// MediaPlayerTrackBitrate
// Gets the title of the track currently playing in Windows Media Player. For example, "128Kbps"
#define SN_MEDIAPLAYERTRACKBITRATE_ROOT HKEY_CURRENT_USER
#define SN_MEDIAPLAYERTRACKBITRATE_PATH TEXT("System//State//MediaPlayer")
#define SN_MEDIAPLAYERTRACKBITRATE_VALUE TEXT("Bitrate")
 
 
////////////////////////////////////////////////////////////////////////////////
// MediaPlayerTrackTitle
// Gets the title of the track currently playing in Windows Media Player.
#define SN_MEDIAPLAYERTRACKTITLE_ROOT HKEY_CURRENT_USER
#define SN_MEDIAPLAYERTRACKTITLE_PATH TEXT("System//State//MediaPlayer")
#define SN_MEDIAPLAYERTRACKTITLE_VALUE TEXT("Title")
 
 
////////////////////////////////////////////////////////////////////////////////
// MediaPlayerAlbumTitle
// Gets the album title of the currently playing track in Windows Media Player.
#define SN_MEDIAPLAYERALBUMTITLE_ROOT HKEY_CURRENT_USER
#define SN_MEDIAPLAYERALBUMTITLE_PATH TEXT("System//State//MediaPlayer")
#define SN_MEDIAPLAYERALBUMTITLE_VALUE TEXT("Wm/AlbumTitle")
 
 
////////////////////////////////////////////////////////////////////////////////
// MediaPlayerTrackArtist
// Gets the artist's name of the currently playing track in Windows Media Player.
#define SN_MEDIAPLAYERTRACKARTIST_ROOT HKEY_CURRENT_USER
#define SN_MEDIAPLAYERTRACKARTIST_PATH TEXT("System//State//MediaPlayer")
#define SN_MEDIAPLAYERTRACKARTIST_VALUE TEXT("WM/OriginalArtist")
 
 
////////////////////////////////////////////////////////////////////////////////
// MediaPlayerTrackNumber
// Gets the number of the current track playing in Windows Media Player.
#define SN_MEDIAPLAYERTRACKNUMBER_ROOT HKEY_CURRENT_USER
#define SN_MEDIAPLAYERTRACKNUMBER_PATH TEXT("System//State//MediaPlayer")
#define SN_MEDIAPLAYERTRACKNUMBER_VALUE TEXT("WM/TrackNumber")
 
 
////////////////////////////////////////////////////////////////////////////////
// MediaPlayerTrackGenre
// Gets the genre of the currently playing track in Windows Media Player.
#define SN_MEDIAPLAYERTRACKGENRE_ROOT HKEY_CURRENT_USER
#define SN_MEDIAPLAYERTRACKGENRE_PATH TEXT("System//State//MediaPlayer")
#define SN_MEDIAPLAYERTRACKGENRE_VALUE TEXT("WM/Genre")
 
 
////////////////////////////////////////////////////////////////////////////////
// MediaPlayerTrackTimeElapsed
// Gets the elapsed time (in milliseconds) of the currently playing track in Windows Media Player.
#define SN_MEDIAPLAYERTRACKTIMEELAPSED_ROOT HKEY_CURRENT_USER
#define SN_MEDIAPLAYERTRACKTIMEELAPSED_PATH TEXT("System//State//MediaPlayer")
#define SN_MEDIAPLAYERTRACKTIMEELAPSED_VALUE TEXT("Elapsed")
 
 
////////////////////////////////////////////////////////////////////////////////
// PowerBatteryStrength
// Gets the remaining battery power level, expressed as a percentage of <i>fully charged</i>.
#define SN_POWERBATTERYSTRENGTH_ROOT HKEY_LOCAL_MACHINE
#define SN_POWERBATTERYSTRENGTH_PATH TEXT("System//State//Battery")
#define SN_POWERBATTERYSTRENGTH_VALUE TEXT("Main")
#define SN_POWERBATTERYSTRENGTH_BITMASK 0xFFFF0000

 
////////////////////////////////////////////////////////////////////////////////
// PowerBatteryState
// Gets the current battery state (for example, it is low, and charging). This enumeration allows a bitwise combination of its member values.
#define SN_POWERBATTERYSTATE_ROOT HKEY_LOCAL_MACHINE
#define SN_POWERBATTERYSTATE_PATH TEXT("System//State//Battery")
#define SN_POWERBATTERYSTATE_VALUE TEXT("Main")
#define SN_POWERBATTERYSTATE_BITMASK 0x0000FFFF
 
 
////////////////////////////////////////////////////////////////////////////////
// PowerBatteryBackupStrength
// Gets the remaining backup battery power level, expressed as a percentage of <i>fully charged</i>.
#define SN_POWERBATTERYBACKUPSTRENGTH_ROOT HKEY_LOCAL_MACHINE
#define SN_POWERBATTERYBACKUPSTRENGTH_PATH TEXT("System//State//Battery")
#define SN_POWERBATTERYBACKUPSTRENGTH_VALUE TEXT("Backup")
#define SN_POWERBATTERYBACKUPSTRENGTH_BITMASK 0xFFFF0000
 
 
////////////////////////////////////////////////////////////////////////////////
// PowerBatteryBackupState
// Gets the current backup battery state (for example, it is low, and charging). This enumeration allows a bitwise combination of its member values.
#define SN_POWERBATTERYBACKUPSTATE_ROOT HKEY_LOCAL_MACHINE
#define SN_POWERBATTERYBACKUPSTATE_PATH TEXT("System//State//Battery")
#define SN_POWERBATTERYBACKUPSTATE_VALUE TEXT("Backup")
#define SN_POWERBATTERYBACKUPSTATE_BITMASK 0x0000FFFF
 
 
////////////////////////////////////////////////////////////////////////////////
// Time
// Gets the current time. This Date/Time value updates once per minute.
#define SN_TIME_ROOT HKEY_LOCAL_MACHINE
#define SN_TIME_PATH TEXT("System//State//DateTime")
#define SN_TIME_VALUE TEXT("Time")
 
 
////////////////////////////////////////////////////////////////////////////////
// Date
// Gets the current date. This Date/Time value changes once per day. Monitor this property to perform actions on a daily basis. <b>Note</b>: Do not use <b>Date</b> to get an accurate clock time; instead, use <b>Time</b>.
#define SN_DATE_ROOT HKEY_LOCAL_MACHINE
#define SN_DATE_PATH TEXT("System//State//DateTime")
#define SN_DATE_VALUE TEXT("Date")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneSignalStrength
// Get the phone signal strength, expressed as a percentage of full strength.
#define SN_PHONESIGNALSTRENGTH_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONESIGNALSTRENGTH_PATH TEXT("System//State//Phone")
#define SN_PHONESIGNALSTRENGTH_VALUE TEXT("Signal Strength Raw")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneOperatorName
// Gets the name of the mobile operator (i.e., the mobile phone company, or carrier).
#define SN_PHONEOPERATORNAME_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEOPERATORNAME_PATH TEXT("System//State//Phone")
#define SN_PHONEOPERATORNAME_VALUE TEXT("Current Operator Name")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneTalkingCallerName
// Gets the name of the person you are talking to on the phone. This value is not set when you are talking on a conference call.
#define SN_PHONETALKINGCALLERNAME_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONETALKINGCALLERNAME_PATH TEXT("System//State//Phone")
#define SN_PHONETALKINGCALLERNAME_VALUE TEXT("Caller Name")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneActiveCallCount
// Gets the number of active phone calls.
#define SN_PHONEACTIVECALLCOUNT_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEACTIVECALLCOUNT_PATH TEXT("System//State//Phone")
#define SN_PHONEACTIVECALLCOUNT_VALUE TEXT("Active Call Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneProfileName
// Gets the localized name of the current sound profile. (Smartphone only)
#define SN_PHONEPROFILENAME_ROOT HKEY_CURRENT_USER
#define SN_PHONEPROFILENAME_PATH TEXT("System//State")
#define SN_PHONEPROFILENAME_VALUE TEXT("Profile")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneProfile
// Gets the non-localized name of the current sound profile. For example, "Normal", "Silent", "Car", "Headset", "Loud", "Meeting", or "Speakerphone". (Smartphone only)
#define SN_PHONEPROFILE_ROOT HKEY_CURRENT_USER
#define SN_PHONEPROFILE_PATH TEXT("ControlPanel//Profiles")
#define SN_PHONEPROFILE_VALUE TEXT("ActiveProfile")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneCellBroadcast
// Gets the cell broadcast message
#define SN_PHONECELLBROADCAST_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONECELLBROADCAST_PATH TEXT("System//State//Phone")
#define SN_PHONECELLBROADCAST_VALUE TEXT("Cell Broadcast")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarNextAppointmentHasConflict
// Gets a value indicating whether there is a conflict with the next Appointment.
#define SN_CALENDARNEXTAPPOINTMENTHASCONFLICT_ROOT HKEY_CURRENT_USER
#define SN_CALENDARNEXTAPPOINTMENTHASCONFLICT_PATH TEXT("System//State//Appointments//Next")
#define SN_CALENDARNEXTAPPOINTMENTHASCONFLICT_VALUE TEXT("Conflict")
 
 
////////////////////////////////////////////////////////////////////////////////
// OwnerName
// Gets the mobile device owner's name.
#define SN_OWNERNAME_ROOT HKEY_CURRENT_USER
#define SN_OWNERNAME_PATH TEXT("ControlPanel//Owner")
#define SN_OWNERNAME_VALUE TEXT("Name")
 
 
////////////////////////////////////////////////////////////////////////////////
// OwnerPhoneNumber
// Gets the mobile device owner's phone number.
#define SN_OWNERPHONENUMBER_ROOT HKEY_CURRENT_USER
#define SN_OWNERPHONENUMBER_PATH TEXT("ControlPanel//Owner")
#define SN_OWNERPHONENUMBER_VALUE TEXT("Telephone")
 
 
////////////////////////////////////////////////////////////////////////////////
// OwnerEmail
// Gets the mobile device owner's e-mail address.
#define SN_OWNEREMAIL_ROOT HKEY_CURRENT_USER
#define SN_OWNEREMAIL_PATH TEXT("ControlPanel//Owner")
#define SN_OWNEREMAIL_VALUE TEXT("E-mail")
 
 
////////////////////////////////////////////////////////////////////////////////
// OwnerNotes
// Gets the text notes entered by the owner of the mobile device.
#define SN_OWNERNOTES_ROOT HKEY_CURRENT_USER
#define SN_OWNERNOTES_PATH TEXT("ControlPanel//Owner")
#define SN_OWNERNOTES_VALUE TEXT("Notes")
 
 
////////////////////////////////////////////////////////////////////////////////
// ActiveSyncStatus
// Gets ActiveSync's current synchronization state.
#define SN_ACTIVESYNCSTATUS_ROOT HKEY_LOCAL_MACHINE
#define SN_ACTIVESYNCSTATUS_PATH TEXT("System//State//ActiveSync")
#define SN_ACTIVESYNCSTATUS_VALUE TEXT("Synchronizing")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneMissedCalls
// Gets the number of missed phone calls.
#define SN_PHONEMISSEDCALLS_ROOT HKEY_CURRENT_USER
#define SN_PHONEMISSEDCALLS_PATH TEXT("System//State//Phone")
#define SN_PHONEMISSEDCALLS_VALUE TEXT("Missed Call Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// HeadsetPresent
// Gets a value indicating whether a headset is present
#define SN_HEADSETPRESENT_ROOT HKEY_LOCAL_MACHINE
#define SN_HEADSETPRESENT_PATH TEXT("System//State//Hardware")
#define SN_HEADSETPRESENT_VALUE TEXT("Headset")
 
 
////////////////////////////////////////////////////////////////////////////////
// CarKitPresent
// Gets a value indicating whether a car kit is present
#define SN_CARKITPRESENT_ROOT HKEY_LOCAL_MACHINE
#define SN_CARKITPRESENT_PATH TEXT("System//State//Hardware")
#define SN_CARKITPRESENT_VALUE TEXT("Car Kit")
 
 
////////////////////////////////////////////////////////////////////////////////
// SpeakerPhoneActive
// Gets a value indicating whether the speakerphone is active
#define SN_SPEAKERPHONEACTIVE_ROOT HKEY_LOCAL_MACHINE
#define SN_SPEAKERPHONEACTIVE_PATH TEXT("System//State//Hardware")
#define SN_SPEAKERPHONEACTIVE_VALUE TEXT("Speaker")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneMultiLine
// Gets a value indicating whether the phone supports multiple lines.
#define SN_PHONEMULTILINE_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEMULTILINE_PATH TEXT("System//State//Phone")
#define SN_PHONEMULTILINE_VALUE TEXT("Multiline Capabilities")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneSimFull
// Gets a value indicating whether the Subscriber Identity Module (SIM) memory is full.
#define SN_PHONESIMFULL_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONESIMFULL_PATH TEXT("System//State//Phone")
#define SN_PHONESIMFULL_VALUE TEXT("Status")
#define SN_PHONESIMFULL_BITMASK 1
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneNoSim
// Gets a value indicating whether the Subscriber Identity Module (SIM) is installed in the mobile device.
#define SN_PHONENOSIM_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONENOSIM_PATH TEXT("System//State//Phone")
#define SN_PHONENOSIM_VALUE TEXT("Status")
#define SN_PHONENOSIM_BITMASK 2
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneInvalidSim
// Gets a value indicating whether the Subscriber Identity Module (SIM) is invalid.
#define SN_PHONEINVALIDSIM_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEINVALIDSIM_PATH TEXT("System//State//Phone")
#define SN_PHONEINVALIDSIM_VALUE TEXT("Status")
#define SN_PHONEINVALIDSIM_BITMASK 4
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneBlockedSim
// Gets a value indicating whether the Subscriber Identity Module (SIM) is blocked.
#define SN_PHONEBLOCKEDSIM_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEBLOCKEDSIM_PATH TEXT("System//State//Phone")
#define SN_PHONEBLOCKEDSIM_VALUE TEXT("Status")
#define SN_PHONEBLOCKEDSIM_BITMASK 8
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneRadioOff
// Gets a value indicating whether the phone's radio is turned off.
#define SN_PHONERADIOOFF_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONERADIOOFF_PATH TEXT("System//State//Phone")
#define SN_PHONERADIOOFF_VALUE TEXT("Status")
#define SN_PHONERADIOOFF_BITMASK 16
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneRadioPresent
// Gets a value indicating whether the mobile device has a phone.
#define SN_PHONERADIOPRESENT_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONERADIOPRESENT_PATH TEXT("System//State//Phone")
#define SN_PHONERADIOPRESENT_VALUE TEXT("Status")
#define SN_PHONERADIOPRESENT_BITMASK 32
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneRingerOff
// Gets a value indicating whether the phone's ringer is off (i.e., if it rings and/or vibrates).
#define SN_PHONERINGEROFF_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONERINGEROFF_PATH TEXT("System//State//Phone")
#define SN_PHONERINGEROFF_VALUE TEXT("Status")
#define SN_PHONERINGEROFF_BITMASK 64
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneLine1Selected
// Gets a value indicating whether line 1 is selected.
#define SN_PHONELINE1SELECTED_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONELINE1SELECTED_PATH TEXT("System//State//Phone")
#define SN_PHONELINE1SELECTED_VALUE TEXT("Status")
#define SN_PHONELINE1SELECTED_BITMASK 128
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneLine2Selected
// Gets a value indicating whether line 2 is selected.
#define SN_PHONELINE2SELECTED_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONELINE2SELECTED_PATH TEXT("System//State//Phone")
#define SN_PHONELINE2SELECTED_VALUE TEXT("Status")
#define SN_PHONELINE2SELECTED_BITMASK 256
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneRoaming
// Gets a value indicating whether the phone is currently in roaming mode.
#define SN_PHONEROAMING_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEROAMING_PATH TEXT("System//State//Phone")
#define SN_PHONEROAMING_VALUE TEXT("Status")
#define SN_PHONEROAMING_BITMASK 512
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneCallForwardingOnLine1
// Gets a value indicating whether call forwarding is enabled on line 1.
#define SN_PHONECALLFORWARDINGONLINE1_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONECALLFORWARDINGONLINE1_PATH TEXT("System//State//Phone")
#define SN_PHONECALLFORWARDINGONLINE1_VALUE TEXT("Status")
#define SN_PHONECALLFORWARDINGONLINE1_BITMASK 1024
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneMissedCall
// Gets a value indicating whether there was a new missed call.
#define SN_PHONEMISSEDCALL_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEMISSEDCALL_PATH TEXT("System//State//Phone")
#define SN_PHONEMISSEDCALL_VALUE TEXT("Status")
#define SN_PHONEMISSEDCALL_BITMASK 2048
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneActiveDataCall
// Gets a value indicating whether the phone has an active cellular data connection.
#define SN_PHONEACTIVEDATACALL_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEACTIVEDATACALL_PATH TEXT("System//State//Phone")
#define SN_PHONEACTIVEDATACALL_VALUE TEXT("Status")
#define SN_PHONEACTIVEDATACALL_BITMASK 4096
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneCallBarring
// Gets a value indicating whether the call barring feature is enabled.
#define SN_PHONECALLBARRING_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONECALLBARRING_PATH TEXT("System//State//Phone")
#define SN_PHONECALLBARRING_VALUE TEXT("Status")
#define SN_PHONECALLBARRING_BITMASK 8192
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneCallOnHold
// Gets a value indicating whether a phone call is currently on hold.
#define SN_PHONECALLONHOLD_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONECALLONHOLD_PATH TEXT("System//State//Phone")
#define SN_PHONECALLONHOLD_VALUE TEXT("Status")
#define SN_PHONECALLONHOLD_BITMASK 16384
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneConferenceCall
// Gets a value indicating whether a conference call is currently in progress.
#define SN_PHONECONFERENCECALL_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONECONFERENCECALL_PATH TEXT("System//State//Phone")
#define SN_PHONECONFERENCECALL_VALUE TEXT("Status")
#define SN_PHONECONFERENCECALL_BITMASK 32768
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneIncomingCall
// Gets a value indicating whether there is an incoming (ringing) call.
#define SN_PHONEINCOMINGCALL_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEINCOMINGCALL_PATH TEXT("System//State//Phone")
#define SN_PHONEINCOMINGCALL_VALUE TEXT("Status")
#define SN_PHONEINCOMINGCALL_BITMASK 65536
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneCallCalling
// Gets a value indicating whether the phone is currently attempting to connect an outgoing call.
#define SN_PHONECALLCALLING_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONECALLCALLING_PATH TEXT("System//State//Phone")
#define SN_PHONECALLCALLING_VALUE TEXT("Status")
#define SN_PHONECALLCALLING_BITMASK 131072
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneGprsCoverage
// Gets a value indicating whether the phone currently has GPRS coverage.
#define SN_PHONEGPRSCOVERAGE_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEGPRSCOVERAGE_PATH TEXT("System//State//Phone")
#define SN_PHONEGPRSCOVERAGE_VALUE TEXT("Status")
#define SN_PHONEGPRSCOVERAGE_BITMASK 1048576
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneNoService
// Gets a value indicating whether the phone is not currently connected to a network.
#define SN_PHONENOSERVICE_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONENOSERVICE_PATH TEXT("System//State//Phone")
#define SN_PHONENOSERVICE_VALUE TEXT("Status")
#define SN_PHONENOSERVICE_BITMASK 2097152
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneSearchingForService
// Gets a value indicating whether the phone is currently searching for service on a network.
#define SN_PHONESEARCHINGFORSERVICE_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONESEARCHINGFORSERVICE_PATH TEXT("System//State//Phone")
#define SN_PHONESEARCHINGFORSERVICE_VALUE TEXT("Status")
#define SN_PHONESEARCHINGFORSERVICE_BITMASK 4194304
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneHomeService
// Gets a value indicating whether the phone is currently registered on its home network.
#define SN_PHONEHOMESERVICE_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEHOMESERVICE_PATH TEXT("System//State//Phone")
#define SN_PHONEHOMESERVICE_VALUE TEXT("Status")
#define SN_PHONEHOMESERVICE_BITMASK 8388608
 
 
////////////////////////////////////////////////////////////////////////////////
// Phone1xRttCoverage
// Gets a value indicating whether the phone currently has 1xRTT coverage.
#define SN_PHONE1XRTTCOVERAGE_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONE1XRTTCOVERAGE_PATH TEXT("System//State//Phone")
#define SN_PHONE1XRTTCOVERAGE_VALUE TEXT("Status")
#define SN_PHONE1XRTTCOVERAGE_BITMASK 268435456
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneCallTalking
// Gets a value indicating whether there is currently a phone call in the talking state.
#define SN_PHONECALLTALKING_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONECALLTALKING_PATH TEXT("System//State//Phone")
#define SN_PHONECALLTALKING_VALUE TEXT("Status")
#define SN_PHONECALLTALKING_BITMASK 536870912
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneCallForwardingOnLine2
// Gets a value indicating whether call forwarding is currently active on line 2.
#define SN_PHONECALLFORWARDINGONLINE2_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONECALLFORWARDINGONLINE2_PATH TEXT("System//State//Phone")
#define SN_PHONECALLFORWARDINGONLINE2_VALUE TEXT("Status")
#define SN_PHONECALLFORWARDINGONLINE2_BITMASK 1073741824
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarNextAppointment
// Gets the next Appointment.
#define SN_CALENDARNEXTAPPOINTMENT_ROOT HKEY_CURRENT_USER
#define SN_CALENDARNEXTAPPOINTMENT_PATH TEXT("System//State//Appointments")
#define SN_CALENDARNEXTAPPOINTMENT_VALUE TEXT("Next")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarNextAppointmentBusyStatus
// Gets the user's availability (e.g., Free, Busy, Tenative, Out of Office) status for the next Appointment.
#define SN_CALENDARNEXTAPPOINTMENTBUSYSTATUS_ROOT HKEY_CURRENT_USER
#define SN_CALENDARNEXTAPPOINTMENTBUSYSTATUS_PATH TEXT("System//State//Appointments//Next")
#define SN_CALENDARNEXTAPPOINTMENTBUSYSTATUS_VALUE TEXT("Busy Status")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarNextAppointmentCategories
// Gets the next Appointment's categories.
#define SN_CALENDARNEXTAPPOINTMENTCATEGORIES_ROOT HKEY_CURRENT_USER
#define SN_CALENDARNEXTAPPOINTMENTCATEGORIES_PATH TEXT("System//State//Appointments//Next")
#define SN_CALENDARNEXTAPPOINTMENTCATEGORIES_VALUE TEXT("Categories")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarAppointment
// Gets the current Appointment.
#define SN_CALENDARAPPOINTMENT_ROOT HKEY_CURRENT_USER
#define SN_CALENDARAPPOINTMENT_PATH TEXT("System//State//Appointments")
#define SN_CALENDARAPPOINTMENT_VALUE TEXT("Current")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarAppointmentSubject
// Gets the current Appointment's subject.
#define SN_CALENDARAPPOINTMENTSUBJECT_ROOT HKEY_CURRENT_USER
#define SN_CALENDARAPPOINTMENTSUBJECT_PATH TEXT("System//State//Appointments//Current")
#define SN_CALENDARAPPOINTMENTSUBJECT_VALUE TEXT("Subject")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarAppointmentLocation
// Gets the current Appointment's location.
#define SN_CALENDARAPPOINTMENTLOCATION_ROOT HKEY_CURRENT_USER
#define SN_CALENDARAPPOINTMENTLOCATION_PATH TEXT("System//State//Appointments//Current")
#define SN_CALENDARAPPOINTMENTLOCATION_VALUE TEXT("Location")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarAppointmentStartTime
// Gets the current Appointment's starting time.
#define SN_CALENDARAPPOINTMENTSTARTTIME_ROOT HKEY_CURRENT_USER
#define SN_CALENDARAPPOINTMENTSTARTTIME_PATH TEXT("System//State//Appointments//Current")
#define SN_CALENDARAPPOINTMENTSTARTTIME_VALUE TEXT("Start Time")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarAppointmentEndTime
// Gets the current Appointment's ending time.
#define SN_CALENDARAPPOINTMENTENDTIME_ROOT HKEY_CURRENT_USER
#define SN_CALENDARAPPOINTMENTENDTIME_PATH TEXT("System//State//Appointments//Current")
#define SN_CALENDARAPPOINTMENTENDTIME_VALUE TEXT("End Time")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarAppointmentHasConflict
// Gets a value indicating whether the current Appointment has a scheduling conflict with an existing Appointment.
#define SN_CALENDARAPPOINTMENTHASCONFLICT_ROOT HKEY_CURRENT_USER
#define SN_CALENDARAPPOINTMENTHASCONFLICT_PATH TEXT("System//State//Appointments//Current")
#define SN_CALENDARAPPOINTMENTHASCONFLICT_VALUE TEXT("Conflict")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarAppointmentBusyStatus
// Gets the user's availability (free/busy status) for the time-slot taken by the current Appointment.
#define SN_CALENDARAPPOINTMENTBUSYSTATUS_ROOT HKEY_CURRENT_USER
#define SN_CALENDARAPPOINTMENTBUSYSTATUS_PATH TEXT("System//State//Appointments//Current")
#define SN_CALENDARAPPOINTMENTBUSYSTATUS_VALUE TEXT("Busy Status")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarAppointmentCategories
// Gets the current Appointment's categories.
#define SN_CALENDARAPPOINTMENTCATEGORIES_ROOT HKEY_CURRENT_USER
#define SN_CALENDARAPPOINTMENTCATEGORIES_PATH TEXT("System//State//Appointments//Current")
#define SN_CALENDARAPPOINTMENTCATEGORIES_VALUE TEXT("Categories")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarHomeScreenAppointment
// Gets the Appointment that is currently displayed on the Home Screen.
#define SN_CALENDARHOMESCREENAPPOINTMENT_ROOT HKEY_CURRENT_USER
#define SN_CALENDARHOMESCREENAPPOINTMENT_PATH TEXT("System//State//Appointments")
#define SN_CALENDARHOMESCREENAPPOINTMENT_VALUE TEXT("HomeScreen")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarHomeScreenAppointmentSubject
// Gets the subject of the Appointment that is currently displayed on the Home Screen.
#define SN_CALENDARHOMESCREENAPPOINTMENTSUBJECT_ROOT HKEY_CURRENT_USER
#define SN_CALENDARHOMESCREENAPPOINTMENTSUBJECT_PATH TEXT("System//State//Appointments//HomeScreen")
#define SN_CALENDARHOMESCREENAPPOINTMENTSUBJECT_VALUE TEXT("Subject")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarHomeScreenAppointmentLocation
// Gets the location of the Appointment that is currently displayed on the Home Screen.
#define SN_CALENDARHOMESCREENAPPOINTMENTLOCATION_ROOT HKEY_CURRENT_USER
#define SN_CALENDARHOMESCREENAPPOINTMENTLOCATION_PATH TEXT("System//State//Appointments//HomeScreen")
#define SN_CALENDARHOMESCREENAPPOINTMENTLOCATION_VALUE TEXT("Location")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarHomeScreenAppointmentStartTime
// Gets the starting time of the Appointment that is currently displayed on the Home Screen.
#define SN_CALENDARHOMESCREENAPPOINTMENTSTARTTIME_ROOT HKEY_CURRENT_USER
#define SN_CALENDARHOMESCREENAPPOINTMENTSTARTTIME_PATH TEXT("System//State//Appointments//HomeScreen")
#define SN_CALENDARHOMESCREENAPPOINTMENTSTARTTIME_VALUE TEXT("Start Time")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarHomeScreenAppointmentEndTime
// Gets the ending time of the Appointment that is currently displayed on the Home Screen.
#define SN_CALENDARHOMESCREENAPPOINTMENTENDTIME_ROOT HKEY_CURRENT_USER
#define SN_CALENDARHOMESCREENAPPOINTMENTENDTIME_PATH TEXT("System//State//Appointments//HomeScreen")
#define SN_CALENDARHOMESCREENAPPOINTMENTENDTIME_VALUE TEXT("End Time")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarHomeScreenAppointmentHasConflict
// Gets a value indicating whether the Appointment that is currently displayed on the Home Screen has a scheduling conflict.
#define SN_CALENDARHOMESCREENAPPOINTMENTHASCONFLICT_ROOT HKEY_CURRENT_USER
#define SN_CALENDARHOMESCREENAPPOINTMENTHASCONFLICT_PATH TEXT("System//State//Appointments//HomeScreen")
#define SN_CALENDARHOMESCREENAPPOINTMENTHASCONFLICT_VALUE TEXT("Conflict")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarHomeScreenAppointmentBusyStatus
// Gets the user's availability (free/busy status) for the Appointment displayed on the Home Screen.
#define SN_CALENDARHOMESCREENAPPOINTMENTBUSYSTATUS_ROOT HKEY_CURRENT_USER
#define SN_CALENDARHOMESCREENAPPOINTMENTBUSYSTATUS_PATH TEXT("System//State//Appointments//HomeScreen")
#define SN_CALENDARHOMESCREENAPPOINTMENTBUSYSTATUS_VALUE TEXT("Busy Status")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarHomeScreenAppointmentCategories
// Gets the categories of the Appointment that is currently displayed on the Home Screen.
#define SN_CALENDARHOMESCREENAPPOINTMENTCATEGORIES_ROOT HKEY_CURRENT_USER
#define SN_CALENDARHOMESCREENAPPOINTMENTCATEGORIES_PATH TEXT("System//State//Appointments//HomeScreen")
#define SN_CALENDARHOMESCREENAPPOINTMENTCATEGORIES_VALUE TEXT("Categories")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneIncomingCallerName
// Gets the name of the person who is currently placing the incoming call.
#define SN_PHONEINCOMINGCALLERNAME_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEINCOMINGCALLERNAME_PATH TEXT("System//State//Phone")
#define SN_PHONEINCOMINGCALLERNAME_VALUE TEXT("Incoming Caller Name")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneLastIncomingCallerName
// Gets the name of the last caller to place an incoming call.
#define SN_PHONELASTINCOMINGCALLERNAME_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONELASTINCOMINGCALLERNAME_PATH TEXT("System//State//Phone")
#define SN_PHONELASTINCOMINGCALLERNAME_VALUE TEXT("Last Incoming Caller Name")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneIncomingCallerNumber
// Gets the incoming call's phone number (Caller ID).
#define SN_PHONEINCOMINGCALLERNUMBER_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEINCOMINGCALLERNUMBER_PATH TEXT("System//State//Phone")
#define SN_PHONEINCOMINGCALLERNUMBER_VALUE TEXT("Incoming Caller Number")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneLastIncomingCallerNumber
// Gets the last incoming call's phone number (Caller ID).
#define SN_PHONELASTINCOMINGCALLERNUMBER_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONELASTINCOMINGCALLERNUMBER_PATH TEXT("System//State//Phone")
#define SN_PHONELASTINCOMINGCALLERNUMBER_VALUE TEXT("Last Incoming Caller Number")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneIncomingCallerContactPropertyName
// Gets the name of the property that matches the Caller ID, e.g. "h" for "Home Telephone".
#define SN_PHONEINCOMINGCALLERCONTACTPROPERTYNAME_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEINCOMINGCALLERCONTACTPROPERTYNAME_PATH TEXT("System//State//Phone")
#define SN_PHONEINCOMINGCALLERCONTACTPROPERTYNAME_VALUE TEXT("Incoming Caller PropName")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneLastIncomingCallerContactPropertyName
// Gets the name of the property that matches the last Caller ID, e.g. "h" for "Home Telephone".
#define SN_PHONELASTINCOMINGCALLERCONTACTPROPERTYNAME_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONELASTINCOMINGCALLERCONTACTPROPERTYNAME_PATH TEXT("System//State//Phone")
#define SN_PHONELASTINCOMINGCALLERCONTACTPROPERTYNAME_VALUE TEXT("Last Incoming Caller PropName")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneIncomingCallerContactPropertyID
// Gets the CEPROPID of the property that matches the Caller ID, for example, PIMPR_HOME_TELEPHONE_NUMBER.
#define SN_PHONEINCOMINGCALLERCONTACTPROPERTYID_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEINCOMINGCALLERCONTACTPROPERTYID_PATH TEXT("System//State//Phone")
#define SN_PHONEINCOMINGCALLERCONTACTPROPERTYID_VALUE TEXT("Incoming Caller PropID")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneLastIncomingCallerContactPropertyID
// Gets the CEPROPID of the property that matches the last Caller ID, for example, PIMPR_HOME_TELEPHONE_NUMBER.
#define SN_PHONELASTINCOMINGCALLERCONTACTPROPERTYID_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONELASTINCOMINGCALLERCONTACTPROPERTYID_PATH TEXT("System//State//Phone")
#define SN_PHONELASTINCOMINGCALLERCONTACTPROPERTYID_VALUE TEXT("Last Incoming Caller PropID")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneIncomingCallerContact
// Gets the Contact that matches the Caller ID.
#define SN_PHONEINCOMINGCALLERCONTACT_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONEINCOMINGCALLERCONTACT_PATH TEXT("System//State//Phone")
#define SN_PHONEINCOMINGCALLERCONTACT_VALUE TEXT("Incoming Caller OID")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneLastIncomingCallerContact
// Gets the Contact that matches the last Caller ID.
#define SN_PHONELASTINCOMINGCALLERCONTACT_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONELASTINCOMINGCALLERCONTACT_PATH TEXT("System//State//Phone")
#define SN_PHONELASTINCOMINGCALLERCONTACT_VALUE TEXT("Last Incoming Caller OID")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneTalkingCallerNumber
// Gets the currently connected caller's phone number.
#define SN_PHONETALKINGCALLERNUMBER_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONETALKINGCALLERNUMBER_PATH TEXT("System//State//Phone")
#define SN_PHONETALKINGCALLERNUMBER_VALUE TEXT("Caller Number")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneTalkingCallerContactPropertyName
// Gets the name of the property of the contact who is on the active phone call, e.g. "h" for "Home Telephone".
#define SN_PHONETALKINGCALLERCONTACTPROPERTYNAME_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONETALKINGCALLERCONTACTPROPERTYNAME_PATH TEXT("System//State//Phone")
#define SN_PHONETALKINGCALLERCONTACTPROPERTYNAME_VALUE TEXT("Caller PropName")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneTalkingCallerContactPropertyID
// Gets the CEPROPID of the property of the contact who is on the active phone call, for example, PIMPR_HOME_TELEPHONE_NUMBER.
#define SN_PHONETALKINGCALLERCONTACTPROPERTYID_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONETALKINGCALLERCONTACTPROPERTYID_PATH TEXT("System//State//Phone")
#define SN_PHONETALKINGCALLERCONTACTPROPERTYID_VALUE TEXT("Caller PropID")
 
 
////////////////////////////////////////////////////////////////////////////////
// PhoneTalkingCallerContact
// Gets the contact who is on the active phone call.
#define SN_PHONETALKINGCALLERCONTACT_ROOT HKEY_LOCAL_MACHINE
#define SN_PHONETALKINGCALLERCONTACT_PATH TEXT("System//State//Phone")
#define SN_PHONETALKINGCALLERCONTACT_VALUE TEXT("Caller OID")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsCount
// Gets a value indicating the number of connections that are currently connected.
#define SN_CONNECTIONSCOUNT_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSCOUNT_PATH TEXT("System//State//Connections")
#define SN_CONNECTIONSCOUNT_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsBluetoothCount
// Gets a value indicating the number of Bluetooth connections that are currently connected.
#define SN_CONNECTIONSBLUETOOTHCOUNT_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSBLUETOOTHCOUNT_PATH TEXT("System//State//Connections//Bluetooth")
#define SN_CONNECTIONSBLUETOOTHCOUNT_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsBluetoothDescriptions
// Gets a semicolon delimited string containing the description of each of the Bluetooth connections.
#define SN_CONNECTIONSBLUETOOTHDESCRIPTIONS_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSBLUETOOTHDESCRIPTIONS_PATH TEXT("System//State//Connections//Bluetooth")
#define SN_CONNECTIONSBLUETOOTHDESCRIPTIONS_VALUE TEXT("Descriptions")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsCellularCount
// Gets a value indicating the number of cellular connections that are currently connected.
#define SN_CONNECTIONSCELLULARCOUNT_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSCELLULARCOUNT_PATH TEXT("System//State//Connections//Cellular")
#define SN_CONNECTIONSCELLULARCOUNT_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsCellularDescriptions
// Gets a semicolon delimited string containing the description of each cellular connection.
#define SN_CONNECTIONSCELLULARDESCRIPTIONS_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSCELLULARDESCRIPTIONS_PATH TEXT("System//State//Connections//Cellular")
#define SN_CONNECTIONSCELLULARDESCRIPTIONS_VALUE TEXT("Descriptions")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsNetworkCount
// Gets a value indicating the number of network connections that are currently connected.
#define SN_CONNECTIONSNETWORKCOUNT_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSNETWORKCOUNT_PATH TEXT("System//State//Connections//Network")
#define SN_CONNECTIONSNETWORKCOUNT_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsNetworkDescriptions
// Gets a semicolon delimited string containing the description of each network connection.
#define SN_CONNECTIONSNETWORKDESCRIPTIONS_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSNETWORKDESCRIPTIONS_PATH TEXT("System//State//Connections//Network")
#define SN_CONNECTIONSNETWORKDESCRIPTIONS_VALUE TEXT("Descriptions")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsNetworkAdapters
// Gets a semicolon delimited string containing the adapter name of each network connection.
#define SN_CONNECTIONSNETWORKADAPTERS_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSNETWORKADAPTERS_PATH TEXT("System//State//Connections//Network")
#define SN_CONNECTIONSNETWORKADAPTERS_VALUE TEXT("Adapters")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsDesktopCount
// Gets a value indicating the number of desktop connections that are currently connected.
#define SN_CONNECTIONSDESKTOPCOUNT_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSDESKTOPCOUNT_PATH TEXT("System//State//Connections//Desktop")
#define SN_CONNECTIONSDESKTOPCOUNT_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsDesktopDescriptions
// Gets a semicolon delimited string containing the description of each desktop connection.
#define SN_CONNECTIONSDESKTOPDESCRIPTIONS_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSDESKTOPDESCRIPTIONS_PATH TEXT("System//State//Connections//Desktop")
#define SN_CONNECTIONSDESKTOPDESCRIPTIONS_VALUE TEXT("Descriptions")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsProxyCount
// Gets a value indicating the number of network connections that are currently connected.
#define SN_CONNECTIONSPROXYCOUNT_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSPROXYCOUNT_PATH TEXT("System//State//Connections//Proxy")
#define SN_CONNECTIONSPROXYCOUNT_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsProxyDescriptions
// Gets a semicolon delimited string containing the description of each proxy connection.
#define SN_CONNECTIONSPROXYDESCRIPTIONS_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSPROXYDESCRIPTIONS_PATH TEXT("System//State//Connections//Proxy")
#define SN_CONNECTIONSPROXYDESCRIPTIONS_VALUE TEXT("Descriptions")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsModemCount
// Gets a value indicating the number of modem connections that are currently connected.
#define SN_CONNECTIONSMODEMCOUNT_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSMODEMCOUNT_PATH TEXT("System//State//Connections//Modem")
#define SN_CONNECTIONSMODEMCOUNT_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsModemDescriptions
// Gets a semicolon delimited string containing the description of each modem connection.
#define SN_CONNECTIONSMODEMDESCRIPTIONS_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSMODEMDESCRIPTIONS_PATH TEXT("System//State//Connections//Modem")
#define SN_CONNECTIONSMODEMDESCRIPTIONS_VALUE TEXT("Descriptions")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsUnknownCount
// Gets a value indicating the number of connections of unknown type that are currently connected.
#define SN_CONNECTIONSUNKNOWNCOUNT_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSUNKNOWNCOUNT_PATH TEXT("System//State//Connections//Unknown")
#define SN_CONNECTIONSUNKNOWNCOUNT_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsUnknownDescriptions
// Gets a semicolon delimited string containing the description of each connections of unknown type.
#define SN_CONNECTIONSUNKNOWNDESCRIPTIONS_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSUNKNOWNDESCRIPTIONS_PATH TEXT("System//State//Connections//Unknown")
#define SN_CONNECTIONSUNKNOWNDESCRIPTIONS_VALUE TEXT("Descriptions")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsVpnCount
// Gets a value indicating the number of virtual private network connections that are currently connected.
#define SN_CONNECTIONSVPNCOUNT_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSVPNCOUNT_PATH TEXT("System//State//Connections//Vpn")
#define SN_CONNECTIONSVPNCOUNT_VALUE TEXT("Count")
 
 
////////////////////////////////////////////////////////////////////////////////
// ConnectionsVpnDescriptions
// Gets a semicolon delimited string containing the description of each virtual private network connection.
#define SN_CONNECTIONSVPNDESCRIPTIONS_ROOT HKEY_LOCAL_MACHINE
#define SN_CONNECTIONSVPNDESCRIPTIONS_PATH TEXT("System//State//Connections//Vpn")
#define SN_CONNECTIONSVPNDESCRIPTIONS_VALUE TEXT("Descriptions")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarEvent
// Gets the current "All Day Event" Appointment.
#define SN_CALENDAREVENT_ROOT HKEY_CURRENT_USER
#define SN_CALENDAREVENT_PATH TEXT("System//State//Appointments")
#define SN_CALENDAREVENT_VALUE TEXT("Event")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarEventSubject
// Gets the subject of the current "All Day Event" Appointment.
#define SN_CALENDAREVENTSUBJECT_ROOT HKEY_CURRENT_USER
#define SN_CALENDAREVENTSUBJECT_PATH TEXT("System//State//Appointments//Event")
#define SN_CALENDAREVENTSUBJECT_VALUE TEXT("Subject")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarEventLocation
// Gets the location of the current "All Day Event" Appointment.
#define SN_CALENDAREVENTLOCATION_ROOT HKEY_CURRENT_USER
#define SN_CALENDAREVENTLOCATION_PATH TEXT("System//State//Appointments//Event")
#define SN_CALENDAREVENTLOCATION_VALUE TEXT("Location")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarEventStartTime
// Gets the starting time of the current "All Day Event" Appointment. This will be the starting day of an Appointment Event that spans multiple days.
#define SN_CALENDAREVENTSTARTTIME_ROOT HKEY_CURRENT_USER
#define SN_CALENDAREVENTSTARTTIME_PATH TEXT("System//State//Appointments//Event")
#define SN_CALENDAREVENTSTARTTIME_VALUE TEXT("Start Time")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarEventEndTime
// Gets the ending time of the current "All Day Event" Appointment. This will be the starting day of an Appointment Event that spans multiple days.
#define SN_CALENDAREVENTENDTIME_ROOT HKEY_CURRENT_USER
#define SN_CALENDAREVENTENDTIME_PATH TEXT("System//State//Appointments//Event")
#define SN_CALENDAREVENTENDTIME_VALUE TEXT("End Time")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarEventHasConflict
// Gets a value indicating whether the user's availability (free/busy) status conflicts with the current "All Day Event".
#define SN_CALENDAREVENTHASCONFLICT_ROOT HKEY_CURRENT_USER
#define SN_CALENDAREVENTHASCONFLICT_PATH TEXT("System//State//Appointments//Event")
#define SN_CALENDAREVENTHASCONFLICT_VALUE TEXT("Conflict")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarEventBusyStatus
// Gets the user's availability (free/busy status) for the current "All Day Event".
#define SN_CALENDAREVENTBUSYSTATUS_ROOT HKEY_CURRENT_USER
#define SN_CALENDAREVENTBUSYSTATUS_PATH TEXT("System//State//Appointments//Event")
#define SN_CALENDAREVENTBUSYSTATUS_VALUE TEXT("Busy Status")
 
 
////////////////////////////////////////////////////////////////////////////////
// CalendarEventCategories
// Gets the categories for the current "All Day Event".
#define SN_CALENDAREVENTCATEGORIES_ROOT HKEY_CURRENT_USER
#define SN_CALENDAREVENTCATEGORIES_PATH TEXT("System//State//Appointments//Event")
#define SN_CALENDAREVENTCATEGORIES_VALUE TEXT("Categories")
 
 
 

#下面程序运行时报错: C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\utils\generic.py Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\utils\generic.py", line 34, in <module> from ..utils import logging ImportError: attempted relative import with no known parent package 进程已结束,退出代码为 1 ------------------------------------------------------------------------------------------------ import inspect import json import os import tempfile import warnings from collections import OrderedDict, UserDict, defaultdict from collections.abc import Iterable, MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import dataclass, fields, is_dataclass from enum import Enum from functools import partial, wraps from typing import Any, Callable, ContextManager, Optional, TypedDict import numpy as np from packaging import version from ..utils import logging from .import_utils import ( get_torch_version, is_flax_available, is_mlx_available, is_tf_available, is_torch_available, is_torch_fx_proxy, requires, ) _CAN_RECORD_REGISTRY = {} logger = logging.get_logger(__name__) if is_torch_available(): # required for @can_return_tuple decorator to work with torchdynamo import torch # noqa: F401 from ..model_debugging_utils import model_addition_debugger_context class cached_property(property): """ Descriptor that mimics @property but caches output in member variable. From tensorflow_datasets Built-in in functools from Python 3.8. """ def __get__(self, obj, objtype=None): # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError("unreadable attribute") attr = "__cached_" + self.fget.__name__ cached = getattr(obj, attr, None) if cached is None: cached = self.fget(obj) setattr(obj, attr, cached) return cached # vendored from distutils.util def strtobool(val): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f"invalid truth value {val!r}") def infer_framework_from_repr(x): """ Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the frameworks in a smart order, without the need to import the frameworks). """ representation = str(type(x)) if representation.startswith("<class 'torch."): return "pt" elif representation.startswith("<class 'tensorflow."): return "tf" elif representation.startswith("<class 'jax"): return "jax" elif representation.startswith("<class 'numpy."): return "np" elif representation.startswith("<class 'mlx."): return "mlx" def _get_frameworks_and_test_func(x): """ Returns an (ordered since we are in Python 3.7+) dictionary framework to test function, which places the framework we can guess from the repr first, then Numpy, then the others. """ framework_to_test = { "pt": is_torch_tensor, "tf": is_tf_tensor, "jax": is_jax_tensor, "np": is_numpy_array, "mlx": is_mlx_array, } preferred_framework = infer_framework_from_repr(x) # We will test this one first, then numpy, then the others. frameworks = [] if preferred_framework is None else [preferred_framework] if preferred_framework != "np": frameworks.append("np") frameworks.extend([f for f in framework_to_test if f not in [preferred_framework, "np"]]) return {f: framework_to_test[f] for f in frameworks} def is_tensor(x): """ Tests if `x` is a `torch.Tensor`, `tf.Tensor`, `jaxlib.xla_extension.DeviceArray`, `np.ndarray` or `mlx.array` in the order defined by `infer_framework_from_repr` """ # This gives us a smart order to test the frameworks with the corresponding tests. framework_to_test_func = _get_frameworks_and_test_func(x) for test_func in framework_to_test_func.values(): if test_func(x): return True # Tracers if is_torch_fx_proxy(x): return True if is_flax_available(): from jax.core import Tracer if isinstance(x, Tracer): return True return False def _is_numpy(x): return isinstance(x, np.ndarray) def is_numpy_array(x): """ Tests if `x` is a numpy array or not. """ return _is_numpy(x) def _is_torch(x): import torch return isinstance(x, torch.Tensor) def is_torch_tensor(x): """ Tests if `x` is a torch tensor or not. Safe to call even if torch is not installed. """ return False if not is_torch_available() else _is_torch(x) def _is_torch_device(x): import torch return isinstance(x, torch.device) def is_torch_device(x): """ Tests if `x` is a torch device or not. Safe to call even if torch is not installed. """ return False if not is_torch_available() else _is_torch_device(x) def _is_torch_dtype(x): import torch if isinstance(x, str): if hasattr(torch, x): x = getattr(torch, x) else: return False return isinstance(x, torch.dtype) def is_torch_dtype(x): """ Tests if `x` is a torch dtype or not. Safe to call even if torch is not installed. """ return False if not is_torch_available() else _is_torch_dtype(x) def _is_tensorflow(x): import tensorflow as tf return isinstance(x, tf.Tensor) def is_tf_tensor(x): """ Tests if `x` is a tensorflow tensor or not. Safe to call even if tensorflow is not installed. """ return False if not is_tf_available() else _is_tensorflow(x) def _is_tf_symbolic_tensor(x): import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(tf, "is_symbolic_tensor"): return tf.is_symbolic_tensor(x) return isinstance(x, tf.Tensor) def is_tf_symbolic_tensor(x): """ Tests if `x` is a tensorflow symbolic tensor or not (ie. not eager). Safe to call even if tensorflow is not installed. """ return False if not is_tf_available() else _is_tf_symbolic_tensor(x) def _is_jax(x): import jax.numpy as jnp # noqa: F811 return isinstance(x, jnp.ndarray) def is_jax_tensor(x): """ Tests if `x` is a Jax tensor or not. Safe to call even if jax is not installed. """ return False if not is_flax_available() else _is_jax(x) def _is_mlx(x): import mlx.core as mx return isinstance(x, mx.array) def is_mlx_array(x): """ Tests if `x` is a mlx array or not. Safe to call even when mlx is not installed. """ return False if not is_mlx_available() else _is_mlx(x) def to_py_obj(obj): """ Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list. """ if isinstance(obj, (int, float)): return obj elif isinstance(obj, (dict, UserDict)): return {k: to_py_obj(v) for k, v in obj.items()} elif isinstance(obj, (list, tuple)): try: arr = np.array(obj) if np.issubdtype(arr.dtype, np.integer) or np.issubdtype(arr.dtype, np.floating): return arr.tolist() except Exception: pass return [to_py_obj(o) for o in obj] framework_to_py_obj = { "pt": lambda obj: obj.tolist(), "tf": lambda obj: obj.numpy().tolist(), "jax": lambda obj: np.asarray(obj).tolist(), "np": lambda obj: obj.tolist(), } # This gives us a smart order to test the frameworks with the corresponding tests. framework_to_test_func = _get_frameworks_and_test_func(obj) for framework, test_func in framework_to_test_func.items(): if test_func(obj): return framework_to_py_obj[framework](obj) # tolist also works on 0d np arrays if isinstance(obj, np.number): return obj.tolist() else: return obj def to_numpy(obj): """ Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a Numpy array. """ framework_to_numpy = { "pt": lambda obj: obj.detach().cpu().numpy(), "tf": lambda obj: obj.numpy(), "jax": lambda obj: np.asarray(obj), "np": lambda obj: obj, } if isinstance(obj, (dict, UserDict)): return {k: to_numpy(v) for k, v in obj.items()} elif isinstance(obj, (list, tuple)): return np.array(obj) # This gives us a smart order to test the frameworks with the corresponding tests. framework_to_test_func = _get_frameworks_and_test_func(obj) for framework, test_func in framework_to_test_func.items(): if test_func(obj): return framework_to_numpy[framework](obj) return obj class ModelOutput(OrderedDict): """ Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular python dictionary. <Tip warning={true}> You can't unpack a `ModelOutput` directly. Use the [`~utils.ModelOutput.to_tuple`] method to convert it to a tuple before. </Tip> """ def __init_subclass__(cls) -> None: """Register subclasses as pytree nodes. This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with `static_graph=True` with modules that output `ModelOutput` subclasses. """ if is_torch_available(): if version.parse(get_torch_version()) >= version.parse("2.2"): from torch.utils._pytree import register_pytree_node register_pytree_node( cls, _model_output_flatten, partial(_model_output_unflatten, output_type=cls), serialized_type_name=f"{cls.__module__}.{cls.__name__}", ) else: from torch.utils._pytree import _register_pytree_node _register_pytree_node( cls, _model_output_flatten, partial(_model_output_unflatten, output_type=cls), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Subclasses of ModelOutput must use the @dataclass decorator # This check is done in __init__ because the @dataclass decorator operates after __init_subclass__ # issubclass() would return True for issubclass(ModelOutput, ModelOutput) when False is needed # Just need to check that the current class is not ModelOutput is_modeloutput_subclass = self.__class__ != ModelOutput if is_modeloutput_subclass and not is_dataclass(self): raise TypeError( f"{self.__module__}.{self.__class__.__name__} is not a dataclass." " This is a subclass of ModelOutput and so must use the @dataclass decorator." ) def __post_init__(self): """Check the ModelOutput dataclass. Only occurs if @dataclass decorator has been used. """ class_fields = fields(self) # Safety and consistency checks if not len(class_fields): raise ValueError(f"{self.__class__.__name__} has no fields.") if not all(field.default is None for field in class_fields[1:]): raise ValueError(f"{self.__class__.__name__} should not have more than one required field.") first_field = getattr(self, class_fields[0].name) other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:]) if other_fields_are_none and not is_tensor(first_field): if isinstance(first_field, dict): iterator = first_field.items() first_field_iterator = True else: try: iterator = iter(first_field) first_field_iterator = True except TypeError: first_field_iterator = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(iterator): if not isinstance(element, (list, tuple)) or len(element) != 2 or not isinstance(element[0], str): if idx == 0: # If we do not have an iterator of key/values, set it as attribute self[class_fields[0].name] = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f"Cannot set key/value for {element}. It needs to be a tuple (key, value)." ) break setattr(self, element[0], element[1]) if element[1] is not None: self[element[0]] = element[1] elif first_field is not None: self[class_fields[0].name] = first_field else: for field in class_fields: v = getattr(self, field.name) if v is not None: self[field.name] = v def __delitem__(self, *args, **kwargs): raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.") def setdefault(self, *args, **kwargs): raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.") def pop(self, *args, **kwargs): raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.") def update(self, *args, **kwargs): raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.") def __getitem__(self, k): if isinstance(k, str): inner_dict = dict(self.items()) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__(self, name, value): if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(name, value) super().__setattr__(name, value) def __setitem__(self, key, value): # Will raise a KeyException if needed super().__setitem__(key, value) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(key, value) def __reduce__(self): if not is_dataclass(self): return super().__reduce__() callable, _args, *remaining = super().__reduce__() args = tuple(getattr(self, field.name) for field in fields(self)) return callable, args, *remaining def to_tuple(self) -> tuple[Any]: """ Convert self to a tuple containing all the attributes/keys that are not `None`. """ return tuple(self[k] for k in self.keys()) if is_torch_available(): import torch.utils._pytree as _torch_pytree def _model_output_flatten(output: ModelOutput) -> tuple[list[Any], "_torch_pytree.Context"]: return list(output.values()), list(output.keys()) def _model_output_unflatten( values: Iterable[Any], context: "_torch_pytree.Context", output_type=None, ) -> ModelOutput: return output_type(**dict(zip(context, values))) if version.parse(get_torch_version()) >= version.parse("2.2"): _torch_pytree.register_pytree_node( ModelOutput, _model_output_flatten, partial(_model_output_unflatten, output_type=ModelOutput), serialized_type_name=f"{ModelOutput.__module__}.{ModelOutput.__name__}", ) else: _torch_pytree._register_pytree_node( ModelOutput, _model_output_flatten, partial(_model_output_unflatten, output_type=ModelOutput), ) class ExplicitEnum(str, Enum): """ Enum with more explicit error message for missing values. """ @classmethod def _missing_(cls, value): raise ValueError( f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}" ) class PaddingStrategy(ExplicitEnum): """ Possible values for the `padding` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an IDE. """ LONGEST = "longest" MAX_LENGTH = "max_length" DO_NOT_PAD = "do_not_pad" class TensorType(ExplicitEnum): """ Possible values for the `return_tensors` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an IDE. """ PYTORCH = "pt" TENSORFLOW = "tf" NUMPY = "np" JAX = "jax" MLX = "mlx" class ContextManagers: """ Wrapper for `contextlib.ExitStack` which enters a collection of context managers. Adaptation of `ContextManagers` in the `fastcore` library. """ def __init__(self, context_managers: list[ContextManager]): self.context_managers = context_managers self.stack = ExitStack() def __enter__(self): for context_manager in self.context_managers: self.stack.enter_context(context_manager) def __exit__(self, *args, **kwargs): self.stack.__exit__(*args, **kwargs) def can_return_loss(model_class): """ Check if a given model can return loss. Args: model_class (`type`): The class of the model. """ framework = infer_framework(model_class) if framework == "tf": signature = inspect.signature(model_class.call) # TensorFlow models elif framework == "pt": signature = inspect.signature(model_class.forward) # PyTorch models else: signature = inspect.signature(model_class.__call__) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def find_labels(model_class): """ Find the labels used by a given model. Args: model_class (`type`): The class of the model. """ model_name = model_class.__name__ framework = infer_framework(model_class) if framework == "tf": signature = inspect.signature(model_class.call) # TensorFlow models elif framework == "pt": signature = inspect.signature(model_class.forward) # PyTorch models else: signature = inspect.signature(model_class.__call__) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."): """Flatten a nested dict into a single level dict.""" def _flatten_dict(d, parent_key="", delimiter="."): for k, v in d.items(): key = str(parent_key) + delimiter + str(k) if parent_key else k if v and isinstance(v, MutableMapping): yield from flatten_dict(v, key, delimiter=delimiter).items() else: yield key, v return dict(_flatten_dict(d, parent_key, delimiter)) @contextmanager def working_or_temp_dir(working_dir, use_temp_dir: bool = False): if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def transpose(array, axes=None): """ Framework-agnostic version of `numpy.transpose` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.transpose(array, axes=axes) elif is_torch_tensor(array): return array.T if axes is None else array.permute(*axes) elif is_tf_tensor(array): import tensorflow as tf return tf.transpose(array, perm=axes) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.transpose(array, axes=axes) else: raise ValueError(f"Type not supported for transpose: {type(array)}.") def reshape(array, newshape): """ Framework-agnostic version of `numpy.reshape` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.reshape(array, newshape) elif is_torch_tensor(array): return array.reshape(*newshape) elif is_tf_tensor(array): import tensorflow as tf return tf.reshape(array, newshape) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.reshape(array, newshape) else: raise ValueError(f"Type not supported for reshape: {type(array)}.") def squeeze(array, axis=None): """ Framework-agnostic version of `numpy.squeeze` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.squeeze(array, axis=axis) elif is_torch_tensor(array): return array.squeeze() if axis is None else array.squeeze(dim=axis) elif is_tf_tensor(array): import tensorflow as tf return tf.squeeze(array, axis=axis) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.squeeze(array, axis=axis) else: raise ValueError(f"Type not supported for squeeze: {type(array)}.") def expand_dims(array, axis): """ Framework-agnostic version of `numpy.expand_dims` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.expand_dims(array, axis) elif is_torch_tensor(array): return array.unsqueeze(dim=axis) elif is_tf_tensor(array): import tensorflow as tf return tf.expand_dims(array, axis=axis) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.expand_dims(array, axis=axis) else: raise ValueError(f"Type not supported for expand_dims: {type(array)}.") def tensor_size(array): """ Framework-agnostic version of `numpy.size` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.size(array) elif is_torch_tensor(array): return array.numel() elif is_tf_tensor(array): import tensorflow as tf return tf.size(array) elif is_jax_tensor(array): return array.size else: raise ValueError(f"Type not supported for tensor_size: {type(array)}.") def infer_framework(model_class): """ Infers the framework of a given model without using isinstance(), because we cannot guarantee that the relevant classes are imported or available. """ for base_class in inspect.getmro(model_class): module = base_class.__module__ name = base_class.__name__ if module.startswith("tensorflow") or module.startswith("keras") or name == "TFPreTrainedModel": return "tf" elif module.startswith("torch") or name == "PreTrainedModel": return "pt" elif module.startswith("flax") or module.startswith("jax") or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f"Could not infer framework from class {model_class}.") def torch_int(x): """ Casts an input to a torch int64 tensor if we are in a tracing context, otherwise to a Python int. """ if not is_torch_available(): return int(x) import torch return x.to(torch.int64) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x) def torch_float(x): """ Casts an input to a torch float32 tensor if we are in a tracing context, otherwise to a Python float. """ if not is_torch_available(): return int(x) import torch return x.to(torch.float32) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x) def filter_out_non_signature_kwargs(extra: Optional[list] = None): """ Decorator to filter out named arguments that are not in the function signature. This decorator ensures that only the keyword arguments that match the function's signature, or are specified in the `extra` list, are passed to the function. Any additional keyword arguments are filtered out and a warning is issued. Parameters: extra (`Optional[list]`, *optional*): A list of extra keyword argument names that are allowed even if they are not in the function's signature. Returns: Callable: A decorator that wraps the function and filters out invalid keyword arguments. Example usage: ```python @filter_out_non_signature_kwargs(extra=["allowed_extra_arg"]) def my_function(arg1, arg2, **kwargs): print(arg1, arg2, kwargs) my_function(arg1=1, arg2=2, allowed_extra_arg=3, invalid_arg=4) # This will print: 1 2 {"allowed_extra_arg": 3} # And issue a warning: "The following named arguments are not valid for `my_function` and were ignored: 'invalid_arg'" ``` """ extra = extra or [] extra_params_to_pass = set(extra) def decorator(func): sig = inspect.signature(func) function_named_args = set(sig.parameters.keys()) valid_kwargs_to_pass = function_named_args.union(extra_params_to_pass) # Required for better warning message is_instance_method = "self" in function_named_args is_class_method = "cls" in function_named_args # Mark function as decorated func._filter_out_non_signature_kwargs = True @wraps(func) def wrapper(*args, **kwargs): valid_kwargs = {} invalid_kwargs = {} for k, v in kwargs.items(): if k in valid_kwargs_to_pass: valid_kwargs[k] = v else: invalid_kwargs[k] = v if invalid_kwargs: invalid_kwargs_names = [f"'{k}'" for k in invalid_kwargs] invalid_kwargs_names = ", ".join(invalid_kwargs_names) # Get the class name for better warning message if is_instance_method: cls_prefix = args[0].__class__.__name__ + "." elif is_class_method: cls_prefix = args[0].__name__ + "." else: cls_prefix = "" warnings.warn( f"The following named arguments are not valid for `{cls_prefix}{func.__name__}`" f" and were ignored: {invalid_kwargs_names}", UserWarning, stacklevel=2, ) return func(*args, **valid_kwargs) return wrapper return decorator class TransformersKwargs(TypedDict, total=False): """ Keyword arguments to be passed to the loss function Attributes: num_items_in_batch (`Optional[torch.Tensor]`, *optional*): Number of items in the batch. It is recommended to pass it when you are doing gradient accumulation. output_hidden_states (`Optional[bool]`, *optional*): Most of the models support outputing all hidden states computed during the forward pass. output_attentions (`Optional[bool]`, *optional*): Turn this on to return the intermediary attention scores. output_router_logits (`Optional[bool]`, *optional*): For MoE models, this allows returning the router logits to compute the loss. cumulative_seqlens_q (`torch.LongTensor`, *optional*) Gets cumulative sequence length for query state. cumulative_seqlens_k (`torch.LongTensor`, *optional*) Gets cumulative sequence length for key state. max_length_q (`int`, *optional*): Maximum sequence length for query state. max_length_k (`int`, *optional*): Maximum sequence length for key state. """ num_items_in_batch: Optional["torch.Tensor"] output_hidden_states: Optional[bool] output_attentions: Optional[bool] output_router_logits: Optional[bool] cumulative_seqlens_q: Optional["torch.LongTensor"] cumulative_seqlens_k: Optional["torch.LongTensor"] max_length_q: Optional[int] max_length_k: Optional[int] def is_timm_config_dict(config_dict: dict[str, Any]) -> bool: """Checks whether a config dict is a timm config dict.""" return "pretrained_cfg" in config_dict def is_timm_local_checkpoint(pretrained_model_path: str) -> bool: """ Checks whether a checkpoint is a timm model checkpoint. """ if pretrained_model_path is None: return False # in case it's Path, not str pretrained_model_path = str(pretrained_model_path) is_file = os.path.isfile(pretrained_model_path) is_dir = os.path.isdir(pretrained_model_path) # pretrained_model_path is a file if is_file and pretrained_model_path.endswith(".json"): with open(pretrained_model_path) as f: config_dict = json.load(f) return is_timm_config_dict(config_dict) # pretrained_model_path is a directory with a config.json if is_dir and os.path.exists(os.path.join(pretrained_model_path, "config.json")): with open(os.path.join(pretrained_model_path, "config.json")) as f: config_dict = json.load(f) return is_timm_config_dict(config_dict) return False def set_attribute_for_modules(module: "torch.nn.Module", key: str, value: Any): """ Set a value to a module and all submodules. """ setattr(module, key, value) for submodule in module.children(): set_attribute_for_modules(submodule, key, value) def del_attribute_from_modules(module: "torch.nn.Module", key: str): """ Delete a value from a module and all submodules. """ # because we might remove it previously in case it's a shared module, e.g. activation function if hasattr(module, key): delattr(module, key) for submodule in module.children(): del_attribute_from_modules(submodule, key) def can_return_tuple(func): """ Decorator to wrap model method, to call output.to_tuple() if return_dict=False passed as a kwarg or use_return_dict=False is set in the config. Note: output.to_tuple() convert output to tuple skipping all `None` values. """ @wraps(func) def wrapper(self, *args, **kwargs): return_dict = self.config.return_dict if hasattr(self, "config") else True return_dict_passed = kwargs.pop("return_dict", return_dict) if return_dict_passed is not None: return_dict = return_dict_passed output = func(self, *args, **kwargs) if not return_dict and not isinstance(output, tuple): output = output.to_tuple() return output return wrapper # if is_torch_available(): # @torch._dynamo.disable @dataclass @requires(backends=("torch",)) class OutputRecorder: """ Configuration for recording outputs from a model via hooks. Attributes: target_class (Type): The class (e.g., nn.Module) to which the hook will be attached. index (Optional[int]): If the output is a tuple/list, optionally record only at a specific index. layer_name (Optional[str]): Name of the submodule to target (if needed), e.g., "transformer.layer.3.attn". class_name (Optional[str]): Name of the class to which the hook will be attached. Could be the suffix of class name in some cases. """ target_class: "type[torch.nn.Module]" index: Optional[int] = 0 layer_name: Optional[str] = None class_name: Optional[str] = None def check_model_inputs(func): """ Decorator to intercept specific layer outputs without using hooks. Compatible with torch.compile (Dynamo tracing). """ @wraps(func) def wrapper(self, *args, **kwargs): use_cache = kwargs.get("use_cache") if use_cache is None: use_cache = getattr(self.config, "use_cache", False) return_dict = kwargs.pop("return_dict", None) if return_dict is None: return_dict = getattr(self.config, "return_dict", True) if getattr(self, "gradient_checkpointing", False) and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False kwargs["use_cache"] = use_cache all_args = kwargs.copy() if "kwargs" in all_args: for k, v in all_args["kwargs"].items(): all_args[k] = v capture_flags = _CAN_RECORD_REGISTRY.get(str(self.__class__), {}) # there is a weak ref for executorch recordable_keys = { f"output_{k}": all_args.get( f"output_{k}", getattr( self.config, f"output_{k}", all_args.get("output_attentions", getattr(self.config, "output_attentions", False)), ), ) for k in capture_flags } collected_outputs = defaultdict(tuple) monkey_patched_layers = [] def make_capture_wrapper(module, orig_forward, key, index): @wraps(orig_forward) def wrapped_forward(*args, **kwargs): if key == "hidden_states" and len(collected_outputs[key]) == 0: collected_outputs[key] += (args[0],) if kwargs.get("debug_io", False): with model_addition_debugger_context( module, kwargs.get("debug_io_dir", "~/model_debug"), kwargs.get("prune_layers") ): output = orig_forward(*args, **kwargs) else: output = orig_forward(*args, **kwargs) if not isinstance(output, tuple): collected_outputs[key] += (output,) elif output[index] is not None: if key not in collected_outputs: collected_outputs[key] = (output[index],) else: collected_outputs[key] += (output[index],) return output return wrapped_forward if any(recordable_keys.values()): capture_tasks = [] for key, layer_specs in capture_flags.items(): if not recordable_keys.get(f"output_{key}", False): continue if not isinstance(layer_specs, list): layer_specs = [layer_specs] for specs in layer_specs: if not isinstance(specs, OutputRecorder): index = 0 if "hidden_states" in key else 1 class_name = None if not isinstance(specs, str) else specs target_class = specs if not isinstance(specs, str) else None specs = OutputRecorder(target_class=target_class, index=index, class_name=class_name) capture_tasks.append((key, specs)) for name, module in self.named_modules(): for key, specs in capture_tasks: # The second check is for multimodals where only backbone layer suffix is available if (specs.target_class is not None and isinstance(module, specs.target_class)) or ( specs.class_name is not None and name.endswith(specs.class_name) ): if specs.layer_name is not None and specs.layer_name not in name: continue # Monkey patch forward original_forward = module.forward module.forward = make_capture_wrapper(module, original_forward, key, specs.index) monkey_patched_layers.append((module, original_forward)) outputs = func(self, *args, **kwargs) # Restore original forward methods for module, original_forward in monkey_patched_layers: module.forward = original_forward # Inject collected outputs into model output for key in collected_outputs: if key == "hidden_states": collected_outputs[key] = collected_outputs[key][:-1] if hasattr(outputs, "vision_hidden_states"): collected_outputs[key] += (outputs.vision_hidden_states,) elif hasattr(outputs, "last_hidden_state"): collected_outputs[key] += (outputs.last_hidden_state,) outputs[key] = collected_outputs[key] elif key == "attentions": if isinstance(capture_flags[key], list) and len(capture_flags[key]) == 2: outputs[key] = collected_outputs[key][0::2] outputs["cross_" + key] = collected_outputs[key][1::2] else: outputs[key] = collected_outputs[key] else: outputs[key] = collected_outputs[key] if return_dict is False: outputs = outputs.to_tuple() return outputs return wrapper class GeneralInterface(MutableMapping): """ Dict-like object keeping track of a class-wide mapping, as well as a local one. Allows to have library-wide modifications though the class mapping, as well as local modifications in a single file with the local mapping. """ # Class instance object, so that a call to `register` can be reflected into all other files correctly, even if # a new instance is created (in order to locally override a given function) _global_mapping = {} def __init__(self): self._local_mapping = {} def __getitem__(self, key): # First check if instance has a local override if key in self._local_mapping: return self._local_mapping[key] return self._global_mapping[key] def __setitem__(self, key, value): # Allow local update of the default functions without impacting other instances self._local_mapping.update({key: value}) def __delitem__(self, key): del self._local_mapping[key] def __iter__(self): # Ensure we use all keys, with the overwritten ones on top return iter({**self._global_mapping, **self._local_mapping}) def __len__(self): return len(self._global_mapping.keys() | self._local_mapping.keys()) @classmethod def register(cls, key: str, value: Callable): cls._global_mapping.update({key: value}) def valid_keys(self) -> list[str]: return list(self.keys())
08-08
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值