path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/GenerativeModel.kt | 1896238529 | package com.langdroid.core.models
import com.langdroid.core.models.request.config.GenerativeConfig
public abstract class GenerativeModel {
public abstract val apiKey: String?
// Name of model
public abstract val id: String
// Max amount of tokens available for model to handle
public abstract val tokenLimit: Int
public abstract val outputTokenLimit: Int?
internal var config: GenerativeConfig<*>? = null
internal abstract val actions: GenerativeModelActions
}
|
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/openai/transform.kt | 3604240317 | package com.langdroid.core.models.openai
import com.aallam.openai.api.chat.ChatMessage
import com.aallam.openai.api.core.Role
import com.langdroid.core.ChatPrompt
import com.langdroid.core.ChatRole
internal fun ChatPrompt.toOpenAIPrompt(): ChatMessage = ChatMessage(
role = first.toOpenAIChatRole(),
content = second
)
private fun ChatRole.toOpenAIChatRole() = Role(this.role)
|
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/openai/OpenAiModel.kt | 4119622322 | package com.langdroid.core.models.openai
import com.langdroid.core.models.GenerativeModel
import com.langdroid.core.models.GenerativeModelActions
public sealed class OpenAiModel(
override val id: String,
override val tokenLimit: Int,
override val outputTokenLimit: Int? = null
) : GenerativeModel() {
private val modelActions: GenerativeModelActions by lazy { OpenAiModelActions(this) }
public override val actions: GenerativeModelActions = modelActions
/*
gpt-3.5-turbo-0125 - The latest GPT-3.5 Turbo model with higher
accuracy at responding in requested formats and a fix for a bug
which caused a text encoding issue for non-English language function calls.
*/
public data class Gpt3_5(override val apiKey: String?) : OpenAiModel(
// Same as gpt-3.5-turbo
id = "gpt-3.5-turbo-0125",
tokenLimit = GPT3_5_TOKEN_LIMIT,
outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT
)
/*
gpt-4 - Currently points to gpt-4-0613. Snapshot of GPT-4 from
June 13th 2023 with improved function calling support.
Training data up to Sep 2021.
*/
public data class Gpt4(override val apiKey: String?) : OpenAiModel(
id = "gpt-4", tokenLimit = GPT4_TOKEN_LIMIT, outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT
)
// OTHER MODELS
/*
gpt-3.5-turbo-1106 - GPT-3.5 Turbo model with improved instruction following,
JSON mode, reproducible outputs, parallel function calling, and more.
*/
public data class Gpt3_5Plus(override val apiKey: String?) : OpenAiModel(
id = "gpt-3.5-turbo-1106",
tokenLimit = GPT3_5_TOKEN_LIMIT,
outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT
)
/*
gpt-4-0125-preview - The latest GPT-4 model intended to reduce
cases of “laziness” where the model doesn’t complete a task.
Training data up to Dec 2023.
*/
public data class Gpt4_128kNoLazy(override val apiKey: String?) : OpenAiModel(
id = "gpt-4-0125-preview",
tokenLimit = GPT_128K_TOKEN_LIMIT,
outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT
)
/*
gpt-4-1106-preview - GPT-4 Turbo model featuring improved instruction
following, JSON mode, reproducible outputs, parallel function calling, and more.
Training data up to Apr 2023.
*/
public data class Gpt4_128kPlus(override val apiKey: String?) : OpenAiModel(
id = "gpt-4-1106-preview",
tokenLimit = GPT_128K_TOKEN_LIMIT,
outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT
)
/*
gpt-4-32k - Currently points to gpt-4-32k-0613.
Snapshot of gpt-4-32k from June 13th 2023 with improved function calling support.
This model was never rolled out widely in favor of GPT-4 Turbo.
Training data up to Sep 2021.
*/
public data class Gpt4_32k(override val apiKey: String?) : OpenAiModel(
id = "gpt-4-32k",
tokenLimit = GPT_32K_TOKEN_LIMIT,
outputTokenLimit = GPT_TOKEN_OUTPUT_LIMIT
)
public data class Custom(
override val id: String,
override val apiKey: String?,
override val tokenLimit: Int = CUSTOM_MODEL_TOKEN_LIMIT,
override val outputTokenLimit: Int? = GPT_TOKEN_OUTPUT_LIMIT,
) : OpenAiModel(id, tokenLimit, outputTokenLimit)
}
private const val CUSTOM_MODEL_TOKEN_LIMIT = 4096
private const val GPT4_TOKEN_LIMIT = 8192
private const val GPT3_5_TOKEN_LIMIT = 16385
private const val GPT_TOKEN_OUTPUT_LIMIT = 4096
private const val GPT_128K_TOKEN_LIMIT = 128000
private const val GPT_32K_TOKEN_LIMIT = 32768
|
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/openai/OpenAiRequestConfigFields.kt | 4027626291 | package com.langdroid.core.models.openai
import com.langdroid.core.models.request.config.fields.RequestConfigFields
public class OpenAiRequestConfigFields(
override val maxOutputTokens: String = "max_tokens",
override val temperature: String = "temperature",
override val topP: String? = "top_p",
override val topK: String? = null,
override val configObjectName: String? = null,
) : RequestConfigFields
|
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/openai/OpenAiModelActions.kt | 4098654370 | package com.langdroid.core.models.openai
import com.aallam.openai.api.chat.ChatCompletionRequest
import com.aallam.openai.api.core.RequestOptions
import com.aallam.openai.api.http.Timeout
import com.aallam.openai.api.model.ModelId
import com.aallam.openai.client.OpenAI
import com.langdroid.core.ChatPrompt
import com.langdroid.core.actionWithResult
import com.langdroid.core.models.GenerativeModelActions
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlin.time.Duration.Companion.seconds
public class OpenAiModelActions(
private val model: OpenAiModel
) : GenerativeModelActions {
override suspend fun generateText(prompts: List<ChatPrompt>): Result<String> =
actionWithResult {
openAi.chatCompletion(
request = createChatRequest(prompts),
requestOptions = RequestOptions(
timeout = Timeout(socket = 180.seconds)
)
).choices.first().message.content.orEmpty()
}
override suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> =
actionWithResult {
openAi.chatCompletions(
request = createChatRequest(prompts)
).map {
it.choices.first().let { chunk ->
if (chunk.finishReason != null) null
else chunk.delta.content
}
}
}
private fun createChatRequest(prompts: List<ChatPrompt>): ChatCompletionRequest {
return ChatCompletionRequest(model = modelId,
temperature = temperature,
topP = topP,
maxTokens = maxTokens,
messages = prompts.map { it.toOpenAIPrompt() })
}
override suspend fun sanityCheck(): Boolean = try {
openAi.models()
true
} catch (e: Exception) {
false
}
override suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> =
actionWithResult {
// Android-specific implementation
tokensCount(prompts, modelId.id)
}
private val openAi: OpenAI by lazy {
OpenAI(model.apiKey.orEmpty())
}
private val modelId: ModelId by lazy {
ModelId(model.id)
}
private val temperature: Double? by lazy {
model.config?.temperature?.toDouble()
}
private val topP: Double? by lazy {
model.config?.topP?.toDouble()
}
private val maxTokens: Int? by lazy {
model.config?.maxOutputTokens
}
}
|
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/models/openai/tokens.kt | 3777956718 | package com.langdroid.core.models.openai
import com.aallam.ktoken.Tokenizer
import com.langdroid.core.ChatPrompt
public suspend fun tokensCount(messages: List<ChatPrompt>, model: String): Int {
val (tokensPerMessage, tokensPerName) = when (model) {
"gpt-3.5-turbo-0613", "gpt-3.5-turbo-16k-0613", "gpt-4-0314", "gpt-4-32k-0314", "gpt-4-0613", "gpt-4-32k-0613", "gpt-3.5-turbo-0125", "gpt-3.5-turbo-1106" -> 3 to 1
"gpt-3.5-turbo-0301" -> 4 to -1 // every message follows <|start|>{role/name}\n{content}<|end|>\n
"gpt-3.5-turbo" -> {
println("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")
return tokensCount(messages, "gpt-3.5-turbo-0613")
}
"gpt-4", "gpt-4-1106-preview", "gpt-4-32k", "gpt-4-0125-preview" -> {
println("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")
return tokensCount(messages, "gpt-4-0613")
}
else -> error("unsupported model")
}
val tokenizer = Tokenizer.of(model)
var numTokens = 0
for (message in messages) {
numTokens += tokensPerMessage
message.run {
numTokens += tokenizer.encode(first.role).size
// name?.let { numTokens += tokensPerName + tokenizer.encode(it).size }
second?.let { numTokens += tokenizer.encode(it).size }
}
}
numTokens += 3 // every reply is primed with <|start|>assistant<|message|>
return numTokens
}
|
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/exceptions/NotImplementedException.kt | 3819188772 | package com.langdroid.core.exceptions
public class NotImplementedException(model: String) :
Exception("This functionality is not implemented for model $model")
|
LangDroid/core/src/commonMain/kotlin/com/langdroid/core/LangDroidModel.kt | 1182901566 | package com.langdroid.core
import com.langdroid.core.models.GenerativeModel
import com.langdroid.core.models.GenerativeModelApiActions
import com.langdroid.core.models.request.config.GenerativeConfig
public class LangDroidModel<M : GenerativeModel>(
public val model: M,
public val config: GenerativeConfig<M>? = null
) : GenerativeModelApiActions by LangDroidModelActions(model, config)
|
LangDroid/core/src/jvmMain/kotlin/com/langdroid/core/models/gemini/GeminiModelActions.jvm.kt | 1433968282 | package com.langdroid.core.models.gemini
import com.langdroid.core.ChatPrompt
import com.langdroid.core.models.GenerativeModelActions
import kotlinx.coroutines.flow.Flow
@Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
public actual class GeminiModelActions actual constructor(
internal actual val model: GeminiModel
) : GenerativeModelActions {
private val modelName = "Gemini"
private val notImplementedException = NotImplementedError(modelName)
actual override suspend fun generateText(prompts: List<ChatPrompt>): Result<String> {
throw notImplementedException
}
actual override suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> {
throw notImplementedException
}
actual override suspend fun sanityCheck(): Boolean {
throw notImplementedException
}
actual override suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> {
throw notImplementedException
}
}
|
LangDroid/core/src/androidMain/kotlin/com/langdroid/core/models/gemini/GeminiModelActions.kt | 3969781139 | package com.langdroid.core.models.gemini
import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.Content
import com.google.ai.client.generativeai.type.GenerationConfig
import com.google.ai.client.generativeai.type.TextPart
import com.langdroid.core.ChatPrompt
import com.langdroid.core.actionWithResult
import com.langdroid.core.models.GenerativeModelActions
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
@Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
public actual class GeminiModelActions actual constructor(
internal actual val model: GeminiModel
) : GenerativeModelActions {
private val geminiModel: GenerativeModel by lazy {
GenerativeModel(modelName = model.id,
apiKey = model.apiKey.orEmpty(),
generationConfig = model.config?.let {
GenerationConfig.builder().apply {
topK = it.topK
topP = it.topP
temperature = it.temperature
maxOutputTokens = it.maxOutputTokens
}.build()
})
}
actual override suspend fun generateText(prompts: List<ChatPrompt>): Result<String> =
actionWithResult {
val generateContentResponse = geminiModel.generateContent(*createPrompts(prompts))
generateContentResponse.text.orEmpty()
}
actual override suspend fun generateTextStream(prompts: List<ChatPrompt>): Result<Flow<String?>> =
actionWithResult {
val generateContentStreamResponse =
geminiModel.generateContentStream(*createPrompts(prompts))
generateContentStreamResponse.map { if (it.promptFeedback?.blockReason != null) null else it.text }
}
// We need to reduce it because Gemini not work for system messages, they are transformed to Model Role by
// this library, and then need to be folded because two+ ChatRole.Model messages repeatedly cause a crash
private fun createPrompts(prompts: List<ChatPrompt>): Array<Content> {
val reducedPrompts = prompts.fold(mutableListOf<ChatPrompt>()) { acc, current ->
val currentRole = current.first
if (acc.isNotEmpty() && acc.last().first.toGeminiRole() == currentRole.toGeminiRole()) {
// If the last added prompt has the same role as the current, merge their texts
val mergedText = acc.last().second.orEmpty() + "\n" + current.second.orEmpty()
// Remove the last prompt and add a new merged prompt
acc.removeAt(acc.size - 1)
acc.add(currentRole to mergedText)
} else {
// If the current prompt has a different role, add it as is
acc.add(current)
}
acc
}
// Convert the reduced list of prompts to Content objects
return reducedPrompts.map {
Content(
role = it.first.toGeminiRole().role, parts = listOf(
TextPart(it.second.orEmpty())
)
)
}.toTypedArray()
}
actual override suspend fun sanityCheck(): Boolean = try {
geminiModel.generateContent("a")
true
} catch (e: Exception) {
false
}
public actual override suspend fun calculateTokens(prompts: List<ChatPrompt>): Result<Int> =
actionWithResult {
geminiModel.countTokens(*createPrompts(prompts)).totalTokens
}
}
|
LangDroid/core/src/androidMain/kotlin/com/langdroid/core/models/gemini/roles.kt | 1495355442 | package com.langdroid.core.models.gemini
import com.langdroid.core.ChatRole
internal fun ChatRole.toGeminiRole(): ChatRole =
if (role == "user" || role == "system") ChatRole.User else ChatRole.Model
|
LangDroid/app/src/main/java/com/langdroid/sample/MainViewModel.kt | 1050414536 | package com.langdroid.sample
import androidx.compose.runtime.Stable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.langdroid.sample.data.WikipediaRepository
import com.langdroid.sample.data.WikipediaUiModel
import com.langdroid.summary.SummaryState
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.plus
const val DEFAULT_SUMMARY_TEXT = "Here will be your summary..."
class MainViewModel(
private val repository: WikipediaRepository,
) : ViewModel() {
private val _uiState: MutableStateFlow<MainUiState> = MutableStateFlow(MainUiState())
val uiState: StateFlow<MainUiState>
get() = _uiState
private var currentSummaryJob: Job? = null
fun fetchData(articleUrl: String) = defaultCoroutineScope.launch {
clearTitle()
updateUiState { it.copy(processingState = ProcessingUiState.Fetching) }
val output = repository.getWikipediaContent(articleUrl)
if (output.isSuccess) {
updateUiState {
it.copy(
textTitle = output.getOrNull()?.title,
processingState = ProcessingUiState.Fetched(output.getOrThrow())
)
}
} else {
clearTitle()
updateUiState {
it.copy(processingState = ProcessingUiState.Failed(output.exceptionOrNull()))
}
}
}
private fun clearTitle() {
updateUiState { it.copy(textTitle = null) }
}
// Not best practice, made for demonstration
fun launchScope(onProcess: suspend CoroutineScope.() -> Unit) {
currentSummaryJob?.cancel()
currentSummaryJob = defaultCoroutineScope.launch {
onProcess(this)
}
}
fun updateSummaryState(summaryState: SummaryState, outputText: String? = null) {
val textToPrint = summaryState.toProcessingString(outputText)
val processingState =
if (summaryState is SummaryState.Success) ProcessingUiState.Success(outputText.orEmpty())
else ProcessingUiState.Summarizing(textToPrint)
updateUiState { it.copy(processingState = processingState) }
}
private inline fun updateUiState(crossinline onUpdate: (MainUiState) -> MainUiState) {
_uiState.update {
onUpdate(it)
}
}
private val defaultCoroutineScope: CoroutineScope by lazy {
val defaultDispatcher = Dispatchers.Default
viewModelScope.plus(defaultDispatcher + CoroutineExceptionHandler { _, throwable ->
updateUiState { it.copy(processingState = ProcessingUiState.Failed(throwable)) }
})
}
}
@Stable
data class MainUiState(
val textTitle: String? = null, val textOutput: String? = null,
val processingState: ProcessingUiState = ProcessingUiState.Idle
)
@Stable
sealed interface ProcessingUiState {
data object Idle : ProcessingUiState
data object Fetching : ProcessingUiState
data class Fetched(val model: WikipediaUiModel) : ProcessingUiState
data class Summarizing(
val summaryStateText: String
) : ProcessingUiState
data class Success(val outputText: String) : ProcessingUiState
data class Failed(val t: Throwable?) : ProcessingUiState
fun isIdle() = this is Idle || this is Success || this is Failed
}
private fun SummaryState.toProcessingString(outputText: String? = null): String = when (this) {
is SummaryState.Idle, is SummaryState.Failure -> DEFAULT_SUMMARY_TEXT
is SummaryState.TextSplitting -> "Splitting text..."
is SummaryState.Reduce -> "Processing chunks $processedChunks/$allChunks"
is SummaryState.Summarizing -> "Summarizing text..."
is SummaryState.Output -> outputText.orEmpty()
is SummaryState.Success -> outputText.orEmpty()
}
fun Factory(repository: WikipediaRepository): ViewModelProvider.Factory =
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST") return MainViewModel(repository) as T
}
}
|
LangDroid/app/src/main/java/com/langdroid/sample/ui/BulletPointList.kt | 204671509 | package com.langdroid.sample.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.unit.dp
@Composable
fun BulletPointText(text: String, modifier: Modifier = Modifier) {
Column(modifier = modifier) {
// Split the text into lines
val lines = text.split("\n")
lines.forEach { line ->
// Check if the line starts with a dash and optionally some leading spaces
if (line.trimStart().startsWith("-")) {
// Remove the dash and any spaces around it, then trim the result
val trimmedLine = line.trimStart().removePrefix("-").trim()
// Build a bullet point string
val bulletPointText = buildAnnotatedString {
// Append a bullet point and a space before the actual text
append("• $trimmedLine")
}
// Display the line with a bullet point
Text(
text = bulletPointText,
modifier = Modifier.padding(start = 4.dp, top = 0.dp, bottom = 12.dp),
)
} else {
// Line does not start with a dash, display it as is
Text(
text = line
)
}
}
}
}
|
LangDroid/app/src/main/java/com/langdroid/sample/ui/theme/Color.kt | 1935691610 | package com.langdroid.sample.ui.theme
import androidx.compose.ui.graphics.Color
val LightWhiteColor = Color(0xFFF7F7F7)
//val LightWhiteColor = Color(0xFFFFFFFF)
val TextBlackColor = Color(0xFF171717)
val ContainerColor = Color(0xFFF1F1F1)
|
LangDroid/app/src/main/java/com/langdroid/sample/ui/theme/Theme.kt | 2406427502 | package com.langdroid.sample.ui.theme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
private val LightColorScheme = lightColorScheme(
primary = TextBlackColor,
secondary = TextBlackColor,
tertiary = TextBlackColor,
background = LightWhiteColor,
surface = TextBlackColor,
primaryContainer = ContainerColor,
onPrimary = LightWhiteColor,
onSecondary = LightWhiteColor,
onTertiary = LightWhiteColor,
onBackground = TextBlackColor,
onSurface = TextBlackColor,
)
@Composable
fun LangdroidTheme(
content: @Composable () -> Unit
) {
MaterialTheme(
colorScheme = LightColorScheme,
typography = Typography,
content = content
)
}
|
LangDroid/app/src/main/java/com/langdroid/sample/ui/theme/Type.kt | 571180319 | package com.langdroid.sample.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
|
LangDroid/app/src/main/java/com/langdroid/sample/ui/MainScreen.kt | 1530847636 | package com.langdroid.sample.ui
import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.langdroid.sample.DEFAULT_ERROR_MESSAGE
import com.langdroid.sample.DEFAULT_SUMMARY_TEXT
import com.langdroid.sample.IS_MATERIAL_3_STYLE
import com.langdroid.sample.MainUiState
import com.langdroid.sample.ProcessingUiState
import com.langdroid.sample.data.WikipediaUiModel
import com.langdroid.sample.ui.theme.LangdroidTheme
import kotlinx.coroutines.flow.StateFlow
private val DefaultPadding = 16.dp
private val TextFieldHeight = 48.dp
private val CircularProgressIndicatorSize = 18.dp
private val CircularProgressIndicatorStrokeWidth = 2.dp
private val HorizontalDividerThickness = 1.dp
private const val HorizontalDividerAlpha = 0.1f
private val PaddingDefault = 8.dp
private val PaddingLarge = 16.dp
@Composable
fun MainScreen(
onFetchData: (String) -> Unit,
uiStateFlow: () -> StateFlow<MainUiState>,
onWikipediaFetched: (WikipediaUiModel) -> Unit,
) {
val context = LocalContext.current
val keyboardController = LocalSoftwareKeyboardController.current
val scrollState = rememberScrollState()
var articleUrl by remember { mutableStateOf("") }
val uiState by uiStateFlow().collectAsStateWithLifecycle()
val processingState = uiState.processingState
val surfaceColor = getSurfaceColor()
// Log.d("HELLO", processingState.toString())
LaunchedEffect(processingState) {
when (processingState) {
is ProcessingUiState.Fetched -> onWikipediaFetched(processingState.model)
is ProcessingUiState.Failed -> makeToast(context, processingState.t)
else -> Unit
}
}
Scaffold(
modifier = Modifier.imePadding(),
topBar = {
MainScreenTopBar(
articleUrl = articleUrl,
onArticleUrlChange = { articleUrl = it },
processingState = processingState,
surfaceColor = surfaceColor,
keyboardController = keyboardController,
onFetchData = onFetchData
)
},
bottomBar = {
MainScreenBottomBar(
articleUrl = articleUrl,
processingState = processingState,
surfaceColor = surfaceColor,
keyboardController = keyboardController,
onFetchData = onFetchData
)
}
) { paddingValues ->
Column(
modifier = Modifier
.padding(paddingValues)
.consumeWindowInsets(paddingValues)
.fillMaxSize()
.verticalScroll(scrollState)
.padding(start = PaddingLarge, end = PaddingLarge, top = PaddingLarge)
) {
val processingText: String = when {
processingState is ProcessingUiState.Summarizing -> {
processingState.summaryStateText
}
processingState is ProcessingUiState.Success -> {
processingState.outputText
}
processingState is ProcessingUiState.Fetching -> "Fetching..."
!processingState.isIdle() -> "Processing..."
else -> DEFAULT_SUMMARY_TEXT
}
if (!uiState.textTitle.isNullOrEmpty()) Text(
text = "Article: ${uiState.textTitle}",
modifier = Modifier.padding(bottom = PaddingLarge),
style = MaterialTheme.typography.titleLarge
)
BulletPointText(text = processingText, modifier = Modifier.fillMaxSize())
// Text(text = processingText, modifier = Modifier.fillMaxSize())
}
}
}
@Composable
private fun MainScreenTopBar(
articleUrl: String,
onArticleUrlChange: (String) -> Unit,
processingState: ProcessingUiState,
surfaceColor: Color,
keyboardController: SoftwareKeyboardController?,
onFetchData: (String) -> Unit
) {
Surface(color = surfaceColor) {
Column(Modifier.windowInsetsPadding(WindowInsets.systemBars.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top))) {
OutlinedTextField(
value = articleUrl,
onValueChange = onArticleUrlChange,
placeholder = { Text("Wikipedia Article or URL") },
modifier = Modifier
.fillMaxWidth()
.padding(DefaultPadding),
keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = {
keyboardController?.hide()
onFetchData(articleUrl)
}),
enabled = processingState.isIdle()
)
SimpleDivider()
}
}
}
@Composable
private fun MainScreenBottomBar(
articleUrl: String,
processingState: ProcessingUiState,
surfaceColor: Color,
keyboardController: SoftwareKeyboardController?,
onFetchData: (String) -> Unit
) {
Surface(color = surfaceColor) {
Column(
Modifier.windowInsetsPadding(
WindowInsets.systemBars.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom)
)
) {
SimpleDivider()
Box(Modifier.padding(16.dp)) {
Button(
onClick = {
if (processingState.isIdle()) {
keyboardController?.hide()
onFetchData(articleUrl)
}
},
modifier = Modifier
.fillMaxWidth()
.height(TextFieldHeight),
enabled = processingState.isIdle() && articleUrl.isNotEmpty(),
shape = MaterialTheme.shapes.medium
) {
if (!processingState.isIdle()) {
Text(
text = if (processingState is ProcessingUiState.Summarizing) "Summarizing" else "Fetching",
modifier = Modifier.padding(end = PaddingDefault),
color = MaterialTheme.colorScheme.primary
)
CircularProgressIndicator(
modifier = Modifier.size(CircularProgressIndicatorSize),
strokeWidth = CircularProgressIndicatorStrokeWidth,
strokeCap = StrokeCap.Round
)
} else {
Text("Summarize")
}
}
}
}
}
}
@Composable
private fun SimpleDivider() {
if (!IS_MATERIAL_3_STYLE)
HorizontalDivider(
thickness = HorizontalDividerThickness,
color = MaterialTheme.colorScheme.primary.copy(alpha = HorizontalDividerAlpha)
)
}
@Composable
private fun getSurfaceColor(): Color {
return if (IS_MATERIAL_3_STYLE) MaterialTheme.colorScheme.primaryContainer
else MaterialTheme.colorScheme.background
}
private fun makeToast(context: Context, exception: Throwable?) {
Toast.makeText(
context, exception?.message ?: DEFAULT_ERROR_MESSAGE, Toast.LENGTH_SHORT
).show()
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
LangdroidTheme {
}
}
|
LangDroid/app/src/main/java/com/langdroid/sample/MainActivity.kt | 3151266648 | package com.langdroid.sample
//import com.langdroid.core.ChatRole
//import com.langdroid.core.LangDroidModel
//import com.langdroid.core.models.gemini.GeminiModel
//import com.langdroid.core.models.openai.OpenAiModel
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.core.view.WindowCompat
import com.langdroid.BuildConfig
import com.langdroid.core.LangDroidModel
import com.langdroid.core.models.openai.OpenAiModel
import com.langdroid.core.models.request.config.GenerativeConfig
import com.langdroid.sample.data.WikipediaApi
import com.langdroid.sample.data.WikipediaRepository
import com.langdroid.sample.data.WikipediaUiModel
import com.langdroid.sample.ui.MainScreen
import com.langdroid.sample.ui.theme.LangdroidTheme
import com.langdroid.summary.SummaryChain
import com.langdroid.summary.SummaryState
import com.langdroid.summary.extensions.collectUntilFinished
import com.langdroid.summary.liveData
import com.langdroid.summary.prompts.PromptsAndMessage
// IMPORTANT! Use {text} in your prompts for places where prompt has to be pasted during processing
private const val WIKIPEDIA_FINAL_PROMPT = """
Write a very detailed summary of the Wikipedia page, the following text delimited by triple backquotes.
Return your response with bullet points which covers the most important key points of the text, sequentially and coherently.
```{text}```
BULLET POINT SUMMARY:
"""
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
val wikipediaApi = WikipediaApi()
val repository = WikipediaRepository(wikipediaApi)
val viewModel: MainViewModel by viewModels { Factory(repository) }
val openAiKey = BuildConfig.OPENAI_API_KEY
val openAiModel =
LangDroidModel(
OpenAiModel.Gpt3_5Plus(openAiKey),
GenerativeConfig.create {
// Set temperature = 0f to minimize literature text and make concise summaries
temperature = 0f
})
// Default prompts are used if "null" or nothing passed
val promptsAndMessage = PromptsAndMessage(
// System message added before all the messages and always noticed by LLM
systemMessage = "You are the Wikipedia oracle",
// Prompt for final chunk mapping and overall summarization
finalPrompt = WIKIPEDIA_FINAL_PROMPT,
)
val summaryChain = SummaryChain(
model = openAiModel,
// Optional values below
isStream = true,
promptsAndMessage = promptsAndMessage
)
val onWikipediaFetched: (WikipediaUiModel) -> Unit = { model ->
val textToSummarize = model.content
// Good practice to have outputBuilder to use summarized output later
val outputBuilder = StringBuilder()
// We launch scope as new job and in default/io coroutine to collect summary chain and don't stop UI
viewModel.launchScope {
val summaryChainFlow = summaryChain.invokeAndGetFlow(textToSummarize)
summaryChainFlow.collectUntilFinished {
if (it is SummaryState.Output) outputBuilder.append(it.text)
viewModel.updateSummaryState(it, outputBuilder.toString())
}
}
}
setContent {
LangdroidTheme {
Surface(
modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
) {
MainScreen(
onFetchData = viewModel::fetchData,
uiStateFlow = viewModel::uiState::get,
onWikipediaFetched = onWikipediaFetched
)
}
}
}
}
}
const val DEFAULT_ERROR_MESSAGE = "Something went wrong"
const val IS_MATERIAL_3_STYLE = true
|
LangDroid/app/src/main/java/com/langdroid/sample/utils/functions.kt | 138157547 | package com.langdroid.sample.utils
|
LangDroid/app/src/main/java/com/langdroid/sample/data/WikipediaApi.kt | 2955542047 | package com.langdroid.sample.data
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.android.Android
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
class WikipediaApi {
private val client = HttpClient(Android) {
install(ContentNegotiation) {
json(Json {
prettyPrint = true
isLenient = true
ignoreUnknownKeys = true
})
}
}
suspend fun getArticleContent(pageTitle: String): WikipediaResponse? =
withContext(Dispatchers.IO) {
try {
client.get("https://en.wikipedia.org/w/api.php") {
parameter("format", "json")
parameter("action", "query")
parameter("prop", "extracts")
parameter("exlimit", "max")
parameter("explaintext", null)
parameter("titles", pageTitle)
parameter("redirects", "")
}.body()
} catch (e: Exception) {
e.printStackTrace()
null
}
}
}
|
LangDroid/app/src/main/java/com/langdroid/sample/data/models.kt | 2812538955 | package com.langdroid.sample.data
import kotlinx.serialization.Serializable
@Serializable
data class WikipediaResponse(
val query: QueryResult
)
@Serializable
data class QueryResult(
val pages: Map<String, PageInfo>
)
@Serializable
data class PageInfo(
val title: String,
val extract: String
)
data class WikipediaUiModel(
val title: String,
val content: String
)
|
LangDroid/app/src/main/java/com/langdroid/sample/data/EmptyOutputException.kt | 1832681078 | package com.langdroid.sample.data
class EmptyOutputException(override val message: String? = "The page content is empty!") :
Exception(message)
|
LangDroid/app/src/main/java/com/langdroid/sample/data/WikipediaRepository.kt | 3021419360 | package com.langdroid.sample.data
import java.net.URLDecoder
import java.nio.charset.StandardCharsets
class WikipediaRepository(private val wikipediaApi: WikipediaApi) {
suspend fun getWikipediaContent(articleUrl: String): Result<WikipediaUiModel> {
val titleUrl = articleUrl.substringAfterLast("/").substringBefore("?")
val title = URLDecoder.decode(titleUrl, StandardCharsets.UTF_8.toString())
return try {
val response = wikipediaApi.getArticleContent(title)
val pageInfo = response?.query?.pages?.values?.firstOrNull()
val outputTitle = pageInfo?.title
val content = pageInfo?.extract
if (outputTitle == null || content == null)
throw EmptyOutputException()
val uiModel = WikipediaUiModel(outputTitle, content)
Result.success(uiModel)
} catch (e: Exception) {
Result.failure(e)
}
}
}
|
LangDroid/plugins/convention/src/main/kotlin/com/langdroid/plugins/AndroidExtension.kt | 4246573007 | package com.langdroid.plugins
import com.android.build.api.dsl.CommonExtension
import com.android.build.api.dsl.LibraryExtension
import org.gradle.api.Project
import org.gradle.kotlin.dsl.getByType
internal fun Project.configureAndroidPublishing(
commonExtension: CommonExtension<*, *, *, *, *>,
) {
commonExtension.apply {
(this as LibraryExtension).publishing {
singleVariant("release") {
withSourcesJar()
}
}
}
} |
LangDroid/plugins/convention/src/main/kotlin/ModulePublishPlugin.kt | 309386219 | import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import com.android.build.gradle.LibraryExtension
import com.langdroid.plugins.configureAndroidPublishing
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.withType
abstract class ModulePublishPlugin : Plugin<Project> {
override fun apply(project: Project) {
with(project) {
pluginManager.apply("maven-publish")
pluginManager.apply("com.android.library")
val extension = extensions.getByType<LibraryExtension>()
configureAndroidPublishing(extension)
afterEvaluate {
val publishing = project.extensions.getByType(PublishingExtension::class.java)
publishing.publications {
val mavenPublication = create("maven", MavenPublication::class.java)
mavenPublication.apply {
from(project.components.findByName("release"))
groupId = "com.langdroid.modules"
artifactId = project.name
version = project.version.toString()
}
val kmmPublication = withType<MavenPublication>().named("kotlinMultiplatform")
kmmPublication.configure {
groupId = "com.langdroid.modules"
artifactId = project.name
version = project.version.toString()
}
}
}
}
}
} |
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/SummaryState.kt | 1628921950 | package com.langdroid.summary
import com.langdroid.summary.chains.states.ChainState
public sealed interface SummaryState : ChainState {
public data object Idle : SummaryState
public data object TextSplitting : SummaryState
public data class Reduce(val processedChunks: Int, val allChunks: Int) : SummaryState
// Used when isStream = false
public data object Summarizing : SummaryState
public data class Output(val text: String) : SummaryState
public data object Success : SummaryState
public data class Failure(val t: Throwable) : SummaryState
}
public fun SummaryState.isFinished(): Boolean =
this is SummaryState.Success || this is SummaryState.Failure
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/exceptions/SummaryException.kt | 1172289093 | package com.langdroid.summary.exceptions
public class SummaryException(override val message: String? = "Something went wrong during summary") :
Exception(message)
public fun <T> Result<T>.createException(): Throwable = exceptionOrNull() ?: SummaryException()
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/splitters/TextSplitter.kt | 3289523588 | package com.langdroid.summary.splitters
public interface TextSplitter {
public fun splitText(
text: String,
separators: List<String> = listOf("\n\n", "\n", " ", ""),
onWarning: (String) -> Unit
): List<String>
}
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/splitters/RecursiveTextSplitter.kt | 4048610722 | package com.langdroid.summary.splitters
import java.util.regex.Pattern
public class RecursiveTextSplitter(
private val chunkSize: Int,
private val chunkOverlap: Int,
private val keepSeparator: Boolean = false,
private val isSeparatorRegex: Boolean = false,
) : TextSplitter {
public override fun splitText(
text: String,
separators: List<String>,
onWarning: (String) -> Unit
): List<String> {
if (separators.isEmpty()) return listOf(text)
val finalChunks = mutableListOf<String>()
var separator = separators.last()
var newSeparators = listOf<String>()
for ((i, sep) in separators.withIndex()) {
val currentSeparator = if (isSeparatorRegex) sep else Pattern.quote(sep)
if (sep.isEmpty() || Regex(currentSeparator).containsMatchIn(text)) {
separator = sep
newSeparators = separators.drop(i + 1)
break
}
}
val splitRegex = if (isSeparatorRegex) separator else Pattern.quote(separator)
val splits = splitTextWithRegex(text, splitRegex, keepSeparator)
val goodSplits = mutableListOf<String>()
val mergeSeparator = if (keepSeparator) "" else separator
for (split in splits) {
if (split.length < chunkSize) {
goodSplits.add(split)
} else {
if (goodSplits.isNotEmpty()) {
val mergedText = mergeSplits(goodSplits, mergeSeparator, onWarning)
finalChunks.addAll(mergedText)
goodSplits.clear()
}
if (newSeparators.isEmpty()) {
finalChunks.add(split)
} else {
val otherInfo = splitText(split, newSeparators, onWarning)
finalChunks.addAll(otherInfo)
}
}
}
if (goodSplits.isNotEmpty()) {
val mergedText = mergeSplits(goodSplits, mergeSeparator, onWarning)
finalChunks.addAll(mergedText)
}
return finalChunks
}
private fun mergeSplits(
splits: Iterable<String>,
separator: String,
onWarning: (String) -> Unit
): List<String> {
val separatorLength = lengthFunction(separator)
val docs = mutableListOf<String>()
var currentDoc = mutableListOf<String>()
var totalLength = 0
for (split in splits) {
val splitLength = lengthFunction(split)
if (totalLength + splitLength + (if (currentDoc.isNotEmpty()) separatorLength else 0) > chunkSize) {
if (totalLength > chunkSize) {
onWarning("Created a chunk of size $totalLength, which is longer than the specified $chunkSize")
}
if (currentDoc.isNotEmpty()) {
val doc = joinDocs(currentDoc, separator)
docs.add(doc)
// Popping from the current document if it's larger than the chunk overlap
// or still has chunks and the length is too long.
while (totalLength > chunkOverlap || (totalLength + splitLength + (if (currentDoc.isNotEmpty()) separatorLength else 0) > chunkSize && totalLength > 0)) {
totalLength -= lengthFunction(currentDoc.first()) + (if (currentDoc.size > 1) separatorLength else 0)
currentDoc = currentDoc.drop(1).toMutableList()
}
}
}
currentDoc.add(split)
totalLength += splitLength + (if (currentDoc.size > 1) separatorLength else 0)
}
val doc = joinDocs(currentDoc, separator)
docs.add(doc)
return docs
}
private fun joinDocs(docs: List<String>, separator: String): String =
docs.joinToString(separator)
private fun lengthFunction(input: String): Int = input.length
private fun splitTextWithRegex(
text: String, separator: String, keepSeparator: Boolean
): List<String> {
if (separator.isEmpty()) return text.map { it.toString() } // Split into characters if separator is empty.
val pattern = if (keepSeparator) "($separator)" else separator
val splits = Regex(pattern).split(text, 0).filterNot { it.isEmpty() }
return if (keepSeparator) {
val result = mutableListOf<String>()
var i = 0
while (i < splits.size) {
if (i + 1 < splits.size && splits[i + 1] == separator) {
result.add(splits[i] + separator)
i += 2
} else {
result.add(splits[i])
i++
}
}
result
} else {
splits
}
}
}
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/extensions/flow.kt | 247434300 | package com.langdroid.summary.extensions
import com.langdroid.summary.SummaryState
import com.langdroid.summary.isFinished
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.takeWhile
public suspend fun Flow<SummaryState>.collectUntilFinished(onEach: (SummaryState) -> Unit): Unit =
takeUntilFinished(onEach).collect()
public fun Flow<SummaryState>.takeUntilFinished(onEach: (SummaryState) -> Unit): Flow<SummaryState> =
this.onEach(onEach).takeWhile { !it.isFinished() }
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/SummaryChain.kt | 3309365530 | package com.langdroid.summary
import com.langdroid.core.LangDroidModel
import com.langdroid.core.models.GenerativeModel
import com.langdroid.core.models.request.config.GenerativeConfig
import com.langdroid.summary.chains.DefaultChain
import com.langdroid.summary.chains.MapReduceChain
import com.langdroid.summary.chains.base.Chain
import com.langdroid.summary.chains.base.DEFAULT_TEXT_PLACEHOLDER
import com.langdroid.summary.chains.states.SummaryChainState
import com.langdroid.summary.extensions.collectUntilFinished
import com.langdroid.summary.prompts.CompletedPromptsAndMessages
import com.langdroid.summary.prompts.DEFAULT_SYSTEM_MESSAGE
import com.langdroid.summary.prompts.PromptTemplate
import com.langdroid.summary.prompts.PromptsAndMessage
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
private const val MAX_DEFAULT_OUTPUT_TOKENS = 512
//In case some calculations are a bit wrong
private const val TOKENS_THRESHOLD = 10
private const val TAG = "SummaryChain"
private const val DEFAULT_CHUNK_PROMPT = """
Write a concise summary of the following:
"{text}"
CONCISE SUMMARY:
"""
private const val DEFAULT_FINAL_PROMPT = """
Write a concise summary of the following text delimited by triple backquotes.
Return your response in bullet points which covers the key points of the text.
```{text}```
BULLET POINT SUMMARY:
"""
public class SummaryChain<M : GenerativeModel> : Chain<SummaryState> {
private val langDroidModel: LangDroidModel<M>
private val isStream: Boolean
private lateinit var coroutineScope: CoroutineScope
private lateinit var promptsAndMessage: CompletedPromptsAndMessages
private var summaryJob: Job? = null
public constructor(
model: LangDroidModel<M>,
isStream: Boolean = true,
coroutineScope: CoroutineScope? = null,
promptsAndMessage: PromptsAndMessage? = null
) {
this.langDroidModel = model
this.isStream = isStream
setupConstructor(coroutineScope, promptsAndMessage)
}
public constructor(
model: M, config: GenerativeConfig<M>? = null,
isStream: Boolean = true,
coroutineScope: CoroutineScope? = null,
promptsAndMessage: PromptsAndMessage? = null,
) {
this.langDroidModel = LangDroidModel(model, config)
this.isStream = isStream
setupConstructor(coroutineScope, promptsAndMessage)
}
private fun setupConstructor(
coroutineScope: CoroutineScope?, promptsAndMessage: PromptsAndMessage?
) {
setupScope(coroutineScope)
createPromptTemplates(promptsAndMessage)
}
private fun createPromptTemplates(
promptsAndMessage: PromptsAndMessage?
) {
this.promptsAndMessage = CompletedPromptsAndMessages(
chunkPrompt = promptsAndMessage?.chunkPrompt ?: DEFAULT_CHUNK_PROMPT,
finalPrompt = promptsAndMessage?.finalPrompt ?: DEFAULT_FINAL_PROMPT,
systemMessage = promptsAndMessage?.systemMessage ?: DEFAULT_SYSTEM_MESSAGE
)
}
private fun setupScope(coroutineScope: CoroutineScope?) {
this.coroutineScope = CoroutineScope(
(coroutineScope?.coroutineContext ?: Dispatchers.IO) + coroutineExceptionHandler
)
}
public override suspend fun invoke(text: String): Unit = summaryScope {
val outputTokenLimit = langDroidModel.model.outputTokenLimit ?: MAX_DEFAULT_OUTPUT_TOKENS
var maxOutputTokens = langDroidModel.config?.maxOutputTokens ?: outputTokenLimit
if (maxOutputTokens > outputTokenLimit) {
warning("Your provided output tokens is too high for this model.\nSet default for ${langDroidModel.model.id}: $outputTokenLimit ")
maxOutputTokens = maxOutputTokens.coerceAtMost(outputTokenLimit)
}
val modelMaxTokens = langDroidModel.model.tokenLimit
val finalPromptTemplate = PromptTemplate(
promptsAndMessage.finalPrompt, promptsAndMessage.systemMessage
)
val promptsTokensCount = langDroidModel.calculateTokens(
finalPromptTemplate.createPrompts(
DEFAULT_TEXT_PLACEHOLDER to text
)
).getOrThrow()
// If prompt input + expected output < max model context length - make summary from full prompt at once
if (promptsTokensCount + maxOutputTokens < modelMaxTokens - TOKENS_THRESHOLD) {
val defaultChain = DefaultChain(langDroidModel, finalPromptTemplate, isStream)
defaultChain.invokeAndConnect(
coroutineScope = this,
chain = this@SummaryChain,
text = text,
onMap = ::mapToSummaryState
)
}
//else - split text
else {
val chunkPromptTemplate = PromptTemplate(
promptsAndMessage.chunkPrompt, promptsAndMessage.systemMessage
)
val mapReduceChain = MapReduceChain(
langDroidModel, chunkPromptTemplate, finalPromptTemplate, isStream
)
mapReduceChain.invokeAndConnect(
coroutineScope = this,
chain = this@SummaryChain,
text = text,
onMap = ::mapToSummaryState
)
}
processingState.tryEmit(SummaryState.Success)
}
public fun invokeAndGetFlow(text: String): SharedFlow<SummaryState> {
workingScope { invoke(text) }
return processingState
}
public fun invokeAndObserve(text: String, onCallback: (state: SummaryState) -> Unit) {
workingScope {
invoke(text)
processingState.collectUntilFinished(onCallback)
}
}
public fun cancel() {
summaryJob?.cancel() // Cancel the job
}
private fun mapToSummaryState(state: SummaryChainState): SummaryState? {
return when (state) {
is SummaryChainState.Reduce -> SummaryState.Reduce(
state.processedChunks, state.allChunks
)
is SummaryChainState.Connecting -> SummaryState.Idle
is SummaryChainState.TextSplitting -> SummaryState.TextSplitting
is SummaryChainState.Summarizing -> SummaryState.Summarizing
is SummaryChainState.Output -> SummaryState.Output(state.text)
is SummaryChainState.Failure -> SummaryState.Failure(state.t)
else -> {
if (state is SummaryChainState.Warning)
// Add Logger
warning(state.warning)
null
}
}
}
private fun warning(message: String) {
// Log.w(TAG, message)
}
private fun error(throwable: Throwable) {
processingState.tryEmit(SummaryState.Failure(throwable))
}
private val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
error(throwable)
}
private inline fun summaryScope(crossinline block: suspend CoroutineScope.() -> Unit) {
cancel()
summaryJob = coroutineScope.launch {
block()
}
}
private inline fun workingScope(crossinline block: suspend CoroutineScope.() -> Unit) {
coroutineScope.launch {
block()
}
}
override val processingState: MutableSharedFlow<SummaryState> =
MutableSharedFlow(extraBufferCapacity = 1000)
}
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/prompts/PromptTemplate.kt | 3583458582 | package com.langdroid.summary.prompts
import com.langdroid.core.ChatPrompt
import com.langdroid.core.ChatRole
internal const val DEFAULT_SYSTEM_MESSAGE = "You are expert in a discussed field"
public class PromptTemplate public constructor(
private val prompt: String,
private val systemMessage: String = DEFAULT_SYSTEM_MESSAGE
) {
public fun createPrompts(vararg promptKeys: Pair<String, String>): List<ChatPrompt> {
return createPrompts(promptKeys.toMap())
}
public fun createPrompts(promptKeys: Map<String, String>): List<ChatPrompt> {
val pattern = "\\{(.*?)\\}".toRegex() // Regex to match {key} patterns
val matches = pattern.findAll(prompt)
val prompts = mutableListOf<ChatPrompt>()
prompts.add(ChatPrompt(ChatRole.System, systemMessage))
var latestPrompt = prompt
matches.forEach { match ->
val key = match.groups[1]?.value
?: throw PromptException("Something wrong with prompt ({} may be empty or invalid)")
val replacement =
promptKeys[key] ?: throw PromptException("Key '$key' not found in promptKeys.")
latestPrompt = latestPrompt.replace("{$key}", replacement)
}
prompts.add(ChatPrompt(ChatRole.User, latestPrompt))
return prompts
}
}
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/prompts/PromptException.kt | 1980381560 | package com.langdroid.summary.prompts
public class PromptException(
override val message: String
) : Exception(message)
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/prompts/PromptsAndMessage.kt | 107647655 | package com.langdroid.summary.prompts
public data class PromptsAndMessage(
val chunkPrompt: String? = null,
val finalPrompt: String? = null,
val systemMessage: String? = null
)
internal data class CompletedPromptsAndMessages(
val chunkPrompt: String,
val finalPrompt: String,
val systemMessage: String
)
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/documents/Document.kt | 3136122411 | package com.langdroid.summary.documents
public data class Document(
val text: String
)
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/DefaultChain.kt | 140173471 | package com.langdroid.summary.chains
import com.langdroid.core.LangDroidModel
import com.langdroid.summary.chains.base.DEFAULT_TEXT_PLACEHOLDER
import com.langdroid.summary.chains.base.TextProcessingChain
import com.langdroid.summary.chains.states.SummaryChainState
import com.langdroid.summary.exceptions.createException
import com.langdroid.summary.prompts.PromptTemplate
import kotlinx.coroutines.flow.takeWhile
internal class DefaultChain(
private val langDroidModel: LangDroidModel<*>,
private val prompt: PromptTemplate,
private val isStream: Boolean = false
) : TextProcessingChain() {
override suspend fun invoke(text: String) {
val prompts = prompt.createPrompts(
DEFAULT_TEXT_PLACEHOLDER to text
)
if (isStream) {
val generateStreamResult = langDroidModel.generateTextStream(prompts)
if (generateStreamResult.isSuccess)
generateStreamResult.getOrThrow().takeWhile { output ->
// When output is null - it's finished its work
output != null // Continue collecting until text is null
}.collect { output ->
if (output != null) {
processText(output)
}
}
else generateStreamResult.createException().let(::processFailure)
} else {
updateState(SummaryChainState.Summarizing)
val textResult = langDroidModel.generateText(prompts)
if (textResult.isSuccess) {
processText(textResult.getOrThrow())
} else textResult.createException().let(::processFailure)
}
updateState(SummaryChainState.Finished)
}
}
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/ChainException.kt | 3748408128 | package com.langdroid.summary.chains
public class ChainException(
override val message: String?
) : Exception()
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/states/SummaryChainState.kt | 21674381 | package com.langdroid.summary.chains.states
internal interface SummaryChainState : ChainState {
data object Connecting : SummaryChainState
data object TextSplitting : SummaryChainState
data class Reduce(val processedChunks: Int, val allChunks: Int) : SummaryChainState
data object Summarizing: SummaryChainState
data class Output(val text: String) : SummaryChainState
data class Warning(val warning: String) : SummaryChainState
data class Failure(val t: Throwable) : SummaryChainState
data object Finished: SummaryChainState
}
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/states/ChainState.kt | 3962642475 | package com.langdroid.summary.chains.states
public interface ChainState
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/MapReduceChain.kt | 2555716065 | package com.langdroid.summary.chains
import com.langdroid.core.LangDroidModel
import com.langdroid.summary.chains.base.DEFAULT_TEXT_PLACEHOLDER
import com.langdroid.summary.chains.base.TextProcessingChain
import com.langdroid.summary.chains.states.SummaryChainState
import com.langdroid.summary.prompts.PromptTemplate
import com.langdroid.summary.splitters.RecursiveTextSplitter
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
private const val DEFAULT_CHUNK_SIZE = 10000
private const val DEFAULT_OVERLAP_SIZE = 500
private const val DEFAULT_DOCUMENT_SEPARATOR = "\n\n"
internal class MapReduceChain(
private val langDroidModel: LangDroidModel<*>,
private val chunkPrompt: PromptTemplate,
private val finalPrompt: PromptTemplate,
private val isStream: Boolean
) : TextProcessingChain() {
override suspend fun invoke(text: String) {
updateState(SummaryChainState.TextSplitting)
val textSplitter = RecursiveTextSplitter(
chunkSize = DEFAULT_CHUNK_SIZE, chunkOverlap = DEFAULT_OVERLAP_SIZE
)
val outputChunks = textSplitter.splitText(text, onWarning = ::processWarning)
//1. Map chunks
val amountOfChunks = outputChunks.size
val processedChunks = processAndTrackChunks(outputChunks) { processedChunks ->
updateState(SummaryChainState.Reduce(processedChunks, amountOfChunks))
}
//2. Reduce chunks into final output
val combinedChunks = processedChunks.joinToString(separator = DEFAULT_DOCUMENT_SEPARATOR)
val defaultChain = DefaultChain(
langDroidModel = langDroidModel, prompt = finalPrompt, isStream = isStream
)
coroutineScope {
defaultChain.invokeAndConnect(
coroutineScope = this,
chain = this@MapReduceChain,
text = combinedChunks
)
}
}
private suspend fun processAndTrackChunks(
outputChunks: List<String>, onProcessedCountUpdated: (Int) -> Unit
): List<String> {
val deferredChunks = mutableListOf<Deferred<String>>()
val processedChunks = mutableListOf<String>()
val mutex = Mutex() // For thread-safe operations on processedChunks
var completedCount = 0 // Track completed deferred tasks
coroutineScope {
for (chunk in outputChunks) {
val chunkChatPrompts = chunkPrompt.createPrompts(
DEFAULT_TEXT_PLACEHOLDER to chunk
)
val deferred = async {
val result = langDroidModel.generateText(chunkChatPrompts).getOrThrow()
mutex.withLock {
processedChunks.add(result) // Safely add result to processed list
completedCount++ // Increment completed counter
onProcessedCountUpdated(completedCount)
}
result
}
deferredChunks.add(deferred)
}
}
return processedChunks // Return the processed chunks directly
}
}
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/base/TextProcessingChain.kt | 841701170 | package com.langdroid.summary.chains.base
import com.langdroid.summary.chains.states.SummaryChainState
internal abstract class TextProcessingChain : BaseChain<SummaryChainState>() {
protected fun processText(text: String) =
processingState.tryEmit(SummaryChainState.Output(text))
protected fun processFailure(t: Throwable) =
processingState.tryEmit(SummaryChainState.Failure(t))
protected fun processWarning(warning: String) =
processingState.tryEmit(SummaryChainState.Warning(warning))
}
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/base/BaseChain.kt | 2479467496 | package com.langdroid.summary.chains.base
import com.langdroid.summary.chains.states.ChainState
import com.langdroid.summary.chains.states.SummaryChainState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
internal abstract class BaseChain<S : ChainState> : Chain<S> {
override val processingState: MutableSharedFlow<S> =
// Replay for cases when emit happened earlier than job creation completed
MutableSharedFlow(replay = 2, extraBufferCapacity = 1000)
override suspend fun invokeAndConnect(
coroutineScope: CoroutineScope, chain: Chain<*>,
text: String, onMap: ((S) -> ChainState?)?
) {
val job = coroutineScope.launch {
processingState.onEach { state ->
val mappedState = onMap?.invoke(state)
if (onMap != null && mappedState == null) {
// Ignore this update
} else {
(chain.processingState as MutableSharedFlow).tryEmit(mappedState ?: state)
}
if (state is SummaryChainState.Finished || state is SummaryChainState.Failure) {
cancel()
}
}.collect()
}
invoke(text)
job.join()
}
protected fun updateState(state: S) {
processingState.tryEmit(state)
}
}
|
LangDroid/summary/src/commonMain/kotlin/com/langdroid/summary/chains/base/Chain.kt | 3227545747 | package com.langdroid.summary.chains.base
import com.langdroid.summary.chains.states.ChainState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
public const val DEFAULT_TEXT_PLACEHOLDER: String = "text"
internal interface Chain<S> {
suspend operator fun invoke(text: String)
suspend fun invokeAndConnect(
coroutineScope: CoroutineScope,
chain: Chain<*>,
text: String,
onMap: ((S) -> ChainState?)? = null
) {
}
val processingState: Flow<S>
}
|
LangDroid/summary/src/commonTest/kotlin/com/langdroid/summary/extensions.kt | 492125672 | package com.langdroid.summary
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
const val DEFAULT_DELAY = 250L
internal fun stringToStreamFlowGenerator(
text: String,
chunkSize: Int
): (isDelay: Boolean) -> Flow<String> = { isDelay ->
flow {
text.chunkedSequence(chunkSize).forEachIndexed { i, chunk ->
emit(chunk)
if (isDelay && i < chunkSize) delay(DEFAULT_DELAY)
}
}
}
private fun String.chunkedSequence(pieces: Int): Sequence<String> = sequence {
val chunkSize = length / pieces
var remainder = length % pieces
var start = 0
for (i in 1..pieces) {
val end = start + chunkSize + if (remainder > 0) 1 else 0
if (remainder > 0) remainder-- // Decrement remainder until it's distributed
yield(substring(start, end))
start = end
}
}
|
LangDroid/summary/src/commonTest/kotlin/com/langdroid/summary/Mocks.kt | 1477413269 | package com.langdroid.summary
import com.langdroid.core.ChatPrompt
import com.langdroid.core.LangDroidModel
import com.langdroid.core.models.openai.OpenAiModel
import com.langdroid.core.models.request.config.GenerativeConfig
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
internal object Mocks {
private const val chunks = 3
private const val tokensTest = 1000
const val text1 = "Hello, can I help you?"
const val text2 = "Hello, weather is good today"
const val MOCK_TEXT = "Wow!"
suspend fun createModelNormalWithList(
text: String = text1,
isStream: Boolean = true,
isTestCompleteness: Boolean = false,
isReduceText: Boolean = false
): Pair<LangDroidModel<*>, List<SummaryState>> {
val model: LangDroidModel<*> = mockk()
val openAiModel: OpenAiModel.Gpt3_5 = mockk()
val config: GenerativeConfig<*> = mockk()
every { openAiModel.tokenLimit } returns tokensTest * (if (isReduceText) 1 else 3)
every { openAiModel.outputTokenLimit } returns tokensTest
every { config.maxOutputTokens } returns tokensTest
every { model.model } returns openAiModel
every { model.config } returns config
val flowGenerator = stringToStreamFlowGenerator(text, chunks)
coEvery { model.generateText(any<String>()) } coAnswers {
delay(DEFAULT_DELAY)
Result.success(text)
}
coEvery { model.generateTextStream(any<String>()) } returns Result.success(
flowGenerator(true)
)
coEvery { model.generateText(any<List<ChatPrompt>>()) } coAnswers {
delay(DEFAULT_DELAY)
Result.success(text)
}
coEvery { model.generateTextStream(any<List<ChatPrompt>>()) } returns Result.success(
flowGenerator(true)
)
coEvery { model.sanityCheck() } returns true
coEvery { model.calculateTokens(any<List<ChatPrompt>>()) } returns Result.success(42)
return model to generateListForText(
text,
isStream,
isReduceText,
isTestCompleteness,
flowGenerator
)
}
private suspend fun generateListForText(
text: String,
isStream: Boolean,
isReduceText: Boolean,
isTestCompleteness: Boolean,
flowGenerator: (Boolean) -> Flow<String>
): List<SummaryState> {
val outputItems =
if (isStream) flowGenerator(false).take(count = chunks).toList() else listOf(text)
return defaultStatesBefore(isStream, isReduceText) + outputItems
.map { SummaryState.Output(it) } + defaultStatesAfter(isTestCompleteness)
}
private fun defaultStatesBefore(isStream: Boolean, isReduceText: Boolean): List<SummaryState> =
if (isReduceText) {
listOf(SummaryState.TextSplitting, SummaryState.Reduce(1, 1))
} else {
listOf()
} + if (!isStream) {
listOf(SummaryState.Summarizing)
} else {
listOf()
}
private fun defaultStatesAfter(isTestCompleteness: Boolean): List<SummaryState> =
if (isTestCompleteness) listOf() else listOf(SummaryState.Success)
}
|
LangDroid/summary/src/commonTest/kotlin/com/langdroid/summary/TestSummaryChain.kt | 3290272536 | package com.langdroid.summary
import app.cash.turbine.test
import com.langdroid.core.LangDroidModel
import com.langdroid.summary.Mocks.MOCK_TEXT
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
class TestSummaryChain {
// Way to check if returned states are correct
private fun runSummaryChainTest(
description: String,
isStream: Boolean,
setup: suspend TestScope.() -> Pair<LangDroidModel<*>, List<SummaryState>>
) = runTest {
val (model, expectedStates) = setup()
val summaryChain = SummaryChain(model, isStream, coroutineScope = backgroundScope)
val isCompletenessTest = checkIsCompletenessTest(description)
val testFlow = if (isCompletenessTest) {
summaryChain.invokeAndGetFlow(MOCK_TEXT).takeWhile { !it.isFinished() }
} else summaryChain.invokeAndGetFlow(MOCK_TEXT)
testFlow.test {
for (state in expectedStates) {
assertEquals(state, awaitItem())
}
if (isCompletenessTest) awaitComplete()
}
}
// Scenarios with isStream = false
@Test
fun testSummariesWithStreamFalse() {
runSummaryChainTest("Normal", false) {
Mocks.createModelNormalWithList(isStream = false)
}
}
@Test
fun testSummariesCompleteWithStreamFalse() {
runSummaryChainTest("Completeness Test", false) {
Mocks.createModelNormalWithList(isStream = false, isTestCompleteness = true)
}
}
@Test
fun testSummariesReduceWithStreamFalse() {
runSummaryChainTest("Reduce Text Test", false) {
Mocks.createModelNormalWithList(isStream = false, isReduceText = true)
}
}
// Scenarios with isStream = true
@Test
fun testSummariesWithStreamTrue() {
runSummaryChainTest("Normal", true) {
Mocks.createModelNormalWithList(isStream = true)
}
}
@Test
fun testSummariesCompleteWithStreamTrue() {
runSummaryChainTest("Completeness Test", true) {
Mocks.createModelNormalWithList(isStream = true, isTestCompleteness = true)
}
}
@Test
fun testSummariesReduceWithStreamTrue() {
runSummaryChainTest("Reduce Text Test", true) {
Mocks.createModelNormalWithList(isStream = true, isReduceText = true)
}
}
private fun checkIsCompletenessTest(description: String) =
description.contains("complete", true)
}
|
LangDroid/summary/src/androidMain/kotlin/com/langdroid/summary/extensions.kt | 550408188 | package com.langdroid.summary
import androidx.lifecycle.LiveData
import androidx.lifecycle.asLiveData
public fun SummaryChain<*>.liveData(): LiveData<SummaryState> =
processingState.asLiveData()
|
BriefBeat/app/src/androidTest/java/com/example/briefbeat/ExampleInstrumentedTest.kt | 1279489379 | package com.example.briefbeat
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.briefbeat", appContext.packageName)
}
} |
BriefBeat/app/src/test/java/com/example/briefbeat/ExampleUnitTest.kt | 607326668 | package com.example.briefbeat
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
BriefBeat/app/src/main/java/com/example/briefbeat/Articles.kt | 1311483383 | package com.example.briefbeat
class Articles(
@JvmField var title: String,
@JvmField var description: String,
@JvmField var urlToImage: String,
@JvmField var getUrlToImage: String,
@JvmField var content: String
)
|
BriefBeat/app/src/main/java/com/example/briefbeat/NewsModal.kt | 3225005743 | package com.example.briefbeat
class NewsModal(var totalResults: Int, var status: String, var articles: ArrayList<Articles>)
|
BriefBeat/app/src/main/java/com/example/briefbeat/MainActivity.kt | 3425714526 | package com.example.briefbeat
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MainActivity : AppCompatActivity(),CategoryRVAdapter.CategoryClickInterface {
private lateinit var newsRV: RecyclerView
private lateinit var categoryRV: RecyclerView
private lateinit var progressbar:ProgressBar
private lateinit var articlesArrayList:ArrayList<Articles>
private lateinit var categoryModalArrayList:ArrayList<CategoryModal>
private lateinit var categoryRVAdapter: CategoryRVAdapter
private lateinit var newsRVAdapter: NewsRVAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//db223ddb2c07443686bfdc750ab4846a
setContentView(R.layout.activity_main)
newsRV=findViewById(R.id.vRV)
categoryRV=findViewById(R.id.hRV)
progressbar=findViewById(R.id.Pbar)
articlesArrayList = ArrayList<Articles>()
categoryModalArrayList=ArrayList<CategoryModal>()
categoryRVAdapter = CategoryRVAdapter(categoryModalArrayList, this, this::onCategoryClick)
newsRVAdapter= NewsRVAdapter(articlesArrayList,this)
newsRV.layoutManager = LinearLayoutManager(this)
newsRV.adapter=newsRVAdapter
categoryRV.adapter=categoryRVAdapter
getCategories()
getNews("All")
newsRVAdapter.notifyDataSetChanged()
}
fun getCategories(){
categoryModalArrayList.add(CategoryModal("All","https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT5_jbTu9KqPs28Pp-IYY1uskfhHTLbnqW0Ug&usqp=CAU"))
categoryModalArrayList.add(CategoryModal("Science","https://assets.technologynetworks.com/production/dynamic/images/content/368887/science-is-becoming-less-disruptive-368887-960x540.jpg?cb=12105518"))
categoryModalArrayList.add(CategoryModal("Technology","https://www.tofler.in/blog/wp-content/uploads/2023/08/technology.jpg"))
categoryModalArrayList.add(CategoryModal("General","https://assets.weforum.org/global_future_council/image/FAdBujGNsB9kx8aa04DoOi3g5mnmf-OkZPy_0idrKMI.jpg"))
categoryModalArrayList.add(CategoryModal("Sports","https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSKAkSRStDdnOJFFQBbhszGokRz5ADw4Btt4eNsXm-H393llFKh56mkpq9DHOp8vKrNqKY&usqp=CAU"))
categoryModalArrayList.add(CategoryModal("Business","https://cloudinary.hbs.edu/hbsit/image/upload/s--EmT0lNtW--/f_auto,c_fill,h_375,w_750,/v20200101/6978C1C20B650473DD135E5352D37D55.jpg"))
categoryModalArrayList.add(CategoryModal("Health","https://imageio.forbes.com/specials-images/imageserve/638ee3f77ab30981d50d997c/The-Top-5-Healthcare-Trends-In-2023/960x0.jpg?height=399&width=711&fit=bounds"))
categoryModalArrayList.add(CategoryModal("Entertainment","https://etimg.etb2bimg.com/photo/75690061.cms"))
categoryRVAdapter.notifyDataSetChanged()
}
private fun getNews(category: String) {
progressbar.visibility= View.VISIBLE
articlesArrayList.clear()
val categoryURL =
"https://newsapi.org/v2/top-headlines?country=in&category=$category&apikey=db223ddb2c07443686bfdc750ab4846a"
val url="https://newsapi.org/v2/top-headlines?country=in&excludeDomains=stackoverflow.com&sortBy=publishedAt&language=en&apikey=db223ddb2c07443686bfdc750ab4846a"
val Base_URL="https://newsapi.org/"
val retrofit = Retrofit.Builder().baseUrl(Base_URL).addConverterFactory(GsonConverterFactory.create()).build()
val retrofitAPI = retrofit.create(RetrofitAPI::class.java)
val call: Call<NewsModal?>? = if (category == "All") {
retrofitAPI.getAllNews(url)
} else {
retrofitAPI.getNewsByCategory(categoryURL)
}
call?.enqueue(object : Callback<NewsModal?> {
override fun onResponse(call: Call<NewsModal?>, response: Response<NewsModal?>) {
val newsModal = response.body()
progressbar.visibility= View.GONE
val articles: ArrayList<Articles> = newsModal!!.articles
for (i in 0 until articles.size) {
val article = articles[i]
articlesArrayList.add(Articles(article.title, article.description,
article.urlToImage,article.getUrlToImage,article.content))
}
newsRVAdapter.notifyDataSetChanged()
}
override fun onFailure(call: Call<NewsModal?>, t: Throwable) {
Toast.makeText(this@MainActivity, "Oops something went wrong!", Toast.LENGTH_SHORT).show() }
})
}
override fun onCategoryClick(position: Int) {
val category = categoryModalArrayList[position].category
getNews(category)
}
} |
BriefBeat/app/src/main/java/com/example/briefbeat/SplashScreenActivity.kt | 1955042119 | package com.example.briefbeat
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.text.PrecomputedText.Params
import android.view.WindowManager
import android.widget.ImageView
class SplashScreenActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
// val icon=findViewById<ImageView>(R.id.splash_icon)
// supportActionBar?.hide()
// window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
// Handler().postDelayed({
val icon=findViewById<ImageView>(R.id.splash_icon)
icon.alpha=1f;
icon.animate().setDuration(4000).alpha(1f).withEndAction{
val i= Intent(this,MainActivity::class.java)
startActivity(i)
finish()
}
// }, 2000)
}
} |
BriefBeat/app/src/main/java/com/example/briefbeat/CategoryModal.kt | 1045806630 | package com.example.briefbeat
class CategoryModal(@JvmField var category: String, @JvmField var categoryImageURL: String)
|
BriefBeat/app/src/main/java/com/example/briefbeat/NewsDetailActivity.kt | 2683519397 | package com.example.briefbeat
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.squareup.picasso.Picasso
class NewsDetailActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_news_detail)
val title = intent.getStringExtra("title")
val des = intent.getStringExtra("description")
val content = intent.getStringExtra("content")
val imageURL = intent.getStringExtra("image")
val url = intent.getStringExtra("url")
val titleTV = findViewById<TextView>(R.id.newsTitle)
val subTitle = findViewById<TextView>(R.id.newsSubtitle)
val desc = findViewById<TextView>(R.id.newsDes)
val newsImg = findViewById<ImageView>(R.id.newsImg)
val newsBtn = findViewById<Button>(R.id.newsButton)
titleTV.text = title
subTitle.text = des
desc.text = content
Picasso.get().load(imageURL).into(newsImg)
newsBtn.setOnClickListener {
val i = Intent(Intent.ACTION_VIEW)
i.setData(Uri.parse(url))
startActivity(i)
}
}
} |
BriefBeat/app/src/main/java/com/example/briefbeat/NewsRVAdapter.kt | 1243490040 | package com.example.briefbeat
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
class NewsRVAdapter(
private val articlesArrayList: ArrayList<Articles>,
private val context: Context
) : RecyclerView.Adapter<NewsRVAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.news, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val articles = articlesArrayList[position]
holder.subtitleTV.text = articles.description
holder.titleTV.text = articles.title
Picasso.get().load(articles.urlToImage).into(holder.newsIV)
holder.itemView.setOnClickListener {
val intent = Intent(context, NewsDetailActivity::class.java)
intent.putExtra("title", articles.title)
intent.putExtra("content", articles.content)
intent.putExtra("description", articles.description)
intent.putExtra("image", articles.urlToImage)
intent.putExtra("url", articles.getUrlToImage)
context.startActivity(intent)
}
}
override fun getItemCount(): Int {
return articlesArrayList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val titleTV: TextView
val subtitleTV: TextView
val newsIV: ImageView
init {
titleTV = itemView.findViewById(R.id.newsText)
subtitleTV = itemView.findViewById(R.id.newsDes)
newsIV = itemView.findViewById(R.id.newsImage)
}
}
}
|
BriefBeat/app/src/main/java/com/example/briefbeat/CategoryRVAdapter.kt | 955811412 | package com.example.briefbeat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
class CategoryRVAdapter(
private val categoryModal: List<CategoryModal>,
private val categoryClickInterface: CategoryClickInterface,
kFunction1: (Int) -> Unit
) : RecyclerView.Adapter<CategoryRVAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.categories, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val categoryModal1 = categoryModal[position]
holder.categoryTV.text = categoryModal1.category
Picasso.get().load(categoryModal1.categoryImageURL).into(holder.categoryIV)
holder.itemView.setOnClickListener { categoryClickInterface.onCategoryClick(position) }
}
override fun getItemCount(): Int {
return categoryModal.size
}
interface CategoryClickInterface {
fun onCategoryClick(position: Int)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val categoryTV: TextView
val categoryIV: ImageView
init {
categoryIV = itemView.findViewById(R.id.catImage)
categoryTV = itemView.findViewById(R.id.catText)
}
}
}
|
BriefBeat/app/src/main/java/com/example/briefbeat/RetrofitAPI.kt | 3720473567 | package com.example.briefbeat
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Url
interface RetrofitAPI {
@GET
fun getAllNews(@Url url: String?): Call<NewsModal?>?
@GET
fun getNewsByCategory(@Url url: String?): Call<NewsModal?>?
// Add a relative path for the base URL
companion object {
const val BASE_URL = "https://newsapi.org/"
}
}
|
FinLedgerPublic/core/src/androidTest/java/com/evicky/core/ExampleInstrumentedTest.kt | 3364122584 | package com.evicky.core
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.evicky.core.test", appContext.packageName)
}
} |
FinLedgerPublic/core/src/test/java/com/evicky/core/ExampleUnitTest.kt | 1965860362 | package com.evicky.core
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
FinLedgerPublic/core/src/main/java/com/evicky/core/dataSource/DataSource.kt | 2787477708 | package com.evicky.core.dataSource
import com.evicky.utility.logger.Log
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
interface IDataSource {
suspend fun writeData(
documentPath: String,
data: Any,
logTag: String,
writeSuccessLogMessage: String,
writeFailureLogMessage: String
): Boolean
suspend fun readData(logTag: String, documentPath: String): Map<String, Any>?
suspend fun deleteData(
documentPath: String,
logTag: String,
writeFailureLogMessage: String
): Boolean
}
class Firestore : IDataSource {
// private val fireStore: FirebaseFirestore = FirebaseFirestore.getInstance()
override suspend fun writeData(
documentPath: String,
data: Any,
logTag: String,
writeSuccessLogMessage: String,
writeFailureLogMessage: String,
) = suspendCancellableCoroutine { continuation ->
try {
// fireStore.document(documentPath).set(data)
// .addOnCompleteListener { task ->
// if (task.isSuccessful) {
// Log.i(logTag, "Data write success to firestore db $writeSuccessLogMessage: $documentPath")
// if (continuation.isActive) continuation.resume(true)
// } else {
// Log.e(logTag,
// "Data write failed to firestore db $writeFailureLogMessage: $documentPath. Error Message: ${task.exception?.message}",
// task.exception)
// if (continuation.isActive) continuation.resume(false)
// }
// }
// sendSuccessResultIfOfflineForDocumentWrite(fireStore.document(documentPath), continuation)
} catch (exception: Exception) {
Log.e(logTag,
"Exception from execution: Data write failed to firestore db. $writeFailureLogMessage: $documentPath. Error Message: ${exception.message}",
exception)
if (continuation.isActive) continuation.resume(false)
}
}
override suspend fun readData(logTag: String, documentPath: String): Map<String, Any>? =
// fireStore.document(documentPath).get().await().data
null
override suspend fun deleteData(
documentPath: String,
logTag: String,
writeFailureLogMessage: String,
) = suspendCancellableCoroutine { continuation ->
try {
// fireStore.document(documentPath).delete()
// .addOnCompleteListener { task ->
// if (task.isSuccessful) {
// Log.i(logTag, "Delete Success in firestore db: $documentPath")
// if (continuation.isActive) continuation.resume(true)
// } else {
// Log.e(logTag,
// "Delete Failure in firestore db: $writeFailureLogMessage: $documentPath. Error Message: ${task.exception?.message}",
// task.exception)
// if (continuation.isActive) continuation.resume(false)
// }
//
// }
} catch (exception: Exception) {
Log.e(logTag,
"Exception from execution: Delete Failure in firestore db: $writeFailureLogMessage: $documentPath. Error Message: ${exception.message}",
exception)
if (continuation.isActive) continuation.resume(false)
}
}
}
/**
* While the device is in offline we won't get success or failure task result for writes to firestore.
* So getting the meta data to send the result back to the caller if the data is from cache.
*/
//fun sendSuccessResultIfOfflineForDocumentWrite(
// documentReference: DocumentReference,
// continuation: CancellableContinuation<Boolean>
//) {
// documentReference.get().addOnSuccessListener {
// if (it.metadata.isFromCache && continuation.isActive) continuation.resume(true)
// }
//}
class DynamoDb : IDataSource {
override suspend fun writeData(
documentPath: String,
data: Any,
logTag: String,
writeSuccessLogMessage: String,
writeFailureLogMessage: String,
): Boolean {
Log.i(logTag, "Data write success to dynamo db $writeSuccessLogMessage: $documentPath")
return true
}
override suspend fun readData(logTag: String, documentPath: String): Map<String, Any>? {
Log.i(logTag, "Data read success from dynamo db $documentPath")
return null
}
override suspend fun deleteData(
documentPath: String,
logTag: String,
writeFailureLogMessage: String,
): Boolean {
Log.i(logTag, "Data delete success in dynamo db $documentPath")
return true
}
} |
FinLedgerPublic/core/src/main/java/com/evicky/core/di/DiKoin.kt | 2635334684 | package com.evicky.core.di
import com.evicky.core.dataSource.DynamoDb
import com.evicky.core.dataSource.Firestore
import com.evicky.core.repo.ISignInRepo
import com.evicky.core.repo.SignInRepo
import com.evicky.core.usecase.SignInUseCase
import com.evicky.utility.utils.CoroutineDispatcherProvider
import com.evicky.utility.utils.ICoroutineDispatcherProvider
import org.koin.core.module.dsl.bind
import org.koin.core.module.dsl.factoryOf
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.module
val useCaseModule = module {
factoryOf(::SignInUseCase)
}
val repoModule = module {
factoryOf(::SignInRepo) { bind<ISignInRepo>() }
}
val dataSourceModule = module {
singleOf(::Firestore)
singleOf(::DynamoDb)
}
val coroutineDispatcherProviderModule = module {
singleOf(::CoroutineDispatcherProvider) { bind<ICoroutineDispatcherProvider>()}
} |
FinLedgerPublic/core/src/main/java/com/evicky/core/model/local/SignInLocalData.kt | 212399414 | package com.evicky.core.model.local
data class SignInLocalData(val id: Long, val name: String) |
FinLedgerPublic/core/src/main/java/com/evicky/core/model/remote/SignInRemoteData.kt | 1183121100 | package com.evicky.core.model.remote
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class SignInRemoteData(val id: Long, val name: String, val address: String, val occupation: String): Parcelable |
FinLedgerPublic/core/src/main/java/com/evicky/core/usecase/SignInUseCase.kt | 2256420234 | package com.evicky.core.usecase
import com.evicky.core.model.local.SignInLocalData
import com.evicky.core.model.remote.SignInRemoteData
import com.evicky.core.repo.ISignInRepo
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
class SignInUseCase(private val signInRepo: ISignInRepo) {
suspend fun writeData(data: SignInLocalData, logTag: String): Boolean {
return signInRepo.writeData(documentPath = "Users/UserId", data = data, logTag = logTag)
}
suspend fun readData(path: String, logTag: String): SignInLocalData {
val signInRemoteData = Json.decodeFromString<SignInRemoteData>(signInRepo.readData(logTag = logTag, path = path).toString())
return SignInLocalData(id = signInRemoteData.id, name = signInRemoteData.name)
}
} |
FinLedgerPublic/core/src/main/java/com/evicky/core/repo/SignInRepo.kt | 29047448 | package com.evicky.core.repo
import com.evicky.core.dataSource.DynamoDb
import com.evicky.core.dataSource.Firestore
import com.evicky.core.dataSource.IDataSource
import com.evicky.core.model.local.SignInLocalData
interface ISignInRepo {
suspend fun writeData(documentPath: String, data: SignInLocalData, logTag: String): Boolean
suspend fun readData(logTag: String, path: String): Map<String, Any>
}
class SignInRepo(firestore: Firestore, dynamoDb: DynamoDb): ISignInRepo {
private val isPremiumUser = false // This data may come from some other data source
private val dataSource: IDataSource = if (isPremiumUser) dynamoDb else firestore
override suspend fun writeData(documentPath: String, data: SignInLocalData, logTag: String): Boolean = dataSource.writeData(
documentPath = documentPath, data = data, logTag = logTag, writeSuccessLogMessage = "Data written successfully", writeFailureLogMessage = "Data write failed")
override suspend fun readData(logTag: String, path: String): Map<String, Any> = dataSource.readData(logTag, documentPath = path) ?: mapOf()
} |
FinLedgerPublic/app/src/androidTest/java/com/evicky/financeledger/ExampleInstrumentedTest.kt | 2565727763 | package com.evicky.financeledger
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.evicky.financeledger", appContext.packageName)
}
} |
FinLedgerPublic/app/src/test/java/com/evicky/financeledger/ExampleUnitTest.kt | 1859841968 | package com.evicky.financeledger
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/ui/theme/Color.kt | 4237046476 | package com.evicky.financeledger.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) |
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/ui/theme/Theme.kt | 3492488416 | package com.evicky.financeledger.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun FinanceLedgerTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} |
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/ui/theme/Type.kt | 2620877852 | package com.evicky.financeledger.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) |
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/MainActivity.kt | 1610759643 | package com.evicky.financeledger
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.evicky.financeledger.root.RootHost
import com.evicky.financeledger.ui.theme.FinanceLedgerTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FinanceLedgerTheme {
RootHost()
}
}
}
} |
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/root/RootHost.kt | 2205440914 | package com.evicky.financeledger.root
import androidx.compose.runtime.Composable
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import com.evicky.feature.signIn.signInNavGraph
import com.evicky.feature.postlogin.navigateToPostLoginScreen
import com.evicky.feature.postlogin.postLoginNavGraph
import com.evicky.feature.util.SIGNIN_ROUTE
@Composable
internal fun RootHost() {
val rootController = rememberNavController()
NavHost(
navController = rootController,
startDestination = SIGNIN_ROUTE,
) {
signInNavGraph(
onSignInPress = {
rootController.navigateToPostLoginScreen(it)
}
)
postLoginNavGraph()
}
} |
FinLedgerPublic/app/src/main/java/com/evicky/financeledger/application/FinanceLedgerApplication.kt | 3407825699 | package com.evicky.financeledger.application
import android.app.Application
import com.evicky.core.di.coroutineDispatcherProviderModule
import com.evicky.core.di.dataSourceModule
import com.evicky.core.di.repoModule
import com.evicky.core.di.useCaseModule
import com.evicky.feature.di.viewModelModule
import org.koin.core.context.startKoin
class FinanceLedgerApplication: Application() {
override fun onCreate() {
super.onCreate()
// FirebaseApp.initializeApp(this)
startKoin {
modules(
dataSourceModule, repoModule, useCaseModule, viewModelModule, coroutineDispatcherProviderModule
)
}
}
} |
FinLedgerPublic/buildSrc/src/main/kotlin/CustomConventionGradlePlugin.kt | 48529178 | import org.gradle.api.Plugin
import org.gradle.api.Project
enum class ModuleType {
Application,
AndroidLibrary,
JavaOrKotlinLibrary
}
class ApplicationGradlePlugin: Plugin<Project> {
override fun apply(project: Project) {
applyCommonPlugins(project)
project.configureAndroidWithCompose(ModuleType.Application)
}
}
class LibraryGradlePlugin: Plugin<Project> {
override fun apply(project: Project) {
applyCommonPlugins(project)
project.configureAndroidWithCompose(ModuleType.AndroidLibrary)
}
}
internal fun applyCommonPlugins(project: Project) {
project.apply {
plugin("kotlin-android")
plugin("kotlin-kapt")
}
}
|
FinLedgerPublic/buildSrc/src/main/kotlin/AndroidGradleConfig.kt | 122905427 | import com.android.build.api.dsl.ApplicationExtension
import com.android.build.gradle.LibraryExtension
import org.gradle.api.JavaVersion
import org.gradle.api.Project
private const val COMPILE_SDK_VERSION = 34
private const val MIN_SDK_VERSION = 24
private const val TARGET_SDK_VERSION = 34
private const val VERSION_CODE = 1
private const val VERSION_NAME = "1.0"
const val KOTLIN_COMPILER_EXTENSION_VERSION = "1.5.6"
private const val TEST_INSTRUMENTATION_RUNNER = "androidx.test.runner.AndroidJUnitRunner"
internal fun Project.configureAndroidWithCompose(moduleType: ModuleType) {
when (moduleType) {
ModuleType.Application -> {
project.extensions.getByType(ApplicationExtension::class.java).apply {
compileSdk = COMPILE_SDK_VERSION
defaultConfig {
applicationId = "com.evicky.financeledger"
minSdk = MIN_SDK_VERSION
targetSdk = TARGET_SDK_VERSION
versionCode = VERSION_CODE
versionName = VERSION_NAME
testInstrumentationRunner = TEST_INSTRUMENTATION_RUNNER
vectorDrawables {
useSupportLibrary = true
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = KOTLIN_COMPILER_EXTENSION_VERSION
}
}
}
ModuleType.AndroidLibrary -> {
project.extensions.getByType(LibraryExtension::class.java).apply {
compileSdk = COMPILE_SDK_VERSION
defaultConfig {
minSdk = MIN_SDK_VERSION
testInstrumentationRunner = TEST_INSTRUMENTATION_RUNNER
consumerProguardFiles("consumer-rules.pro")
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
// compose feature is enabled only for the library modules which requires it
}
ModuleType.JavaOrKotlinLibrary -> {
// No-op
}
}
} |
FinLedgerPublic/feature/src/androidTest/java/com/evicky/feature/ExampleInstrumentedTest.kt | 470579217 | package com.evicky.feature
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.evicky.feature.test", appContext.packageName)
}
} |
FinLedgerPublic/feature/src/test/java/com/evicky/feature/ExampleUnitTest.kt | 3617261421 | package com.evicky.feature
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
FinLedgerPublic/feature/src/main/java/com/evicky/feature/di/DiKoin.kt | 229539962 | package com.evicky.feature.di
import com.evicky.feature.signIn.SignInViewModel
import org.koin.androidx.viewmodel.dsl.viewModelOf
import org.koin.dsl.module
val viewModelModule = module {
viewModelOf(::SignInViewModel)
} |
FinLedgerPublic/feature/src/main/java/com/evicky/feature/util/Constants.kt | 2643517000 | package com.evicky.feature.util
const val SIGNIN_ROUTE = "login"
const val POST_LOGIN_ROUTE = "postlogin" |
FinLedgerPublic/feature/src/main/java/com/evicky/feature/signIn/SignInGraph.kt | 4274104900 | package com.evicky.feature.signIn
import androidx.compose.runtime.getValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import com.evicky.feature.util.SIGNIN_ROUTE
import org.koin.androidx.compose.koinViewModel
fun NavGraphBuilder.signInNavGraph(
onSignInPress: (String) -> Unit
) {
composable(route = SIGNIN_ROUTE) {
val viewModel: SignInViewModel = koinViewModel()
val loginUiState by viewModel.signInUiState.collectAsStateWithLifecycle()
SignInScreen(
signInUiState = loginUiState,
onSignInPress = { if (loginUiState.errorMessage.isEmpty() && loginUiState.phoneNumber.isNotEmpty()) onSignInPress.invoke(it) },
onPhoneNumberChange = { updatedValue ->
viewModel.onPhoneNumberChange(updatedValue)
}
)
}
}
|
FinLedgerPublic/feature/src/main/java/com/evicky/feature/signIn/SignInViewModel.kt | 3801390457 | package com.evicky.feature.signIn
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.evicky.core.model.local.SignInLocalData
import com.evicky.core.usecase.SignInUseCase
import com.evicky.utility.logger.Log
import com.evicky.utility.utils.CoroutineDispatcherProvider
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
data class SignInUiState(
val phoneNumber: String = "",
val isLoginSuccess: Boolean = false,
val errorMessage: String = ""
)
private const val SIGNIN_VM_SAVED_STATE_HANDLE_KEY = "signInVMSavedStateHandleKey"
private const val logTag = "SignInViewModel"
class SignInViewModel(private val savedStateHandle: SavedStateHandle, private val signInUseCase: SignInUseCase, private val coroutineDispatcherProvider: CoroutineDispatcherProvider): ViewModel() {
var signInUiState = MutableStateFlow(SignInUiState())
private set
init {
savedStateHandle.get<SignInUiState>(SIGNIN_VM_SAVED_STATE_HANDLE_KEY)?.let { signInUiState.value = it }
}
fun onPhoneNumberChange(phoneNumber: String) {
signInUiState.value = signInUiState.value.copy(phoneNumber = phoneNumber)
if (phoneNumber.length != 10) {
setPhoneNumberFieldErrorMessage("Invalid mobile number.")
} else {
setPhoneNumberFieldErrorMessage("")
}
}
private fun setPhoneNumberFieldErrorMessage(errorMessage: String) {
signInUiState.value = signInUiState.value.copy(errorMessage = errorMessage)
}
fun writeDataToDataSource() {
viewModelScope.launch(coroutineDispatcherProvider.io()) {
val isWriteSuccess = signInUseCase.writeData(data = SignInLocalData(id = 1L, name = "eVicky"), logTag = "$logTag:writeDataToDataSource")
Log.i("$logTag:writeDataToDataSource", "isWriteSuccess: $isWriteSuccess")
}
}
fun readDataFromDataSource() {
viewModelScope.launch(coroutineDispatcherProvider.io()) {
val signInLocalData = signInUseCase.readData(path = "Users/UserId", logTag = logTag)
Log.i("$logTag:readDataFromDataSource", "signInLocalData: $signInLocalData")
}
}
override fun onCleared() {
super.onCleared()
//To not to lose data during android low memory kill
savedStateHandle[SIGNIN_VM_SAVED_STATE_HANDLE_KEY] = signInUiState
}
} |
FinLedgerPublic/feature/src/main/java/com/evicky/feature/signIn/SignInScreen.kt | 3157103840 | package com.evicky.feature.signIn
import android.content.res.Configuration
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.evicky.feature.R
@Composable
internal fun SignInScreen(
signInUiState: SignInUiState,
onSignInPress: (String) -> Unit,
onPhoneNumberChange: (String) -> Unit
) {
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Image(
painter = painterResource(id = R.drawable.logo_finance_ledger),
contentDescription = "logo",
alignment = Alignment.Center,
modifier = Modifier.height(250.dp).width(250.dp).clip(CircleShape)
)
Spacer(modifier = Modifier.height(16.dp))
PhoneNumberField(signInUiState = signInUiState) { updatedValue ->
onPhoneNumberChange(updatedValue)
}
OutlinedButton(
onClick = { onSignInPress(signInUiState.phoneNumber) },
enabled = signInUiState.errorMessage.isEmpty()
) {
Text(text = stringResource(R.string.sign_in))
}
}
}
@Composable
fun PhoneNumberField(
modifier: Modifier = Modifier,
signInUiState: SignInUiState,
onPhoneNumberChange: (String) -> Unit,
) {
OutlinedTextField(
value = signInUiState.phoneNumber,
onValueChange = { updatedValue -> onPhoneNumberChange(updatedValue) },
modifier = Modifier
.fillMaxWidth()
.then(modifier.padding(horizontal = 40.dp)),
label = {
Text(text = stringResource(R.string.mobile_number))
},
leadingIcon = {
Icon(imageVector = Icons.Default.Phone, contentDescription = null)
},
isError = signInUiState.errorMessage.isNotEmpty(),
supportingText = {
Text(text = signInUiState.errorMessage, style = MaterialTheme.typography.bodySmall, color = Color.Red)
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
}
@Preview(showBackground = true, showSystemUi = false)
@Composable
private fun LoginScreenPreview() {
MaterialTheme {
SignInScreen(
signInUiState = SignInUiState(),
onSignInPress = { _ -> },
onPhoneNumberChange = { _ -> }
)
}
}
@Preview(device = "id:Nexus 7", showBackground = true,
uiMode = Configuration.UI_MODE_NIGHT_NO or Configuration.UI_MODE_TYPE_NORMAL,
showSystemUi = false
)
@Composable
private fun LoginScreenTabPreview() {
MaterialTheme {
SignInScreen(
signInUiState = SignInUiState(),
onSignInPress = { _ -> },
onPhoneNumberChange = { _ -> }
)
}
} |
FinLedgerPublic/feature/src/main/java/com/evicky/feature/postlogin/PostLoginScreen.kt | 484218302 | package com.evicky.feature.postlogin
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.evicky.feature.R
@Composable
fun PostLoginScreen(phoneNumber: String) {
Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
Row(
modifier = Modifier.fillMaxWidth().padding(50.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
OutlinedTextField(value = phoneNumber, onValueChange = {}, readOnly = true, label = {
Text(text = stringResource(R.string.mobile_number))
})
}
Text(text = "Login Success!", fontSize = 50.sp, fontFamily = FontFamily.Monospace, fontStyle = FontStyle.Italic)
}
}
@Preview(showBackground = true)
@Composable
fun PostLoginScreenPreview() {
MaterialTheme {
PostLoginScreen("23232")
}
} |
FinLedgerPublic/feature/src/main/java/com/evicky/feature/postlogin/PostLoginGraph.kt | 1919015741 | package com.evicky.feature.postlogin
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import com.evicky.feature.util.POST_LOGIN_ROUTE
fun NavController.navigateToPostLoginScreen(data: String) {
navigate("$POST_LOGIN_ROUTE/$data")
}
private const val PHONE_NO_KEY = "phoneNumberKey"
fun NavGraphBuilder.postLoginNavGraph() {
composable(route = "$POST_LOGIN_ROUTE/{$PHONE_NO_KEY}") {
val receivedPhoneNumber = it.arguments?.getString(PHONE_NO_KEY) ?: ""
PostLoginScreen(phoneNumber = receivedPhoneNumber)
}
}
|
FinLedgerPublic/utility/src/androidTest/java/com/evicky/utility/ExampleInstrumentedTest.kt | 2259566363 | package com.evicky.utility
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.evicky.utility.test", appContext.packageName)
}
} |
FinLedgerPublic/utility/src/test/java/com/evicky/utility/ExampleUnitTest.kt | 3278723020 | package com.evicky.utility
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
FinLedgerPublic/utility/src/main/java/com/evicky/utility/logger/Log.kt | 379615953 | package com.evicky.utility.logger
import android.util.Log
object Log {
fun v(tag: String, msg: String?, throwable: Throwable? = null) =
msg?.run {
Log.v(tag, this, throwable)
}
fun d(tag: String, msg: String?, throwable: Throwable? = null) =
msg?.run {
Log.d(tag, this, throwable)
}
fun i(tag: String, msg: String?, throwable: Throwable? = null) =
msg?.run {
Log.i(tag, this, throwable)
}
fun w(tag: String, msg: String?, throwable: Throwable? = null) =
msg?.run {
Log.w(tag, this, throwable)
}
fun e(tag: String, msg: String?, throwable: Throwable? = null) =
msg?.run {
Log.e(tag, this, throwable)
}
} |
FinLedgerPublic/utility/src/main/java/com/evicky/utility/network/InternetConnectionStatus.kt | 2934675006 | package com.evicky.utility.network
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.ProducerScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import java.net.URL
import javax.net.ssl.HttpsURLConnection
private const val TAG = "InternetConnectionStatus"
private const val PING_TIMEOUT = 5000
private const val NO_CONTENT_ERR_CODE = 204
private const val EXCEPTION_RETRY_DELAY = 2_000L
private const val MAX_EXCEPTION_RETRY_COUNT = 10
private const val NO_CONTENT_REQUEST_URL = "https://clients3.google.com/generate_204"
@OptIn(ExperimentalCoroutinesApi::class)
class InternetConnectionStatus(context: Context) {
private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private var connectExceptionRetryCount = 0
/**
* Memoization variable to help exception retry recursion function.
* If we get positive response for internet connectivity then this will be returned
* insteadof negative values from recursion stack. This will be reset upon recursion completion
* and on network lost callback.
*/
private var hasActiveInternet = false
val networkStatus = callbackFlow {
val networkStatusCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
val hasInternetCapability = hasInternetCapabilities(connectivityManager, network)
if (hasInternetCapability.not()) {
return
}
checkForInternetConnectivity("onAvailable", this@callbackFlow)
}
override fun onLost(network: Network) {
trySend(false)
hasActiveInternet = false
}
override fun onUnavailable() {
checkForInternetConnectivity("onUnavailable", this@callbackFlow)
}
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
checkForInternetConnectivity("onCapabilitiesChanged", this@callbackFlow)
}
}
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
.build()
connectivityManager.registerNetworkCallback(request, networkStatusCallback)
awaitClose {
connectivityManager.unregisterNetworkCallback(networkStatusCallback)
}
}.distinctUntilChanged()
fun checkForInternetConnectivity(source: String, producerScope: ProducerScope<Boolean>) {
producerScope.launch(CoroutineName(this.javaClass.name) + Dispatchers.IO) {
val hasInternet = pingGoogleToGetInternetConnectivityStatus()
producerScope.trySend(hasInternet)
hasActiveInternet = false
}
}
@Suppress("DEPRECATION")
fun hasInternetCapabilities(connectivityManager: ConnectivityManager, network: Network): Boolean =
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q ->
connectivityManager.getNetworkCapabilities(network)?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false
else ->
connectivityManager.getNetworkInfo(network)?.let { networkInfo ->
return@let networkInfo.isConnected
} ?: false
}
suspend fun pingGoogleToGetInternetConnectivityStatus(): Boolean =
coroutineScope {
async(Dispatchers.IO) {
try {
val urlConnection: HttpsURLConnection = URL(NO_CONTENT_REQUEST_URL).openConnection() as HttpsURLConnection
urlConnection.setRequestProperty("User-Agent", "Android")
urlConnection.setRequestProperty("Connection", "close")
urlConnection.connectTimeout = PING_TIMEOUT
urlConnection.connect()
hasActiveInternet = urlConnection.responseCode == NO_CONTENT_ERR_CODE && urlConnection.contentLength == 0
hasActiveInternet
} catch (e: Exception) {
delay(EXCEPTION_RETRY_DELAY)
if (connectExceptionRetryCount < MAX_EXCEPTION_RETRY_COUNT) {
connectExceptionRetryCount += 1
pingGoogleToGetInternetConnectivityStatus()
}
hasActiveInternet
}
}.await()
}
} |
FinLedgerPublic/utility/src/main/java/com/evicky/utility/utils/CoroutineDispatcherProvider.kt | 3739843480 | package com.evicky.utility.utils
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
interface ICoroutineDispatcherProvider {
fun main(): CoroutineDispatcher = Dispatchers.Main
fun mainImmediate(): CoroutineDispatcher = Dispatchers.Main.immediate
fun default(): CoroutineDispatcher = Dispatchers.Default
fun io(): CoroutineDispatcher = Dispatchers.IO
fun unconfined(): CoroutineDispatcher = Dispatchers.Unconfined
}
class CoroutineDispatcherProvider : ICoroutineDispatcherProvider
class TestCoroutineDispatcherProvider : ICoroutineDispatcherProvider {
// override fun main(): CoroutineDispatcher = UnconfinedTestDispatcher()
// override fun default(): CoroutineDispatcher = UnconfinedTestDispatcher()
// override fun io(): CoroutineDispatcher = UnconfinedTestDispatcher()
// override fun unconfined(): CoroutineDispatcher = UnconfinedTestDispatcher()
} |
FinLedgerPublic/utility/src/main/java/com/evicky/utility/utils/Constants.kt | 2539674331 | package com.evicky.utility.utils
|
custom_Dialog/app/src/androidTest/java/in/instea/customdialog/ExampleInstrumentedTest.kt | 3265203503 | package `in`.instea.customdialog
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("in.instea.customdialog", appContext.packageName)
}
} |
custom_Dialog/app/src/test/java/in/instea/customdialog/ExampleUnitTest.kt | 1589922886 | package `in`.instea.customdialog
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
custom_Dialog/app/src/main/java/in/instea/customdialog/MainActivity.kt | 4175291066 | package `in`.instea.customdialog
import android.app.Dialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
lateinit var dialog: Dialog
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var showBtn = findViewById<Button>(R.id.openDialog_button)
showBtn.setOnClickListener { }
dialog = Dialog(this)
dialog.setContentView(R.layout.custom_dialog)
// dialog.window?.setBackgroundDrawable(getDrawable(R.drawable.dialog_bg))
dialog.window?.setBackgroundDrawableResource(R.drawable.dialog_bg)
val feedbackBtn = dialog.findViewById<Button>(R.id.btnFeedback)
val goodBtn = dialog.findViewById<Button>(R.id.btnGood)
showBtn.setOnClickListener {
dialog.show()
}
feedbackBtn.setOnClickListener {
Toast.makeText(this, "feedback sent...", Toast.LENGTH_SHORT).show()
dialog.dismiss()
}
goodBtn.setOnClickListener {
Toast.makeText(this, "Congratulations...", Toast.LENGTH_SHORT).show()
dialog.dismiss()
}
}
} |
Retrofitwithloginandregistraion/app/src/androidTest/java/com/example/practiceactivity/ExampleInstrumentedTest.kt | 284705448 | package com.example.practiceactivity
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.practiceactivity", appContext.packageName)
}
} |
Retrofitwithloginandregistraion/app/src/test/java/com/example/practiceactivity/ExampleUnitTest.kt | 3793318266 | package com.example.practiceactivity
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
Retrofitwithloginandregistraion/app/src/main/java/com/example/practiceactivity/MainActivity.kt | 4040741987 | package com.example.practiceactivity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import com.example.practiceactivity.databinding.ActivityMainBinding
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class MainActivity : AppCompatActivity() {
private lateinit var binding:ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.alreadyhaveaccount.setOnClickListener {
startActivity(Intent(this@MainActivity,loginActivity::class.java))
finish()
}
binding.registerbtn.setOnClickListener {
if (binding.emailet.text.toString() == "" || binding.passet.text.toString() == "") {
Toast.makeText(
this@MainActivity,
"Please Enter All Info",
Toast.LENGTH_SHORT
).show()
} else {
Firebase.auth.createUserWithEmailAndPassword(
binding.emailet.text.toString(),
binding.passet.text.toString()
)
.addOnCompleteListener {
if (it.isSuccessful) {
startActivity(Intent(this@MainActivity,HomeActivity::class.java))
finish()
} else {
Toast.makeText(
this@MainActivity,
it.exception?.localizedMessage,
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
override fun onStart() {
super.onStart()
if(Firebase.auth.currentUser!=null){
startActivity(Intent(this@MainActivity,HomeActivity::class.java))
finish()
}
}
} |
Retrofitwithloginandregistraion/app/src/main/java/com/example/practiceactivity/HomeActivity.kt | 2590979542 | package com.example.practiceactivity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import com.example.practiceactivity.databinding.ActivityHomeBinding
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class HomeActivity : AppCompatActivity() {
private lateinit var binding:ActivityHomeBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityHomeBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
/* binding.logoutbtn.setOnClickListener {
Firebase.auth.signOut()
startActivity(Intent(this@HomeActivity,MainActivity::class.java))
finish()
}*/
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu,menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId){
R.id.logout -> {Firebase.auth.signOut()
startActivity(Intent(this@HomeActivity,MainActivity::class.java))
finish()}
}
return super.onOptionsItemSelected(item)
}
} |
Retrofitwithloginandregistraion/app/src/main/java/com/example/practiceactivity/splashScreen.kt | 3252710784 | package com.example.practiceactivity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
class splashScreen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
Handler(Looper.getMainLooper()).postDelayed({
startActivity(Intent(this@splashScreen,loginActivity::class.java))
finish()
},3000)
}
} |
Retrofitwithloginandregistraion/app/src/main/java/com/example/practiceactivity/loginActivity.kt | 4147235757 | package com.example.practiceactivity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.practiceactivity.databinding.ActivityLoginBinding
import com.google.android.gms.auth.api.Auth
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.GoogleApiClient
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class loginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private lateinit var mAuth: FirebaseAuth
private lateinit var mGoogleApiClient: GoogleApiClient
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityLoginBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.donthaveaccount.setOnClickListener {
startActivity(Intent(this@loginActivity, MainActivity::class.java))
finish()
}
mAuth = FirebaseAuth.getInstance()
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
mGoogleApiClient = GoogleApiClient.Builder(this)
.enableAutoManage(this) { connectionResult ->
Toast.makeText(this@loginActivity, "Google Service Error", Toast.LENGTH_SHORT)
.show()
}
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build()
binding.loginbtn.setOnClickListener {
val email = binding.emailetlogin.text.toString()
val password = binding.passetlogin.text.toString()
signInWithEmailAndPassword(email, password)
}
}
private fun signInWithEmailAndPassword(email: String, password: String) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
startActivity(Intent(this@loginActivity, HomeActivity::class.java))
finish()
} else {
Toast.makeText(this@loginActivity, "Invalid Email or Password", Toast.LENGTH_SHORT).show()
}
}
}
override fun onStart() {
super.onStart()
if (Firebase.auth.currentUser != null) {
startActivity(Intent(this@loginActivity, HomeActivity::class.java))
finish()
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.